當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。