當前位置: 首頁>>代碼示例>>Golang>>正文


Golang securecookie.New函數代碼示例

本文整理匯總了Golang中github.com/gorilla/securecookie.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的github.com/gorilla/securecookie.New函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。