本文整理汇总了Golang中github.com/gorilla/sessions.CookieStore类的典型用法代码示例。如果您正苦于以下问题:Golang CookieStore类的具体用法?Golang CookieStore怎么用?Golang CookieStore使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CookieStore类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: ValidateAuth
// Validates that the user cookie is set up before calling the handler
// passed as parameter.
func ValidateAuth(h httputils.ContextHandler) httputils.ContextHandler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var (
sessionData *SessionData
err error
ok bool
cookieStore *sessions.CookieStore
session *sessions.Session
)
cookieStore, ok = ctx.Value("cookieStore").(*sessions.CookieStore)
if !ok {
return fmt.Errorf("validate auth: could not cast value as cookie store:", ctx.Value("cookieStore"))
}
session, err = cookieStore.Get(r, SessionCookieName)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return nil
}
sessionData, ok = session.Values["data"].(*SessionData)
if !ok {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return nil
}
authenticatedContext := context.WithValue(ctx, "sessionData", sessionData)
return h(authenticatedContext, w, r)
}
}
开发者ID:gitter-badger,项目名称:abcd,代码行数:37,代码来源:middleware.go
示例2: receiveCode
func receiveCode(w http.ResponseWriter, req *http.Request, config map[string]string, store *sessions.CookieStore, templates *template.Template) {
session, _ := store.Get(req, config["SESSION_NAME"])
context, _ := url.ParseQuery(req.URL.RawQuery)
if code, ok := context["code"]; ok {
auth_code := string(code[0])
resp, _ := http.PostForm(API_URI+"/token/",
url.Values{"client_id": {config["CLIENT_ID"]},
"client_secret": {config["CLIENT_SECRET"]},
"grant_type": {"authorization_code"},
"code": {auth_code},
"redirect_uri": {config["REDIRECT_URI"]},
"scope": {config["scope"]},
})
defer resp.Body.Close()
if resp.StatusCode == 200 {
var t_res TokenResponse
dec := json.NewDecoder(resp.Body)
err := dec.Decode(&t_res)
if err != nil {
log.Printf(err.Error())
} else {
session.Values[config["SESSION_ACCESS_TOKEN_KEY"]] = t_res.AccessToken
session.Save(req, w)
http.Redirect(w, req, "/", 303)
}
}
} else if error_type, ok := context["error"]; ok {
fmt.Fprintf(w, "%s: %s", string(error_type[0]), string(context["error_description"][0]))
}
}
开发者ID:jjll88,项目名称:api-example-go,代码行数:30,代码来源:app.go
示例3: LoginFunc
func LoginFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
return func(w http.ResponseWriter, req *http.Request) {
loginJSON := map[string]int{"LoginStatus": networkErrStatus}
id := req.PostFormValue("UserID")
if id == "" {
http.ServeFile(w, req, "DHUCourseChooseHTML/login.html")
return
}
pw := req.PostFormValue("UserPassword")
//TODO It should be a form value that come from the user request
school := "DHU"
DBsession := GetSession()
defer DBsession.Close()
cLogin := DBsession.DB(school).C("StudentInfo")
name, err := validateLogin(id, pw, school, cLogin)
switch err {
case nil:
name = url.QueryEscape(name)
http.SetCookie(w, &http.Cookie{Name: "stuName", Value: name})
session, _ := store.Get(req, "sessionid")
session.Values["stuid"] = id
session.Values["school"] = school
session.Save(req, w)
loginJSON["LoginStatus"] = successStatus
case passwordErr:
loginJSON["LoginStatus"] = passwordErrStatus
}
r.JSON(w, http.StatusOK, loginJSON)
}
}
开发者ID:XingLong9630,项目名称:DHUCourseSelection,代码行数:31,代码来源:WebAPI.go
示例4: LoginPostHandler
// LoginPostHandler writes out login response
func LoginPostHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, cfg *Config, connection *Connection) {
username := req.PostFormValue("username")
password := cryptPassword(req.PostFormValue("password"), cfg.SecretKey)
var response []interface{}
response, err := connection.LoginPost(username, password)
if err != nil || len(response) == 0 {
WriteJSONResponse(200, true, "Invalid username or password.", req, w)
} else {
// Store session
userID := response[0].(map[string]interface{})["id"].(string)
session := Session{UserID: userID,
Expires: time.Now().Unix() + int64(cfg.SessionExpires)}
response, err := connection.LoginPostInsertSession(session)
if err != nil || response.Inserted < 1 {
WriteJSONResponse(200, true, "Error creating the user session.", req, w)
} else {
session, _ := cs.Get(req, "magnet_session")
session.Values["session_id"] = response.GeneratedKeys[0]
session.Values["username"] = username
session.Values["user_id"] = userID
session.Save(req, w)
WriteJSONResponse(200, false, "User correctly logged in.", req, w)
}
}
}
开发者ID:NovemberFoxtrot,项目名称:magnet,代码行数:31,代码来源:handler.go
示例5: logged
func logged(r *http.Request, store *sessions.CookieStore) bool {
session, _ := store.Get(r, "session-name")
if _, ok := session.Values["login"]; ok {
return true
}
return false
}
开发者ID:nischalkarki,项目名称:goshop,代码行数:7,代码来源:user.go
示例6: registerHandler
func registerHandler(db db.DbManager, jar *sessions.CookieStore) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
session, _ := jar.Get(r, "carton-session")
if _, ok := session.Values["user"]; ok {
http.Error(w, "already signed in", http.StatusBadRequest)
return
}
decoder := json.NewDecoder(r.Body)
var user NewUser
err := decoder.Decode(&user)
if err != nil {
http.Error(w, "error decoding json", http.StatusBadRequest)
return
}
if user.Username == "" ||
user.Password1 == "" ||
user.Password2 == "" ||
user.Password1 != user.Password2 {
http.Error(w, "bad arguments", http.StatusBadRequest)
return
}
if db.IsUser(user.Username) {
http.Error(w, "user already exists", http.StatusBadRequest)
return
}
bytePass := []byte(user.Password1)
hash, err := bcrypt.GenerateFromPassword(bytePass, bcrypt.DefaultCost)
if err != nil {
http.Error(
w,
"error hashing password",
http.StatusInternalServerError,
)
return
}
err = db.RegisterUser(user.Username, hash)
if err != nil {
http.Error(
w,
"unable to add user",
http.StatusInternalServerError,
)
return
}
session.Values["user"] = user.Username
session.Save(r, w)
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "Successfully registered %v", user.Username)
} else {
return404(w)
}
})
}
开发者ID:vichetuc,项目名称:carton,代码行数:59,代码来源:auth.go
示例7: ValidateAuth
// ValidateAuth validates that the user cookie is set up before calling the
// handler passed as parameter.
func ValidateAuth(h httputils.ContextHandler) httputils.ContextHandler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var (
sessionData *httputils.SessionData
err error
ok bool
cookieStore *sessions.CookieStore
session *sessions.Session
cfg = ctx.Value("config").(*config.Config)
)
cookieStore, ok = ctx.Value("cookieStore").(*sessions.CookieStore)
if !ok {
httputils.WriteError(w, http.StatusInternalServerError, "")
return fmt.Errorf("validate auth: could not cast value as cookie store: %s", ctx.Value("cookieStore"))
}
session, err = cookieStore.Get(r, cfg.SessionCookieName)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return nil
}
sessionData, ok = session.Values["data"].(*httputils.SessionData)
if !ok || sessionData.IsInvalid() {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return nil
} else if time.Now().After(sessionData.ExpiresAt) {
session.Options.MaxAge = -1
session.Save(r, w)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return nil
}
// Extend the session's lifetime.
cfg, ok = ctx.Value("config").(*config.Config)
if !ok {
httputils.WriteError(w, http.StatusInternalServerError, "")
return fmt.Errorf("validate auth: error casting config object: %s", ctx.Value("config"))
}
// Save session only if the session was extended.
if extendSessionLifetime(sessionData, cfg.SessionLifeTime) {
sessionData.ExpiresAt = time.Now().Add(cfg.SessionLifeTime)
session.Save(r, w)
}
authenticatedContext := context.WithValue(ctx, "sessionData", sessionData)
return h(authenticatedContext, w, r)
}
}
开发者ID:ab22,项目名称:abcd,代码行数:59,代码来源:middleware.go
示例8: LogoutHandler
// LogoutHandler writes out logout response
func LogoutHandler(cs *sessions.CookieStore, req *http.Request, connection *Connection, w http.ResponseWriter) {
session, _ := cs.Get(req, "magnet_session")
_, _ = connection.Logout(session)
session.Values["user_id"] = ""
session.Values["session_id"] = ""
session.Values["username"] = ""
session.Save(req, w)
http.Redirect(w, req, "/", 301)
}
开发者ID:NovemberFoxtrot,项目名称:magnet,代码行数:13,代码来源:handler.go
示例9: logout
func logout(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore, t *template.Template) {
s, _ := store.Get(r, "rp-session")
if s.IsNew {
http.Redirect(w, r, "/", 200)
}
//s.Options.MaxAge = -1
user := s.Values["user"].(*users.User)
user.Logout(db)
s.Values["user"] = users.Default
http.SetCookie(w, &http.Cookie{Name: "rp-session", MaxAge: -1, Path: "/"})
http.Redirect(w, r, "/", 200)
}
开发者ID:patrickjr,项目名称:poker2,代码行数:12,代码来源:users.go
示例10: Session
// Session attaches session to gin context
func Session(store *sessions.CookieStore) gin.HandlerFunc {
return func(c *gin.Context) {
session, err := store.Get(c.Request, utils.ConfigEntry("SessionName"))
if err != nil {
tracelog.CompletedError(err, "Session", "Getting the session")
c.Error(err, "Failed to create session")
c.AbortWithStatus(500)
}
c.Set("session", session)
defer context.Clear(c.Request)
}
}
开发者ID:zannet,项目名称:wiki-player,代码行数:14,代码来源:session.go
示例11: loginHandler
func loginHandler(db db.DbManager, jar *sessions.CookieStore) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
session, _ := jar.Get(r, "carton-session")
if _, ok := session.Values["user"]; ok {
http.Error(w, "already signed in", http.StatusBadRequest)
return
}
decoder := json.NewDecoder(r.Body)
var user User
err := decoder.Decode(&user)
if err != nil {
http.Error(w, "error decoding json", http.StatusBadRequest)
return
}
if user.Username == "" || user.Password == "" {
http.Error(w, "bad arguments", http.StatusBadRequest)
return
}
dbHash := db.GetPwdHash(user.Username)
if dbHash == nil {
http.Error(
w,
"user password combo doesn't exist",
http.StatusBadRequest,
)
return
}
err = bcrypt.CompareHashAndPassword(dbHash, []byte(user.Password))
if err != nil {
http.Error(
w,
"user password combo doesn't exist",
http.StatusBadRequest,
)
return
}
session.Values["user"] = user.Username
session.Save(r, w)
// Sets return code to 200
fmt.Fprintln(w, "login succeeded")
} else {
return404(w)
}
})
}
开发者ID:vichetuc,项目名称:carton,代码行数:50,代码来源:auth.go
示例12: statusHandler
func statusHandler(jar *sessions.CookieStore) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
session, _ := jar.Get(r, "carton-session")
if _, ok := session.Values["user"]; ok {
// Sets return code to 200
fmt.Fprintln(w, "User is logged in")
} else {
http.Error(w, "No user is signed in", http.StatusForbidden)
}
} else {
return404(w)
}
})
}
开发者ID:vichetuc,项目名称:carton,代码行数:15,代码来源:auth.go
示例13: StreamCreateMiddleware
func StreamCreateMiddleware(cs *sessions.CookieStore, ss *ssemux.Store) routing.Handler {
return func(c *routing.Context) error {
// Get a session. We're ignoring the error resulted from decoding an
// existing session: Get() always returns a session, even if empty.
session, err := cs.Get(c.Request, SESSION_NAME)
if err != nil {
return routing.NewHTTPError(http.StatusInternalServerError, err.Error())
}
fmt.Println("id: " + session.Values["id"].(string))
fmt.Println("uid: " + session.Values["uid"].(string))
c.Set(STREAM_CONTEXT_KEY, ss.New(session.Values["id"].(string)))
ss.Associate(session.Values["id"].(string), "uid", session.Values["uid"].(string))
return nil
}
}
开发者ID:caleblloyd,项目名称:ssemux-server,代码行数:15,代码来源:main.go
示例14: CookieMiddleware
func CookieMiddleware(c *sessions.CookieStore) MiddlewareFunc {
//That Middleware is used to detect the session
return func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
urlpath := r.URL.Path
if _, ok := UrlNotDetectSessionList[urlpath]; !ok {
session, _ := c.Get(r, "sessionid")
if session.IsNew || session.Values["stuid"] == "" {
next(rw, r)
http.Redirect(rw, r, "/index", http.StatusMovedPermanently)
return
}
}
next(rw, r)
}
}
开发者ID:XingLong9630,项目名称:DHUCourseSelection,代码行数:15,代码来源:Middleware.go
示例15: GetUserID
// GetUserID fetches userID from rethinkdb
func GetUserID(cs *sessions.CookieStore, req *http.Request, connection *Connection) string {
session, _ := cs.Get(req, "magnet_session")
var response map[string]interface{}
userID := ""
response, err := connection.GetUnexpiredSession(session)
if err == nil && len(response) > 0 {
if int64(response["Expires"].(float64)) > time.Now().Unix() {
userID = response["UserID"].(string)
}
}
return userID
}
开发者ID:gauthierc,项目名称:magnet,代码行数:17,代码来源:util.go
示例16: SessionMiddleware
func SessionMiddleware(cs *sessions.CookieStore) routing.Handler {
return func(c *routing.Context) error {
session, err := cs.Get(c.Request, SESSION_NAME)
if err != nil {
return routing.NewHTTPError(http.StatusInternalServerError, err.Error())
}
if session.IsNew {
randId, _ := rand.Int(rand.Reader, big.NewInt(100000))
randInt, _ := rand.Int(rand.Reader, big.NewInt(3))
session.Values["id"] = randId.String()
session.Values["uid"] = randInt.String()
}
session.Save(c.Request, c.Response)
return nil
}
}
开发者ID:caleblloyd,项目名称:ssemux-server,代码行数:16,代码来源:main.go
示例17: checkSession
func checkSession(r *http.Request, db *sql.DB, s *sessions.CookieStore) (*users.User, bool) {
exists, _ := s.Get(r, "rp-session")
if exists.IsNew {
return nil, false
} else {
x := exists.Values["user"]
if x != nil {
user := x.(*users.User)
err := loginWithCookie(db, user.Name, "", r.RemoteAddr)
if err != nil {
return nil, false
}
return user, true
}
return nil, false
}
}
开发者ID:patrickjr,项目名称:poker2,代码行数:17,代码来源:users.go
示例18: logoutHandler
func logoutHandler(jar *sessions.CookieStore) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
session, _ := jar.Get(r, "carton-session")
if _, ok := session.Values["user"]; !ok {
http.Error(w, "no user to sign out", http.StatusBadRequest)
return
}
delete(session.Values, "user")
session.Save(r, w)
// Sets return code to 200
fmt.Fprintln(w, "Successfully logged out")
} else {
return404(w)
}
})
}
开发者ID:vichetuc,项目名称:carton,代码行数:17,代码来源:auth.go
示例19: confirmSession
//function that returns true if the client is authenticated (has a valid cookie)
//also returns the session information associated with the cookie
func confirmSession(store *sessions.CookieStore, errorMsg string, w http.ResponseWriter, r *http.Request) (bool, *sessions.Session) {
//check for session to see if client is authenticated
session, err := store.Get(r, "flash-session")
if err != nil {
//http.Error(w, err.Error(), http.StatusInternalServerError)
handleError(err, errorMsg, w)
return false, nil
}
fm := session.Flashes("message")
if fm == nil {
//fmt.Fprint(w, "No flash messages")
handleError(err, errorMsg, w)
return false, nil
}
//session.Save(r, w)
return true, session
}
开发者ID:andrew-li,项目名称:Greddit,代码行数:20,代码来源:helpers.go
示例20: getStream
func getStream(store *sessions.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "sndcld")
t, ok := session.Values["token"]
if !ok {
http.Error(w, "No token in session", 500)
}
resp, err := http.Get(fmt.Sprintf("https://api.soundcloud.com/me/activities?limit=25&oauth_token=%s", t.(string)))
if err != nil {
http.Error(w, "No token in session", 500)
}
defer resp.Body.Close()
io.Copy(w, resp.Body)
}
}
开发者ID:stuartnelson3,项目名称:importcloud,代码行数:18,代码来源:main.go
注:本文中的github.com/gorilla/sessions.CookieStore类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论