本文整理汇总了Golang中github.com/gorilla/securecookie.GenerateRandomKey函数的典型用法代码示例。如果您正苦于以下问题:Golang GenerateRandomKey函数的具体用法?Golang GenerateRandomKey怎么用?Golang GenerateRandomKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GenerateRandomKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: register
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 == "[email protected]" && 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)
}
}
示例2: NewRouter
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
}
示例3: Parse
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/*"))
}
示例4: Save
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
}
示例5: main
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)
}
示例6: readConfig
// 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
}
示例7: NewRouter
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
}
示例8: GenerateCookieSecrets
func (conf *configType) GenerateCookieSecrets() {
hash := securecookie.GenerateRandomKey(32)
encryption := securecookie.GenerateRandomKey(32)
conf.CookieHash = base64.StdEncoding.EncodeToString(hash)
conf.CookieEncryption = base64.StdEncoding.EncodeToString(encryption)
}
示例9: NewServer
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
}
示例10: readConfig
// 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
}
示例11: init
func init() {
authenticationKeyBytes := securecookie.GenerateRandomKey(64)
defaultConfig["AuthenticationKey"] = string(authenticationKeyBytes)
encryptionKeyBytes := securecookie.GenerateRandomKey(32)
defaultConfig["EncryptionKey"] = string(encryptionKeyBytes)
}
示例12: CreateStore
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,
}
}
示例13: main
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))
}
示例14: Open
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
}
示例15: InitSessionStore
// 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
}