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

Golang securecookie.New函数代码示例

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

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



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

示例1: New

func New(db *database.DB,
	mailer mailer.Mailer,
	log *logrus.Logger,
	cfg *config.Config) *Server {

	secureCookieKey, _ := base64.StdEncoding.DecodeString(cfg.SecureCookieKey)

	cookie := securecookie.New(
		[]byte(cfg.SecretKey),
		secureCookieKey,
	)

	renderOptions := render.Options{
		IsDevelopment: cfg.IsDev(),
	}

	renderer := render.New(renderOptions)

	feedparser := feedparser.New()

	return &Server{
		DB:         db,
		Config:     cfg,
		Log:        log,
		Render:     renderer,
		Cookie:     cookie,
		Feedparser: feedparser,
		Mailer:     mailer,
	}
}
开发者ID:szwork2013,项目名称:podbaby,代码行数:30,代码来源:server.go


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


示例3: InitFromMetadataOrJSON

// InitFromMetadataOrJSON must be called before any other login methods.
//
// InitFromMetadataOrJSON will eventually replace all instances of Init, at
// which point it will be renamed back to Init().
//
// The function first tries to load the cookie salt, client id, and client
// secret from GCE project level metadata. If that fails it looks for a
// "client_secret.json" file in the current directory to extract the client id
// and client secret from. If both of those fail then it returns an error.
//
// The authWhiteList is the space separated list of domains and email addresses
// that are allowed to log in. The authWhiteList will be overwritten from
// GCE instance level metadata if present.
func InitFromMetadataOrJSON(redirectURL, scopes string, authWhiteList string) error {
	cookieSalt, clientID, clientSecret := tryLoadingFromMetadata()
	if clientID == "" {
		b, err := ioutil.ReadFile("client_secret.json")
		if err != nil {
			return fmt.Errorf("Failed to read from metadata and from client_secret.json file: %s", err)
		}
		config, err := google.ConfigFromJSON(b)
		if err != nil {
			return fmt.Errorf("Failed to read from metadata and decode client_secret.json file: %s", err)
		}
		clientID = config.ClientID
		clientSecret = config.ClientSecret
	}
	secureCookie = securecookie.New([]byte(cookieSalt), nil)
	oauthConfig.ClientId = clientID
	oauthConfig.ClientSecret = clientSecret
	oauthConfig.RedirectURL = redirectURL
	oauthConfig.Scope = scopes
	// We allow for meta data to not be present.
	whiteList, err := metadata.Get(metadata.AUTH_WHITE_LIST)
	if err != nil {
		glog.Infof("Failed to retrieve auth whitelist from instance meta data: %s", err)
	} else {
		authWhiteList = whiteList
	}
	activeDomainWhiteList, activeEmailWhiteList = splitAuthWhiteList(authWhiteList)
	return nil
}
开发者ID:saltmueller,项目名称:skia-buildbot,代码行数:42,代码来源:login.go


示例4: AuthHandler

