当前位置: 首页>>代码示例>>Golang>>正文


Golang sessions.NewCookieStore函数代码示例

本文整理汇总了Golang中github.com/gorilla/sessions.NewCookieStore函数的典型用法代码示例。如果您正苦于以下问题:Golang NewCookieStore函数的具体用法?Golang NewCookieStore怎么用?Golang NewCookieStore使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewCookieStore函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NewCookie

func NewCookie(kvdb *bolt.DB) (*sessions.CookieStore, error) {
	var secret []byte

	// Create cookie secret if one does not exist.
	err := kvdb.Update(func(tx *bolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists([]byte("cookie"))
		if err != nil {
			return err
		}

		secret = bucket.Get([]byte("secret"))
		if len(secret) == 0 {
			secret = []byte(uuid.New())
			err = bucket.Put([]byte("secret"), secret)
		}

		return err
	})

	if err != nil {
		return nil, err
	}

	if len(secret) == 0 {
		return nil, errors.New("Cookie secret cannot be empty.")
	}

	return sessions.NewCookieStore(secret), nil
}
开发者ID:sandeepone,项目名称:chillax,代码行数:29,代码来源:cookie.go

示例2: initSession

func initSession() {

	gob.Register(UserPermission(0))

	SessionStorage = sessions.NewCookieStore([]byte( /*NewHashString()*/ "main-session-storage"))
	SessionStorage.MaxAge(86400 * 3) //3 days
}
开发者ID:mshockwave,项目名称:nthuaplus-backend,代码行数:7,代码来源:public.go

示例3: init

func init() {
	key := []byte(os.Getenv("SESSION_SECRET"))
	if string(key) == "" {
		fmt.Println("goth/gothic: no SESSION_SECRET environment variable is set. The default cookie store is not available and any calls will fail. Ignore this warning if you are using a different store.")
	}
	Store = sessions.NewCookieStore([]byte(key))
}
开发者ID:oyvindsk,项目名称:goth,代码行数:7,代码来源:gothic.go

示例4: NewServer

func NewServer(conf *ServerConf) *server {
	if conf.Name == "" {
		conf.Name = "server"
	}
	if conf.Port == 0 {
		conf.Port = DEFAULT_PORT
	}
	if conf.SessionSecret == "" {
		conf.SessionSecret = DEFAULT_SESSION_SECRET
	}

	self := &server{conf: conf}

	self.serverMux = http.NewServeMux()
	self.server = &graceful.Server{
		Timeout: 500 * time.Millisecond,

		Server: &http.Server{
			Addr:    ":" + self.getPortStr(),
			Handler: self.LogMiddleware(context.ClearHandler(self.serverMux)),
		},
	}
	self.server.SetKeepAlivesEnabled(false) // FIXME
	self.cookieStore = sessions.NewCookieStore([]byte(self.conf.SessionSecret))

	self.setupHandlers()
	fs := http.FileServer(http.Dir(self.conf.StaticDir))
	self.serverMux.Handle(self.conf.StaticUrl, http.StripPrefix("", fs))
	self.setupLogging()

	self.genPaths = make(map[string]*genpath.GenPath)
	return self
}
开发者ID:igorcoding,项目名称:shortest-path,代码行数:33,代码来源:server.go

示例5: Init

//Init initializes the session store
//this reads and sets the auth and encryption keys for session cookie
//throw errors so app is not usable if auth or encrypt keys are missing
func Init() error {
	//get the auth and encypt keys from files
	aKey, err0 := ioutil.ReadFile(authKeyPath)
	eKey, err1 := ioutil.ReadFile(encryptKeyPath)
	if err0 != nil {
		initError = err0
		return err0
	} else if err1 != nil {
		initError = err1
		return err1
	}

	//assign to package variables
	authKey = aKey
	encryptKey = eKey

	//init the session store
	s := sessions.NewCookieStore(
		authKey,
		encryptKey,
	)

	//set session options
	s.Options = options

	//store sessions to global variable
	Store = s

	//done
	return nil
}
开发者ID:coreymgilmore,项目名称:stripe-appengine-frontend,代码行数:34,代码来源:sessionutils.go

示例6: init

func init() {
	if cfg.VersionAndQuit {
		fmt.Printf("cloudkeys-go %s\n", version)
		os.Exit(0)
	}

	if _, err := cfg.ParsedStorage(); err != nil {
		fmt.Printf("ERR: Please provide a valid storage URI\n")
		os.Exit(1)
	}

	if cfg.CookieSigningKey == "" {
		cfg.CookieSigningKey = uuid.NewV4().String()[:32]
		fmt.Printf("WRN: cookie-authkey was set randomly, this will break your sessions!\n")
	}

	if cfg.CookieEncryptKey == "" {
		cfg.CookieEncryptKey = uuid.NewV4().String()[:32]
		fmt.Printf("WRN: cookie-encryptkey was set randomly, this will break your sessions!\n")
	}

	cookieStore = sessions.NewCookieStore(
		[]byte(cfg.CookieSigningKey),
		[]byte(cfg.CookieEncryptKey),
	)
}
开发者ID:Luzifer,项目名称:cloudkeys-go,代码行数:26,代码来源:main.go

示例7: SetUpSuite

func (s *S) SetUpSuite(c *C) {
	s.srv = httptest.NewServer(APIHandler(&Config{
		SessionStore:  sessions.NewCookieStore([]byte("session-secret")),
		LoginToken:    testLoginToken,
		ControllerKey: testControllerKey,
	}))
}
开发者ID:ably-forks,项目名称:flynn,代码行数:7,代码来源:api_test.go

示例8: TestClear

func TestClear(t *testing.T) {
	var cookieName = "test"

	// Create a cookiestore
	store := sessions.NewCookieStore([]byte("secret-key"))

	// Create the recorder
	w := httptest.NewRecorder()

	// Create the request
	r := fakeGet()

	// Get the session
	sess, err := store.Get(r, cookieName)
	if err != nil {
		t.Fatalf("Error getting session: %v", err)
	}

	// Generate a token
	Token(w, r, sess)

	// Clear the token
	Clear(w, r, sess)

	if _, ok := sess.Values[TokenName]; ok {
		t.Errorf("StringMap should not exist: expected %v, got %v", nil, reflect.TypeOf(sess.Values[TokenName]))
	}
}
开发者ID:vonwenm,项目名称:csrfbanana,代码行数:28,代码来源:token_test.go

示例9: TestCSRFTokenBackend

func TestCSRFTokenBackend(t *testing.T) {
	var cookieName = "test"

	// Create a cookiestore
	store := sessions.NewCookieStore([]byte("secret-key"))

	// Create the recorder
	w := httptest.NewRecorder()

	// Create the handler
	h := New(http.HandlerFunc(successHandler), store, cookieName)

	// Create the form
	form := url.Values{}

	// Create the POST request
	req, err := http.NewRequest("POST", "http://localhost/", bytes.NewBufferString(form.Encode()))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// Run the page
	h.ServeHTTP(w, req)

	if w.Code == 200 {
		t.Errorf("The request should have failed, but it didn't. Instead, the code was %d",
			w.Code)
	}
}
开发者ID:vonwenm,项目名称:csrfbanana,代码行数:30,代码来源:csrfbanana_test.go

示例10: TestMatch

func TestMatch(t *testing.T) {
	var cookieName = "test"

	// Create a cookiestore
	store := sessions.NewCookieStore([]byte("secret-key"))

	// Create the form
	token := "123456"
	form := url.Values{}
	form.Set(TokenName, token)

	// Create the POST request
	req, err := http.NewRequest("POST", "http://localhost/", bytes.NewBufferString(form.Encode()))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// Get the session
	sess, err := store.Get(req, cookieName)
	if err != nil {
		t.Fatalf("Error getting session: %v", err)
	}

	// Set the values in the session manually
	sess.Values[TokenName] = make(StringMap)
	sess.Values[TokenName].(StringMap)["/"] = "123456"

	if ok := match(req, sess, true); !ok {
		t.Error("Tokens do not match")
	}
}
开发者ID:vonwenm,项目名称:csrfbanana,代码行数:32,代码来源:token_test.go

示例11: TestToken

func TestToken(t *testing.T) {
	var cookieName = "test"
	TokenName = "foo"

	// Create a cookiestore
	store := sessions.NewCookieStore([]byte("secret-key"))

	// Create the recorder
	w := httptest.NewRecorder()

	// Create the request
	r := fakeGet()

	// Get the session
	sess, err := store.Get(r, cookieName)
	if err != nil {
		t.Fatalf("Error getting session: %v", err)
	}

	token := Token(w, r, sess)

	if token != sess.Values[TokenName].(StringMap)["/"] {
		t.Errorf("Tokens do not match: expected %v, got %v", sess.Values[TokenName], token)
	}

	// Reset the token name
	TokenName = "token"
}
开发者ID:vonwenm,项目名称:csrfbanana,代码行数:28,代码来源:token_test.go

