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


Golang securecookie.GenerateRandomKey函数代码示例

本文整理汇总了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)
	}
}
开发者ID:jcarley,项目名称:harbor,代码行数:32,代码来源:authentication.go

示例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
}
开发者ID:jcarley,项目名称:harbor,代码行数:25,代码来源:server.go

示例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/*"))
}
开发者ID:jondavidcody1,项目名称:rtgo,代码行数:25,代码来源:app.go

示例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
}
开发者ID:hlawrenz,项目名称:pgstore,代码行数:31,代码来源:pgstore.go

示例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)
}
开发者ID:kempchee,项目名称:GoEmberWebsockets,代码行数:32,代码来源:server.go

示例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
}
开发者ID:jedwards36,项目名称:web-blog,代码行数:35,代码来源:main.go

示例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

}
开发者ID:astub,项目名称:pfm,代码行数:33,代码来源:routes.go

示例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)
}
开发者ID:pselibas,项目名称:semaphore,代码行数:7,代码来源:config.go

示例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
}
开发者ID:webx-top,项目名称:webx,代码行数:28,代码来源:server.go

示例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
}
开发者ID:leobcn,项目名称:fofou,代码行数:36,代码来源:main.go

示例11: init

func init() {
	authenticationKeyBytes := securecookie.GenerateRandomKey(64)
	defaultConfig["AuthenticationKey"] = string(authenticationKeyBytes)

	encryptionKeyBytes := securecookie.GenerateRandomKey(32)
	defaultConfig["EncryptionKey"] = string(encryptionKeyBytes)
}
开发者ID:gaego,项目名称:session,代码行数:7,代码来源:store.go

示例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,
	}
}
开发者ID:pereztr5,项目名称:cyboard,代码行数:8,代码来源:webHandler.go

示例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))
}
开发者ID:BurntSushi,项目名称:lcmweb,代码行数:8,代码来源:main.go

示例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
}
开发者ID:BurntSushi,项目名称:sqlsess,代码行数:12,代码来源:store.go

示例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
}
开发者ID:KarolBedkowski,项目名称:secproxy,代码行数:15,代码来源:session.go


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