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 }
func initSession() { gob.Register(UserPermission(0)) SessionStorage = sessions.NewCookieStore([]byte( /*NewHashString()*/ "main-session-storage")) SessionStorage.MaxAge(86400 * 3) //3 days }
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)) }
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 }
//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 }
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), ) }
func (s *S) SetUpSuite(c *C) { s.srv = httptest.NewServer(APIHandler(&Config{ SessionStore: sessions.NewCookieStore([]byte("session-secret")), LoginToken: testLoginToken, ControllerKey: testControllerKey, })) }
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])) } }
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) } }
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") } }
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" }
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)) } }
// 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://%v@localhost: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 }
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") } }
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"] = "******" 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, ) } }
// NewApplication is the constructor for Application struct. // // If testing is true, connects to the "test" database. func NewApplication(testing bool) (*Application, error) { u, err := libunix.CurrentUser() if err != nil { return nil, err } dbname := "forty-thieves" if testing { dbname += "-test" } dsn := libenv.EnvWithDefault( "DSN", fmt.Sprintf("postgres://%v@localhost:5432/%s?sslmode=disable", u, dbname)) db, err := sqlx.Connect("postgres", dsn) if err != nil { return nil, err } cookieStoreSecret := libenv.EnvWithDefault("COOKIE_SECRET", "ittwiP92o0oi6P4i") app := &Application{} app.dsn = dsn app.db = db app.cookieStore = sessions.NewCookieStore([]byte(cookieStoreSecret)) return app, err }
func init() { //Changed by William: use a config file instead of an environment variable key, err := ioutil.ReadFile(SESSION_SECRET_CONFIG_FILE_PATH) if err != nil { log.Println("could not load session secret from file ", SESSION_SECRET_CONFIG_FILE_PATH) log.Println(err) //TODO delete these lines, when I know this will never be used. // key, err = os.Getenv("SESSION_SECRET") // if err != nil { // log.Println("could not load session secret from " + // "environment variable SESSION_SECRET.\nUsing a hard-coded value. " + // "This should be removed from production code.") // log.Println(err) // key = "aFakeTemporarySecret" // } } keySet = len(key) != 0 Store = sessions.NewCookieStore([]byte(key)) Store.Options = &sessions.Options{ Path: "/", MaxAge: 60 * SESSION_DURATION_MINUTES, HttpOnly: true, Secure: true, } defaultStore = Store }
// Create a new server with session configuration and service registry func New(sessionName, sessionSecret string, services map[string]*url.URL, public bool) *Server { srv := &Server{ sessionName: sessionName, sessionSecret: sessionSecret, sessionStore: sessions.NewCookieStore([]byte(sessionSecret)), services: services, public: public, } // Proxy services prx := proxy.New(srv.services, srv.isAuth) http.Handle("/prx/", http.StripPrefix("/prx", prx)) // Login handle http.HandleFunc("/oauth/", srv.oauthCallback) // Static GUI http.Handle("/", http.FileServer(http.Dir("./public"))) log.Info("Handling web GUI on /") log.Info("Handling proxying to services on /prx/") return srv }
func NewRouter() http.Handler { // Setup session store authKey := securecookie.GenerateRandomKey(64) encryptionKey := securecookie.GenerateRandomKey(32) store := sessions.NewCookieStore( authKey, encryptionKey, ) appContext := &ctx{ sessionStore: store, } router := mux.NewRouter() // Setup the WS Hub here // Add handlers for routes router.Handle("/signup", http.RedirectHandler("/signup.html", 307)).Methods("GET") router.Handle("/signin", appHandler{appContext, signIn}).Methods("POST") // Add handlers for websockets return router }
// Create a new fogo app. Uses the config object. func NewFogoApp(c *Config) *Fogo { if c == nil { c = DefaultConfig() } tplFuncs := make(map[string]interface{}) tplFuncs["url_for"] = UrlFor tplFuncs["host"] = Host tplFuncs["marshal"] = Marshal keys := make([][]byte, 0) for _, key := range c.SessionKeys { keys = append(keys, []byte(key)) } fogo := &Fogo{ config: c, router: mux.NewRouter(), subRoutes: make(map[string]*mux.Router), tplFuncs: tplFuncs, session: sessions.NewCookieStore(keys...), beforeMiddleware: make([]FogoMiddleware, 0), afterMiddleware: make([]FogoMiddleware, 0), notFoundHandler: nil, defaultErrorHandler: nil, logger: newDefaultLogger(), templateCache: make(map[string]*template.Template), } fogo.router.NotFoundHandler = fogo return fogo }
func NewCookieJar(w http.ResponseWriter, r *http.Request, keypairs ...[]byte) *CookieJar { cj := new(CookieJar) cj.cookieStore = sessions.NewCookieStore(keypairs...) cj.w = w cj.r = r return cj }
func main() { store = sessions.NewCookieStore([]byte("this-is-super-secret")) // securecookie.GenerateRandomKey(32), // securecookie.GenerateRandomKey(32)) store.Options.HttpOnly = true store.Options.Secure = true clients = make(map[string]*imap.Client) m := pat.New() m.Get("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) m.Get("/login", handler(LoginForm)) m.Post("/login", handler(LoginHandler)) m.Get("/logout", handler(Logout)) m.Get("/mail", handler(InboxHandler)) m.Get("/mail/messages/", handler(MessagesHandler)) m.Get("/mail/message/:id", handler(MessageHandler)) m.Get("/mail/attachment/:msg/:id", handler(AttachmentHandler)) m.Post("/mail/archive/:id", handler(ArchiveHandler)) m.Post("/mail/delete/:id", handler(DeleteHandler)) m.Get("/", handler(root)) http.Handle("/", m) http.ListenAndServeTLS(":5000", "certs/newcert.pem", "certs/privkey.pem", nil) }
func main() { // Create cookie store Store = sessions.NewCookieStore([]byte("This is super screen...")) Store.Options = &sessions.Options{ //Domain: "localhost", // Chrome doesn't work with localhost domain Path: "/", MaxAge: 3600 * 8, // 8 hours HttpOnly: true, } // Default handler h := http.HandlerFunc(routeLogin) // Prevents CSRF cs := csrfbanana.New(h, Store, SessionName) // Set error page for CSRF cs.FailureHandler(http.HandlerFunc(routeInvalidToken)) // Generate a new token after each check (also prevents double submits) cs.ClearAfterUsage(true) // Exclude /static/ from tokens (even though we don't have a static file handler...) cs.ExcludeRegexPaths([]string{"/static(.*)"}) // Optional - set the token length csrfbanana.TokenLength = 32 // Optional - set the token name used in the forms csrfbanana.TokenName = "token" fmt.Println("Listening on http://localhost:80/") http.ListenAndServe(":8080", cs) }
func (application *Application) Init(APISecret string, baseURL string, cookieSecret string, cookieSecure bool, DBHost string, DBName string, DBPassword string, DBPort string, DBUser string) { hash := sha256.New() io.WriteString(hash, cookieSecret) application.Store = sessions.NewCookieStore(hash.Sum(nil)) application.Store.Options = &sessions.Options{ Path: "/", HttpOnly: true, Secure: cookieSecure, } application.DbMap = models.GetDbMap( APISecret, baseURL, DBUser, DBPassword, DBHost, DBPort, DBName) application.CsrfProtection = &CsrfProtection{ Key: CSRFKey, Cookie: CSRFCookie, Header: CSRFHeader, Secure: cookieSecure, } application.APISecret = APISecret }
func (application *Application) Init(filename *string) { config, err := toml.LoadFile(*filename) if err != nil { glog.Fatalf("TOML load failed: %s\n", err) } hash := sha256.New() io.WriteString(hash, config.Get("cookie.mac_secret").(string)) application.Store = sessions.NewCookieStore(hash.Sum(nil)) application.Store.Options = &sessions.Options{ Path: "/", HttpOnly: true, Secure: config.Get("cookie.secure").(bool), } dbConfig := config.Get("database").(*toml.TomlTree) application.DbMap = models.GetDbMap( dbConfig.Get("user").(string), dbConfig.Get("password").(string), dbConfig.Get("hostname").(string), dbConfig.Get("port").(string), dbConfig.Get("database").(string)) application.CsrfProtection = &CsrfProtection{ Key: config.Get("csrf.key").(string), Cookie: config.Get("csrf.cookie").(string), Header: config.Get("csrf.header").(string), Secure: config.Get("cookie.secure").(bool), } application.Config = config }
func InitHandlers() { initCodeBaseDir() // Register datatypes such that it can be saved in the session. gob.Register(SessionUserKey(0)) gob.Register(&User{}) // Initialize XSRF token key. xsrfKey = "My personal very secure XSRF token key" sessKey := []byte("secure-key-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa") // Create a session cookie store. cookieStore = sessions.NewCookieStore( sessKey[:64], sessKey[:32], ) cookieStore.Options = &sessions.Options{ MaxAge: maxSessionIDAge, // Session valid for 30 Minutes. HttpOnly: true, } // Create identity toolkit client. c := &gitkit.Config{ ServerAPIKey: getConfig(siteName, "serverAPIKey"), ClientID: getConfig(siteName, "clientID"), WidgetURL: WidgetSigninAuthorizedRedirectURL, } // Service account and private key are not required in GAE Prod. // GAE App Identity API is used to identify the app. if appengine.IsDevAppServer() { c.ServiceAccount = getConfig(siteName, "serviceAccount") c.PEMKeyPath = privateKeyPath } var err error gitkitClient, err = gitkit.New(c) if err != nil { log.Fatal(err) } // The gorilla sessions use gorilla request context ClearHandler := func(fc http.HandlerFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer gorillaContext.Clear(r) fc(w, r) }) } http.Handle(homeURL, ClearHandler(handleHome)) http.Handle(WidgetSigninAuthorizedRedirectURL, ClearHandler(handleWidget)) http.Handle(signOutURL, ClearHandler(handleSignOut)) http.Handle(signinLandingDefaultURL, ClearHandler(handleSigninSuccessLanding)) http.Handle(signoutLandingDefaultURL, ClearHandler(handleSignOutLanding)) http.HandleFunc(accountChooserBrandingURL, accountChooserBranding) }
func main() { // configure the github oauth parameters config := &auth.GitHubConfig{ &auth.Config{ ClientID: os.Getenv("GITHUB_CLIENT_ID"), ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"), CallbackURL: os.Getenv("GITHUB_CALLBACK_URL"), }, } auth.SetGitHubConfig(config) // setup a store, in our case one using secure cookies store := sessions.NewCookieStore([]byte("something-very-secret")) s := auth.NewServer(store) // configure a mux r := mux.NewRouter() r.PathPrefix(auth.PathPrefix).Handler(s.GetMux()) // add a wrapper to check the session for each request o := auth.CheckSession(r, store) // listen to the network http.ListenAndServe(":5000", o) }
// Initialize collects server-side credential from environment variables and prepare for authentication with Github OAuth. // // Client authentication is disabled and CurrentUser always returns "anonymous" if any of the environment variables are missing. func Initialize(anynomous User, cookieSecret []byte) { store = sessions.NewCookieStore(cookieSecret) githubCallbackURL = os.Getenv("GITHUB_CALLBACK_URL") cred := struct { githubRandomHashKey string githubOmniauthID string githubOmniauthKey string }{ os.Getenv("GITHUB_RANDOM_HASH_KEY"), os.Getenv("GITHUB_OMNI_AUTH_ID"), os.Getenv("GITHUB_OMNI_AUTH_KEY"), } defaultUser = anynomous if cred.githubRandomHashKey == "" || cred.githubOmniauthID == "" || cred.githubOmniauthKey == "" || githubCallbackURL == "" { log.Printf( "Missing one or more Gomniauth Environment Variables: Running with with limited functionality! \n githubRandomHashKey [%s] \n githubOmniauthID [%s] \n githubOmniauthKey[%s] \n githubCallbackURL[%s]", cred.githubRandomHashKey, cred.githubOmniauthID, cred.githubOmniauthKey, githubCallbackURL, ) enabled = false return } githubCallbackURL = path.Join(githubCallbackURL, "/auth/github/callback") gomniauth.SetSecurityKey(cred.githubRandomHashKey) gomniauth.WithProviders( githubOauth.New(cred.githubOmniauthID, cred.githubOmniauthKey, githubCallbackURL), ) enabled = true }
// create a new http based frontend func NewHTTPFrontend(daemon *NNTPDaemon, config map[string]string, url string) Frontend { var front httpFrontend front.daemon = daemon front.regenBoardTicker = time.NewTicker(time.Second * 10) front.ukkoTicker = time.NewTicker(time.Second * 30) front.regenBoard = make(map[string]groupRegenRequest) front.attachments = mapGetInt(config, "allow_files", 1) == 1 front.bindaddr = config["bind"] front.name = config["name"] front.webroot_dir = config["webroot"] front.static_dir = config["static_files"] front.template_dir = config["templates"] front.prefix = config["prefix"] front.regen_on_start = config["regen_on_start"] == "1" front.regen_threads = mapGetInt(config, "regen_threads", 1) front.store = sessions.NewCookieStore([]byte(config["api-secret"])) front.store.Options = &sessions.Options{ // TODO: detect http:// etc in prefix Path: front.prefix, MaxAge: 600, } front.postchan = make(chan NNTPMessage, 16) front.recvpostchan = make(chan NNTPMessage, 16) front.regenThreadChan = make(chan ArticleEntry, 16) front.regenGroupChan = make(chan groupRegenRequest, 8) return front }
// Initialize collects server-side credential from environment variables and prepare for authentication with Github OAuth. // // Client authentication is disabled and CurrentUser always returns "anonymous" if any of the environment variables are missing. func Initialize(anynomous User, cookieSecret []byte) { store = sessions.NewCookieStore(cookieSecret) githubCallbackBase = os.Getenv("GITHUB_CALLBACK_URL") cred := struct { githubRandomHashKey string githubOmniauthID string githubOmniauthKey string }{ os.Getenv("GITHUB_RANDOM_HASH_KEY"), os.Getenv("GITHUB_OMNI_AUTH_ID"), os.Getenv("GITHUB_OMNI_AUTH_KEY"), } defaultUser = anynomous if cred.githubRandomHashKey == "" || cred.githubOmniauthID == "" || cred.githubOmniauthKey == "" || githubCallbackBase == "" { glog.Warningf( "Missing one or more Gomniauth Environment Variables: Running with with limited functionality! \n GITHUB_RANDOM_HASH_KEY [%s] \n GITHUB_OMNI_AUTH_ID [%s] \n GITHUB_OMNI_AUTH_KEY [%s] \n GITHUB_CALLBACK_URL [%s]", cred.githubRandomHashKey, cred.githubOmniauthID, cred.githubOmniauthKey, githubCallbackBase, ) enabled = false return } url := fmt.Sprintf("%s/auth/github/callback", githubCallbackBase) gomniauth.SetSecurityKey(cred.githubRandomHashKey) gomniauth.WithProviders( githubOauth.New(cred.githubOmniauthID, cred.githubOmniauthKey, url), ) glog.Infof("Enabled authentication by github OAuth2") enabled = true }