// AuthHandler allows to get admin web interface token.
func (app *Application) AuthHandler(w http.ResponseWriter, r *http.Request) {
	password := r.FormValue("password")
	if app.config.WebPassword == "" || app.config.WebSecret == "" {
		logger.ERROR.Println("web_password and web_secret must be set in configuration")
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}
	if password == app.config.WebPassword {
		w.Header().Set("Content-Type", "application/json")
		app.RLock()
		s := securecookie.New([]byte(app.config.WebSecret), nil)
		app.RUnlock()
		token, err := s.Encode(AuthTokenKey, AuthTokenValue)
		if err != nil {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		resp := map[string]string{
			"token": token,
		}
		json.NewEncoder(w).Encode(resp)
		return
	}
	http.Error(w, "Bad Request", http.StatusBadRequest)
}
开发者ID:rohan1790,项目名称:centrifugo,代码行数:26,代码来源:handlers.go


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


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


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


示例8: Login

// handles the login process
// the first param is a map of strings that will be added to the cookie data before encryption and will be
// able to be recovered when Check() is called
func Login(ctx *gin.Context, extra map[string]string) error {

	data := make(map[string]string)

	for key, value := range extra {

		if key == "ip" || key == "hash" || key == "experation" {
			return errors.New("The key '" + key + "' is reserved.")
		}

		data[key] = value
	}

	// our current time + our expiration time, converted to a unix time stamp
	data["expiration"] = strconv.FormatInt(time.Now().Add(time.Duration(Expiration)*time.Second).Unix(), 10)
	data["ip"] = ip(ctx)
	data["hash"] = hashHeader(ctx)

	// encode our cookie data securely
	SecureCookie = securecookie.New(HashKey, BlockKey)
	if encoded, err := SecureCookie.Encode(CookieName, data); err == nil {

		//set our cookie
		cookie := http.Cookie{Name: CookieName, Value: encoded, Path: "/", MaxAge: int(Expiration)}
		http.SetCookie(ctx.Writer, &cookie)

	} else {
		return err
	}

	return nil
}
开发者ID:rageix,项目名称:ginAuth,代码行数:35,代码来源:auth.go


示例9: generateCookie

func generateCookie() *securecookie.SecureCookie {
	// Generates SecureCookie type object and returns a pointer to it.
	// It is used to Encode/Decode plain data to/from a cookie.

	S := securecookie.New([]byte(config.Config.Secret1), []byte(config.Config.Secret2))
	return S
}
开发者ID:nymoral,项目名称:gothere,代码行数:7,代码来源:cookies.go


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


示例11: init

func init() {
	//configs = my_local.Load_config(filepath.Join(getCurrentDir(), "config.json"))
	configs = my_config.Load_config("./config.json")
	//cookieHandler = securecookie.New(
	//	securecookie.GenerateRandomKey(32),
	//	securecookie.GenerateRandomKey(32))
	cookieHandler = securecookie.New(
		[]byte(configs.HashKey),
		[]byte(configs.BlockKey))
	CSRF = csrf.Protect([]byte(configs.CsrfAuthKey), csrf.Secure(false))
	// First we create a FuncMap with which to register the function.
	funcMap = template.FuncMap{
		// The name "title" is what the function will be called in the template text.
		"trim":  strings.TrimSpace,
		"lower": strings.ToLower,
		"upper": strings.ToUpper,
		"safehtml": func(text string) template.HTML {
			return template.HTML(text)
		},
	}
	g_templates = make(myTemplates)
	loadTemplates("")
	fmt.Printf("%v\n", g_templates)
	r = gin.New()
}
开发者ID:supermet,项目名称:gowiki,代码行数:25,代码来源:wiki.go


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


示例13: checkAuthToken

// checkAuthToken checks admin connection token which Centrifugo returns after admin login
func (app *Application) checkAuthToken(token string) error {

	app.RLock()
	secret := app.config.WebSecret
	app.RUnlock()

	if secret == "" {
		logger.ERROR.Println("provide web_secret in configuration")
		return ErrUnauthorized
	}

	if token == "" {
		return ErrUnauthorized
	}

	s := securecookie.New([]byte(secret), nil)
	var val string
	err := s.Decode(AuthTokenKey, token, &val)
	if err != nil {
		return ErrUnauthorized
	}

	if val != AuthTokenValue {
		return ErrUnauthorized
	}
	return nil
}
开发者ID:rohan1790,项目名称:centrifugo,代码行数:28,代码来源:application.go


示例14: init

func init() {
	log.SetFlags(log.Lshortfile)
	hashKey = []byte(os.Getenv("HASHKEY"))
	if bKey := os.Getenv("BLOCKKEY"); bKey != "" {
		blockKey = []byte(bKey)
	}
	sCookie = securecookie.New(hashKey, blockKey)
}
开发者ID:jbaikge,项目名称:ingress-inventory,代码行数:8,代码来源:main.go


示例15: InitServer

func InitServer(r *mux.Router) {

	s := &Server{securecookie.New([]byte("MiaMySuperSecret"), []byte("MiaMySuperSecret"))}

	r.HandleFunc("/send", s.secure(s.handleSend))
	r.HandleFunc("/login", s.handleLogin)

}
开发者ID:jjvvark,项目名称:Prufor,代码行数:8,代码来源:server.go


示例16: NewUserCookieCodec

func NewUserCookieCodec(hashKey string, blockKey string) *securecookie.SecureCookie {
	return securecookie.New(
		[]byte(hashKey),
		[]byte(blockKey),
	).
		SetSerializer(securecookie.JSONEncoder{}).
		HashFunc(sha512.New)
}
开发者ID:mxmCherry,项目名称:trafficrouter,代码行数:8,代码来源:trafficrouter.go


示例17: signCookie

// Sign the specified cookie's value
func signCookie(ck *http.Cookie, secret string) error {
	sck := securecookie.New([]byte(secret), nil)
	enc, err := sck.Encode(ck.Name, ck.Value)
	if err != nil {
		return err
	}
	ck.Value = enc
	return nil
}
开发者ID:rnd-ua,项目名称:scope,代码行数:10,代码来源:session.go


示例18: DecodeState

// DecodeState decodes the oauth2 transfer state encoded with EncodeState.
func (p Provider) DecodeState(data string) (map[string]string, error) {
	sc := securecookie.New(p.Secret, p.BlockSecret)
	sc.MaxAge(int(p.StateLifetime))

	state := make(map[string]string)
	err := sc.Decode(p.SessionKey, data, &state)

	return state, err
}
开发者ID:knq,项目名称:oauthmw,代码行数:10,代码来源:provider.go


示例19: parseSignedCookie

// Parse a signed cookie and return the cookie value
func parseSignedCookie(ck *http.Cookie, secret string) (string, error) {
	var val string

	sck := securecookie.New([]byte(secret), nil)
	err := sck.Decode(ck.Name, ck.Value, &val)
	if err != nil {
		return "", err
	}
	return val, nil
}
开发者ID:rnd-ua,项目名称:scope,代码行数:11,代码来源:session.go


示例20: Protect

// Protect is HTTP middleware that provides Cross-Site Request Forgery
// protection.
//
// It securely generates a masked (unique-per-request) token that
// can be embedded in the HTTP response (e.g. form field or HTTP header).
// The original (unmasked) token is stored in the session, which is inaccessible
// by an attacker (provided you are using HTTPS). Subsequent requests are
// expected to include this token, which is compared against the session token.
// Requests that do not provide a matching token are served with a HTTP 403
// 'Forbidden' error response.
//
// Example:
//	package main
//
//	import (
//	    "github.com/goji/csrf"
//	    "github.com/zenazn/goji"
//	)
//
//	func main() {
//	    // Add the middleware to your router.
//	    goji.Use(csrf.Protect([]byte("32-byte-long-auth-key")))
//	    goji.Get("/signup", GetSignupForm)
//	    // POST requests without a valid token will return a HTTP 403 Forbidden.
//	    goji.Post("/signup/post", PostSignupForm)
//
//	    goji.Serve()
//	}
//
//	func GetSignupForm(c web.C, w http.ResponseWriter, r *http.Request) {
//	    // signup_form.tmpl just needs a {{ .csrfField }} template tag for
//	    // csrf.TemplateField to inject the CSRF token into. Easy!
//	    t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{
//	        csrf.TemplateTag: csrf.TemplateField(c, r),
//	    })
//	    // We could also retrieve the token directly from csrf.Token(c, r) and
//	    // set it in the request header - w.Header.Set("X-CSRF-Token", token)
//	    // This is useful if your sending JSON to clients or a front-end JavaScript
//	    // framework.
//	}
//
func Protect(authKey []byte, opts ...Option) func(*web.C, http.Handler) http.Handler {
	return func(c *web.C, h http.Handler) http.Handler {
		cs := parseOptions(h, opts...)

		// Set the defaults if no options have been specified
		if cs.opts.ErrorHandler == nil {
			cs.opts.ErrorHandler = web.HandlerFunc(unauthorizedHandler)
		}

		if cs.opts.MaxAge < 1 {
			// Default of 12 hours
			cs.opts.MaxAge = 3600 * 12
		}

		if cs.opts.FieldName == "" {
			cs.opts.FieldName = fieldName
		}

		if cs.opts.CookieName == "" {
			cs.opts.CookieName = cookieName
		}

		if cs.opts.RequestHeader == "" {
			cs.opts.RequestHeader = headerName
		}

		// Create an authenticated securecookie instance.
		if cs.sc == nil {
			cs.sc = securecookie.New(authKey, nil)
			// Use JSON serialization (faster than one-off gob encoding)
			cs.sc.SetSerializer(securecookie.JSONEncoder{})
			// Set the MaxAge of the underlying securecookie.
			cs.sc.MaxAge(cs.opts.MaxAge)
		}

		if cs.st == nil {
			// Default to the cookieStore
			cs.st = &cookieStore{
				name:     cs.opts.CookieName,
				maxAge:   cs.opts.MaxAge,
				secure:   cs.opts.Secure,
				httpOnly: cs.opts.HttpOnly,
				path:     cs.opts.Path,
				domain:   cs.opts.Domain,
				sc:       cs.sc,
			}
		}

		// Initialize Goji's request context
		cs.c = c

		return *cs
	}
}
开发者ID:molivier,项目名称:csrf,代码行数:95,代码来源:csrf.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang securecookie.SecureCookie类代码示例发布时间:2022-05-23
下一篇:
Golang securecookie.GenerateRandomKey函数代码示例发布时间: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