示例12: TestFlash

func TestFlash(t *testing.T) {
	codecKey1 := "ePAPW9vJv7gHoftvQTyNj5VkWB52mlza"
	codecKey2 := "N8SmpJ00aSpepNrKoyYxmAJhwVuKEWZD"
	jar, err := cookiejar.New(nil)
	if err != nil {
		t.Error(err)
	}
	client := &http.Client{Jar: jar}
	o := &router.Options{
		Log:          logger.NewDefaultLogger(os.Stdout),
		SessionStore: sessions.NewCookieStore([]byte(codecKey1), []byte(codecKey2)),
	}
	r := router.NewRouter(o)
	r.Add(NewFlashTest)
	ts := httptest.NewServer(r)
	defer ts.Close()
	_, err = client.Get(fmt.Sprintf("%s/", ts.URL))
	if err != nil {
		t.Error(err)
	}
	_, err = client.Get(fmt.Sprintf("%s/flash", ts.URL))
	if err != nil {
		t.Error(err)
	}

	if len(result) != 3 {
		t.Errorf("expected 3 got %d", len(result))
	}
}
开发者ID:gernest,项目名称:utron,代码行数:29,代码来源:flash_test.go

示例13: New

// New is the constructor for Application struct.
func New() (*Application, error) {
	u, err := libunix.CurrentUser()
	if err != nil {
		return nil, err
	}

	dsn := libenv.EnvWithDefault("RESOURCED_MASTER_DSN", fmt.Sprintf("postgres://%[email protected]:5432/resourced-master?sslmode=disable", u))

	db, err := sqlx.Connect("postgres", dsn)
	if err != nil {
		return nil, err
	}

	// As a user, you must provide your own secret
	// But make sure you keep using the same one, otherwise sessions will expire.
	cookieStoreSecret := libenv.EnvWithDefault("RESOURCED_MASTER_COOKIE_SECRET", "T0PS3CR3T")

	app := &Application{}
	app.Addr = libenv.EnvWithDefault("RESOURCED_MASTER_ADDR", ":55655")
	app.dsn = dsn
	app.db = db
	app.cookieStore = sessions.NewCookieStore([]byte(cookieStoreSecret))
	app.WSTraffickers = wstrafficker.NewWSTraffickers()

	return app, err
}
开发者ID:simudream,项目名称:resourced-master,代码行数:27,代码来源:application.go

示例14: TestNewSession

func TestNewSession(t *testing.T) {
	store := sessions.NewCookieStore([]byte("secret"))
	fn := func(c web.C, w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	}
	mux := web.New()
	mux.Handle("/*", fn)
	mux.Use(Middleware("session", store))
	ts := httptest.NewServer(context.ClearHandler(mux))
	defer ts.Close()

	var err error

	var resp *http.Response
	resp, err = http.Get(ts.URL)
	if err != nil {
		t.Fatal(err)
	}

	cookie := resp.Header.Get("Set-Cookie")
	t.Logf("Set-Cookie: %v", cookie)
	if cookie == "" {
		t.Fatal("\"Set-Cookie\" header missing")
	}

	matches := sessionPattern.FindStringSubmatch(cookie)
	if len(matches) != 2 {
		t.Fatal("session cookie missing")
	}
}
开发者ID:faultier,项目名称:goji-session,代码行数:30,代码来源:middleware_test.go

示例15: TestStatusHandle

func TestStatusHandle(t *testing.T) {
	jar := sessions.NewCookieStore([]byte("secret key"))
	statusHandle := statusHandler(jar)
	test := GenerateHandleTester(t, statusHandle)

	// Check that status failed without a user logged in
	w := test("GET", "")
	if w.Code != http.StatusForbidden {
		t.Errorf(
			"GET /status returned %v. Expected %v",
			w.Code,
			http.StatusForbidden,
		)
	}

	// Check succeeds when a user is logged in
	req, err := http.NewRequest("GET", "", nil)
	if err != nil {
		t.Errorf("%v", err)
	}
	w = httptest.NewRecorder()
	session, _ := jar.Get(req, "carton-session")
	session.Values["user"] = "test user"
	session.Save(req, w)
	statusHandle.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Errorf(
			"GET /status with user returned %v. Expected %v",
			w.Code,
			http.StatusOK,
		)
	}
}
开发者ID:vichetuc,项目名称:carton,代码行数:34,代码来源:auth_test.go


注:本文中的github.com/gorilla/sessions.NewCookieStore函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。