func register(ctx context, w http.ResponseWriter, r *http.Request) { email := r.PostFormValue("inputEmail") password := r.PostFormValue("inputPassword") salt := securecookie.GenerateRandomKey(32) // salt := "d61162e555f68c3151133351fc908d688aa2bb1e5bab958859290c443eeec0bc" dk, _ := scrypt.Key([]byte(password), salt, 16384, 8, 1, 32) password_hash := fmt.Sprintf("%x", dk) password_salt := fmt.Sprintf("%x", salt) user := models.User{ Username: email, PasswordHash: password_hash, PasswordSalt: password_salt, } fmt.Printf("%+v\n", user) if email == "*****@*****.**" && password == "password" { session, _ := ctx.SessionStore().Get(r, "login") session.Values["username"] = email session.Values["sessionKey"] = string(securecookie.GenerateRandomKey(16)) session.Save(r, w) w.Write([]byte("success")) } else { http.Redirect(w, r, "index.html", 301) } }
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 }
func (a *App) Parse(filepath string) { var ( hashkey []byte blockkey []byte ) file, err := ioutil.ReadFile(filepath) if err != nil { log.Fatal("Could not parse config.json: ", err) } if err := json.Unmarshal(file, a); err != nil { log.Fatal("Error parsing config.json: ", err) } if a.Hashkey == "" { hashkey = securecookie.GenerateRandomKey(16) } else { hashkey = []byte(a.Hashkey) } if a.Blockkey == "" { blockkey = securecookie.GenerateRandomKey(16) } else { blockkey = []byte(a.Blockkey) } a.Scook = securecookie.New(hashkey, blockkey) a.Templates = template.Must(template.ParseGlob("./static/views/*")) }
func (db *PGStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { // Set delete if max-age is < 0 if session.Options.MaxAge < 0 { if err := db.destroy(session); err != nil { return err } http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options)) return nil } if session.ID == "" { // Generate a random session ID key suitable for storage in the DB session.ID = string(securecookie.GenerateRandomKey(32)) session.ID = strings.TrimRight( base32.StdEncoding.EncodeToString( securecookie.GenerateRandomKey(32)), "=") } if err := db.save(session); err != nil { return err } // Keep the session ID key in a cookie so it can be looked up in DB later. encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, db.Codecs...) if err != nil { return err } http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options)) return nil }
func main() { log.Println("Starting Server") log.Println("Starting mongo db session") session, err := mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) finalFormsCollection = session.DB("irsForms").C("finalForms") draftFormsCollection = session.DB("irsForms").C("draftForms") userCollection = session.DB("irsForms").C("users") hashKey = []byte(securecookie.GenerateRandomKey(32)) blockKey = []byte(securecookie.GenerateRandomKey(32)) secureCookieInstance = securecookie.New(hashKey, blockKey) r := mux.NewRouter() r.HandleFunc("/register", RegisterHandler) r.HandleFunc("/sockets", SocketsHandler) r.HandleFunc("/links", getLinksHandler).Methods("GET") r.HandleFunc("/updateLinks", UpdateLinksHandler).Methods("POST") r.HandleFunc("/draft_forms", DraftFormsHandler).Methods("GET") r.HandleFunc("/update_draft_forms", UpdateDraftFormsHandler).Methods("POST") r.HandleFunc("/form_report_items", createFormReportHandler).Methods("GET") r.HandleFunc("/draft_form_report_items", createDraftFormReportHandler).Methods("GET") r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/"))) http.Handle("/", r) log.Println("Listening on 8080") http.ListenAndServe(":8080", nil) }
// reads the configuration file from the path specified by // the config command line flag. func readConfig(configFile string) error { b, err := ioutil.ReadFile(configFile) if err != nil { return err } err = json.Unmarshal(b, &config) if err != nil { return err } cookieAuthKey, err = hex.DecodeString(*config.CookieAuthKeyHexStr) if err != nil { return err } cookieEncrKey, err = hex.DecodeString(*config.CookieEncrKeyHexStr) if err != nil { return err } secureCookie = securecookie.New(cookieAuthKey, cookieEncrKey) // verify auth/encr keys are correct val := map[string]string{ "foo": "bar", } _, err = secureCookie.Encode(cookieName, val) if err != nil { // for convenience, if the auth/encr keys are not set, // generate valid, random value for them auth := securecookie.GenerateRandomKey(32) encr := securecookie.GenerateRandomKey(32) fmt.Printf("auth: %s\nencr: %s\n", hex.EncodeToString(auth), hex.EncodeToString(encr)) } // TODO: somehow verify twitter creds return err }
func NewRouter(db DataHandler) *mux.Router { fe := FrontEnd{DataHandler: db} fe.CookieHandler = securecookie.New(securecookie.GenerateRandomKey(64), securecookie.GenerateRandomKey(32)) fe.CacheOld = true var routes = Routes{ Route{"Index", "GET", "/", Index}, Route{"EventNews", "GET", "/eventnews", EventNewsPage}, Route{"Media", "GET", "/media", MediaPage}, Route{"ExhibitsPage", "GET", "/exhibits", ExhibitsPage}, Route{"Resources", "GET", "/resourcesqq", Resources}, Route{"InfoPage", "GET", "/info", InfoPage}, Route{"GetPosts", "GET", "/get_posts", fe.GetPosts}, Route{"ShowPost", "GET", "/post/{id}", fe.ShowPost}, Route{"ImgUpload", "POST", "/upload_img", ImgUpload}, Route{"AddPost", "POST", "/new_post", fe.NewPost}, Route{"UpdatePost", "POST", "/update_post", fe.UpdatePost}, Route{"DeletePost", "POST", "/delete_postqq/{id}", fe.DeletePost}, } router := mux.NewRouter().StrictSlash(true) for _, route := range routes { router.Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(route.HandlerFunc) } router.PathPrefix("/").Handler(http.FileServer(http.Dir("./www/"))) return router }
func (conf *configType) GenerateCookieSecrets() { hash := securecookie.GenerateRandomKey(32) encryption := securecookie.GenerateRandomKey(32) conf.CookieHash = base64.StdEncoding.EncodeToString(hash) conf.CookieEncryption = base64.StdEncoding.EncodeToString(encryption) }
func NewServer(name string, middlewares ...echo.Middleware) (s *Server) { s = &Server{ Name: name, Apps: make(map[string]*App), apps: make(map[string]*App), DefaultMiddlewares: []echo.Middleware{webxHeader(), mw.Log(), mw.Recover()}, TemplateDir: `template`, Url: `/`, MaxUploadSize: 10 * 1024 * 1024, CookiePrefix: "webx_" + name + "_", CookieHttpOnly: true, } s.InitContext = func(e *echo.Echo) interface{} { return NewContext(s, echo.NewContext(nil, nil, e)) } s.CookieAuthKey = string(codec.GenerateRandomKey(32)) s.CookieBlockKey = string(codec.GenerateRandomKey(32)) s.SessionStoreEngine = `cookie` s.SessionStoreConfig = s.CookieAuthKey s.Codec = codec.New([]byte(s.CookieAuthKey), []byte(s.CookieBlockKey)) s.Core = echo.NewWithContext(s.InitContext) s.URL = NewURL(name, s) s.Core.Use(s.DefaultMiddlewares...) s.Core.Use(middlewares...) servs.Set(name, s) return }
// reads the configuration file from the path specified by // the config command line flag. func readConfig(configFile string) error { b, err := ioutil.ReadFile(configFile) if err != nil { return fmt.Errorf("%s config file doesn't exist. Read readme.md for config instructions", configFile) } err = json.Unmarshal(b, &config) if err != nil { return err } cookieAuthKey, err = hex.DecodeString(*config.CookieAuthKeyHexStr) if err != nil { return err } cookieEncrKey, err = hex.DecodeString(*config.CookieEncrKeyHexStr) if err != nil { return err } secureCookie = securecookie.New(cookieAuthKey, cookieEncrKey) // verify auth/encr keys are correct val := map[string]string{ "foo": "bar", } _, err = secureCookie.Encode(cookieName, val) if err != nil { // for convenience, if the auth/encr keys are not set, // generate valid, random value for them fmt.Printf("CookieAuthKeyHexStr and CookieEncrKeyHexStr are invalid or missing in %q\nYou can use the following random values:\n", configFile) auth := securecookie.GenerateRandomKey(32) encr := securecookie.GenerateRandomKey(32) fmt.Printf("CookieAuthKeyHexStr: %s\nCookieEncrKeyHexStr: %s\n", hex.EncodeToString(auth), hex.EncodeToString(encr)) } // TODO: somehow verify twitter creds return err }
func init() { authenticationKeyBytes := securecookie.GenerateRandomKey(64) defaultConfig["AuthenticationKey"] = string(authenticationKeyBytes) encryptionKeyBytes := securecookie.GenerateRandomKey(32) defaultConfig["EncryptionKey"] = string(encryptionKeyBytes) }
func CreateStore() { Store = sessions.NewCookieStore([]byte(securecookie.GenerateRandomKey(64)), []byte(securecookie.GenerateRandomKey(32))) Store.Options = &sessions.Options{ // Cookie will last for 1 hour MaxAge: 3600, HttpOnly: true, } }
func main() { enc := base64.StdEncoding hashKey := securecookie.GenerateRandomKey(64) blockKey := securecookie.GenerateRandomKey(32) fmt.Printf("hash_key = \"%s\"\n", enc.EncodeToString(hashKey)) fmt.Printf("block_key = \"%s\"\n", enc.EncodeToString(blockKey)) }
func Open(db *sql.DB) (*Store, error) { if _, err := db.Exec(SqlCreateSession); err != nil { return nil, err } s := &Store{ DB: db, hashKey: securecookie.GenerateRandomKey(64), blockKey: securecookie.GenerateRandomKey(32), } return s, nil }
// InitSessionStore initialize sessions support func InitSessionStore(conf *config.AppConfiguration) error { if len(conf.AdminPanel.CookieAuthKey) < 32 { logSession.Info("Random CookieAuthKey") conf.AdminPanel.CookieAuthKey = string(securecookie.GenerateRandomKey(32)) } if len(conf.AdminPanel.CookieEncKey) < 32 { logSession.Info("Random CookieEncKey") conf.AdminPanel.CookieEncKey = string(securecookie.GenerateRandomKey(32)) } store = sessions.NewCookieStore([]byte(conf.AdminPanel.CookieAuthKey), []byte(conf.AdminPanel.CookieEncKey)) return nil }
func StoreEngine(options *echo.SessionOptions) (store Store) { store = ss.StoreEngine(options) if store == nil { cs := cookieStore.New(&cookieStore.CookieOptions{ KeyPairs: [][]byte{ []byte(codec.GenerateRandomKey(32)), []byte(codec.GenerateRandomKey(32)), }, SessionOptions: options, }) cookieStore.Reg(cs) store = cs } return }
func (m *MgoManager) newUser(email, pwd string, app bool) (*User, error) { if !m.Formater.EmailValidate(email) { return nil, authmodel.ErrInvalidEmail } if !m.Formater.PasswordValidate(pwd) { return nil, authmodel.ErrInvalidPassword } u := &User{} u.Id = bson.NewObjectId() sid := u.Id.Hex() u.User.Id = &sid u.Email = &email p, err := hashPwd(pwd) if err != nil { return nil, err } u.Pwd = &p u.Approved = &app if !app { u.ConfirmCodes = map[string]string{ "activate": strings.Trim(base64.URLEncoding. EncodeToString(securecookie.GenerateRandomKey(64)), "="), } } return u, nil }
func init() { godotenv.Load() redisClient = storage.RedisClient(os.Getenv("REDIS_ADDR"), os.Getenv("REDIS_PASS")) translator = t.NewTranslateAdapter( []backend_full.IBackendFull{ backend_full.NewGoogleTranslator(httpclient.GetHttpClient(), os.Getenv("G_TR_KEY")), backend_full.NewYandexTranslator(httpclient.GetHttpClient(), os.Getenv("Y_TR_KEY")), // backend_full.NewBingTranslator(os.Getenv("B_TR_KEY")), }, components.NewChain(2), ) //translator.AddParticular(&particular.AbbyyLingvoLiveTranslator{}) if "" == os.Getenv("APP_SECRET") { os.Setenv("APP_SECRET", string(securecookie.GenerateRandomKey(32))) } cookieStore = &sessions.CookieStore{ Codecs: securecookie.CodecsFromPairs([]byte(os.Getenv("APP_SECRET"))), Options: &sessions.Options{ Path: "/", MaxAge: 86400 * 30 * 10, // Secure:true, HttpOnly: true, }, } }
func init() { RegWithOptions(&CookieOptions{ KeyPairs: [][]byte{ []byte(codec.GenerateRandomKey(32)), []byte(codec.GenerateRandomKey(32)), }, SessionOptions: &echo.SessionOptions{ Name: `GOSESSIONID`, Engine: `cookie`, CookieOptions: &echo.CookieOptions{ Path: `/`, HttpOnly: true, }, }, }) }
// BeforeSave invokes required actions before persisting. func (u *User) BeforeSave(db *gorm.DB) (err error) { if u.Slug == "" { for i := 0; true; i++ { if i == 0 { u.Slug = slugify.Slugify(u.Username) } else { u.Slug = slugify.Slugify( fmt.Sprintf("%s-%d", u.Username, i), ) } notFound := db.Where( "slug = ?", u.Slug, ).Not( "id", u.ID, ).First( &User{}, ).RecordNotFound() if notFound { break } } } if u.Email != "" { email, err := govalidator.NormalizeEmail( u.Email, ) if err != nil { return fmt.Errorf("Failed to normalize email") } u.Email = email } if u.Password != "" { encrypt, err := bcrypt.GenerateFromPassword( []byte(u.Password), bcrypt.DefaultCost, ) if err != nil { return fmt.Errorf("Failed to encrypt password") } u.Hashword = string(encrypt) } if u.Hash == "" { u.Hash = base32.StdEncoding.EncodeToString( securecookie.GenerateRandomKey(32), ) } return nil }
// id returns either the session id from a user's cookie or generates // a fresh one if the cookie is inaccessible or missing. func (s *Store) id(r *http.Request) string { id := s.readCookie(r, CookieIdName) if len(id) == 0 { id = string(securecookie.GenerateRandomKey(64)) } return id }
// Pod transforms the containers in the Yaml to use Pod networking, where every // container shares the localhost connection. func Pod(c *yaml.Config) error { rand := base64.RawURLEncoding.EncodeToString( securecookie.GenerateRandomKey(8), ) ambassador := &yaml.Container{ ID: fmt.Sprintf("drone_ambassador_%s", rand), Name: "ambassador", Image: "busybox:latest", Detached: true, Entrypoint: []string{"/bin/sleep"}, Command: []string{"86400"}, Volumes: []string{c.Workspace.Path, c.Workspace.Base}, Environment: map[string]string{}, } network := fmt.Sprintf("container:%s", ambassador.ID) var containers []*yaml.Container containers = append(containers, c.Pipeline...) containers = append(containers, c.Services...) for _, container := range containers { container.VolumesFrom = append(container.VolumesFrom, ambassador.ID) if container.Network == "" { container.Network = network } } c.Services = append([]*yaml.Container{ambassador}, c.Services...) return nil }
// GetAuthURL starts the authentication process with the requested provided. // It will return a URL that should be used to send users to. // // I would recommend using the BeginAuth instead of doing all of these steps // yourself. func GetAuthURL(providerName string, w http.ResponseWriter, r *http.Request) (string, error) { provider, err := goth.GetProvider(providerName) if err != nil { return "", err } state := base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(stateLen * 3 / 4)) sess, err := provider.BeginAuth(state) if err != nil { return "", err } url, err := sess.GetAuthURL() if err != nil { return "", err } encoded, err := securecookie.EncodeMulti(CookieName, state+sess.Marshal(), codecs...) if err != nil { return "", err } http.SetCookie(w, cookie(CookieName, encoded, &CookieOptions)) return url, err }
// Save adds a single session to the response. // // If the Options.MaxAge of the session is <= 0 then the session file will be // deleted from the store path. With this process it enforces the properly // session cookie handling so no need to trust in the cookie management in the // web browser. func (s *FilesystemStore) Save(r *http.Request, w http.ResponseWriter, session *Session) error { // Delete if max-age is <= 0 if session.Options.MaxAge <= 0 { if err := s.erase(session); err != nil { return err } http.SetCookie(w, NewCookie(session.Name(), "", session.Options)) return nil } if session.ID == "" { // Because the ID is used in the filename, encode it to // use alphanumeric characters only. session.ID = strings.TrimRight( base32.StdEncoding.EncodeToString( securecookie.GenerateRandomKey(32)), "=") } if err := s.save(session); err != nil { return err } encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, s.Codecs...) if err != nil { return err } http.SetCookie(w, NewCookie(session.Name(), encoded, session.Options)) return nil }
// Save adds a single session to the response. func (s *SentinelFailoverStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { if session.Options.MaxAge < 0 { if err := s.delete(session); err != nil { return err } http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options)) return nil } if session.ID == "" { // Because the ID is not initialized when newly created, encode it to // use alphanumeric characters only. session.ID = strings.TrimRight( base32.StdEncoding.EncodeToString( securecookie.GenerateRandomKey(32)), "=") } if err := s.save(session); err != nil { return err } encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, s.Codecs...) if err != nil { return err } http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options)) return nil }
// Generate generates a new token func (d *DefaultCSRFGenerator) Generate(actionID string) string { if _, ok := d.Session.Get(CsrfSessionKey).(string); !d.Session.Has(CsrfSessionKey) || !ok { d.Session.Set(CsrfSessionKey, base64.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(16))) } t := xsrftoken.Generate(d.Secret, d.Session.Get(CsrfSessionKey).(string), actionID) return t }
// Return the session, the old XSRF token and an error if needed func getSession(req *http.Request, w http.ResponseWriter) (*sessions.Session, []uint8, error) { session, _ := dStore.Get(req, conf.SESSION_NAME) session.Options = &sessions.Options{ Path: "/", MaxAge: 7 * 24 * 60 * 60, // 7 days } var oldtoken []uint8 if session.Values["xsrf"] != nil { oldtoken = session.Values["xsrf"].([]uint8) } token := securecookie.GenerateRandomKey(32) session.Values["xsrf"] = token encoded, err := securecookie.EncodeMulti("XSRF-TOKEN", token, xsrfCodecs...) if err != nil { return nil, nil, fmt.Errorf("encode token failed: %s", err) } http.SetCookie(w, &http.Cookie{ Name: "XSRF-TOKEN", Value: encoded, Path: "/", }) return session, oldtoken, nil }
func NewWeb(mailConf *conf.MailConf, debug bool) *MailWeb { var web *MailWeb = new(MailWeb) web.mconf = mailConf web.debug = debug web.userTimeout = 86400 // 1 day store := sessions.NewCookieStore(securecookie.GenerateRandomKey(128)) // 1) Set a maximum age for the client-side cookies (forces a session timeout afterwards) store.Options(sessions.Options{MaxAge: int(web.userTimeout)}) web.martini = martini.Classic() web.martini.Use(render.Renderer(render.Options{ Directory: "static/templates", Extensions: []string{".html"}, })) web.martini.Use(sessions.Sessions("watneySession", store)) web.martini.Use(sessionauth.SessionUser(auth.GenerateAnonymousUser)) sessionauth.RedirectUrl = "/sessionTimeout" sessionauth.RedirectParam = "next" // 2) Register a cleanup go routine that checks every x minutes, for outdated users, which // simply left the page without logging out web.registerUserCleanup(30) // x) Define and set all handlers web.initHandlers() return web }
// newUser create an *auth.User without save it to database. // Its set an BSON ObjectID and check email,password. func (m *MgoUserManager) newUser(email, pwd string, app bool) (*auth.User, error) { if !m.Formater.EmailValidate(email) { return nil, auth.ErrInvalidEmail } if !m.Formater.PasswordValidate(pwd) { return nil, auth.ErrInvalidPassword } u := &auth.User{} u.Id = bson.NewObjectId() u.Email = email u.LastActivity = time.Now() u.Info.JoinDay = u.LastActivity p, err := auth.HashPwd(pwd) if err != nil { return nil, err } u.Pwd = p u.Approved = app if !app { u.ConfirmCodes = map[string]string{ "activate": base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(64)), } } return u, nil }
func (s *RedisStore) save(session *sessions.Session) error { encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, s.Codecs...) if err != nil { return err } c := s.storeHandler.GetRedisConnection() defer c.Close() if session.ID == "" { // Because the ID is used in the filename, encode it to // use alphanumeric characters only. session.ID = strings.TrimRight(base32.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)), "=") } c.Send("SET", "morioka_sess_"+session.ID, encoded) if err = c.Flush(); err != nil { return err } if _, err = c.Receive(); err != nil { return err } c.Send("EXPIRE", "morioka_sess_"+session.ID, 86400) if err = c.Flush(); err != nil { return err } if _, err = c.Receive(); err != nil { return err } return nil }