本文整理匯總了Golang中github.com/gorilla/sessions.CookieStore類的典型用法代碼示例。如果您正苦於以下問題:Golang CookieStore類的具體用法?Golang CookieStore怎麽用?Golang CookieStore使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了CookieStore類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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)
}
}
示例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]))
}
}
示例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)
}
}
示例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)
}
}
}
示例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
}
示例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)
}
})
}
示例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)
}
}
示例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)
}
示例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)
}
示例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)
}
}
示例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)
}
})
}
示例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)
}
})
}
示例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
}
}
示例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)
}
}
示例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
}