• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang securecookie.GenerateRandomKey函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/gorilla/securecookie.GenerateRandomKey函数的典型用法代码示例。如果您正苦于以下问题:Golang GenerateRandomKey函数的具体用法?Golang GenerateRandomKey怎么用?Golang GenerateRandomKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GenerateRandomKey函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: StoreEngine

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


示例17: newUser

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
}
开发者ID:kidstuff,项目名称:auth-mongo-mngr,代码行数:32,代码来源:user.go


示例18: init

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


示例19: init

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,
			},
		},
	})
}
开发者ID:webx-top,项目名称:echo,代码行数:16,代码来源:cookie.go


示例20: BeforeSave

// 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:umschlag,项目名称:umschlag-api,代码行数:61,代码来源:user.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang securecookie.New函数代码示例发布时间:2022-05-23
下一篇:
Golang securecookie.EncodeMulti函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap