/* получить актуальную сессию */ func Get(w http.ResponseWriter, r *http.Request) *Session { var ( err error cookie *http.Cookie ses *Session ok bool ses_id string ) cookie, err = r.Cookie(sid) if err != nil { ses_id, ses = registry.new() cookie = &http.Cookie{Name: sid, Value: ses_id, Path: "/", HttpOnly: true, MaxAge: int(maxlifetime.Seconds())} http.SetCookie(w, cookie) return ses } ses, ok = registry.get(cookie.Value) if !ok { ses = registry.create(cookie.Value) cookie.MaxAge = int(maxlifetime.Seconds()) cookie.Path = "/" http.SetCookie(w, cookie) return ses } cookie.MaxAge = int(maxlifetime.Seconds()) http.SetCookie(w, cookie) return ses }
func LogoutHandler(c *gin.Context) { var userCookie http.Cookie userCookie.Name = "user" userCookie.MaxAge = -1 http.SetCookie(c.Writer, &userCookie) c.Redirect(http.StatusMovedPermanently, "/") }
// AddSignedCookie adds the specified cookie to the response and also adds an // additional 'signed' cookie that is used to validate the cookies value when // SignedCookie is called. func (c *Context) AddSignedCookie(cookie *http.Cookie) (*http.Cookie, error) { // make the signed cookie signedCookie := new(http.Cookie) // copy the cookie settings signedCookie.Path = cookie.Path signedCookie.Domain = cookie.Domain signedCookie.RawExpires = cookie.RawExpires signedCookie.Expires = cookie.Expires signedCookie.MaxAge = cookie.MaxAge signedCookie.Secure = cookie.Secure signedCookie.HttpOnly = cookie.HttpOnly signedCookie.Raw = cookie.Raw // set the signed cookie specifics signedCookie.Name = toSignedCookieName(cookie.Name) signedCookie.Value = Hash(cookie.Value) // add the cookies http.SetCookie(c.ResponseWriter, cookie) http.SetCookie(c.ResponseWriter, signedCookie) // return the new signed cookie (and no error) return signedCookie, nil }
/** * クッキーを作成する * @function * @param {string} name クッキーの名前 * @param {string} value クッキーの値 * @param {string} domain 有効ドメイン * @param {string} path 有効ディレクトリ * @param {int} hour 有効期限(時間) */ func NewCookie(name string, value string, domain string, path string, hour int) *http.Cookie { duration := time.Hour * time.Duration(hour) now := time.Now() expire := now.Add(duration) cookie := new(http.Cookie) cookie.Name = name cookie.Value = value cookie.Domain = domain cookie.Path = path cookie.Expires = expire cookie.RawExpires = expire.Format(time.UnixDate) cookie.MaxAge = 60 * 60 * hour cookie.Secure = false cookie.HttpOnly = true cookie.Raw = fmt.Sprintf("%s=%s", cookie.Name, cookie.Value) cookie.Unparsed = []string{cookie.Raw} return cookie }
// parse parses a Set-Cookie header into a cookie. // It supports space in name unlike net/http. // Returns nil if invalid. func parse(s string) *http.Cookie { var c http.Cookie for i, field := range strings.Split(s, ";") { if len(field) == 0 { continue } nv := strings.SplitN(field, "=", 2) name := strings.TrimSpace(nv[0]) value := "" if len(nv) > 1 { value = strings.TrimSpace(nv[1]) } if i == 0 { if len(nv) != 2 { continue } c.Name = name c.Value = value continue } switch strings.ToLower(name) { case "secure": c.Secure = true case "httponly": c.HttpOnly = true case "domain": c.Domain = value case "max-age": secs, err := strconv.Atoi(value) if err != nil || secs != 0 && value[0] == '0' { continue } if secs <= 0 { c.MaxAge = -1 } else { c.MaxAge = secs } case "expires": exptime, err := time.Parse(time.RFC1123, value) if err != nil { exptime, err = time.Parse("Mon, 02-Jan-2006 15:04:05 MST", value) if err != nil { c.Expires = time.Time{} continue } } c.Expires = exptime.UTC() case "path": c.Path = value } } if c.Name == "" { return nil } return &c }
// set cookie // args: name, value, max age, path, domain, secure, http only, expires func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { cookie := http.Cookie{} cookie.Name = name cookie.Value = url.QueryEscape(value) if len(others) > 0 { switch v := others[0].(type) { case int: cookie.MaxAge = v case int64: cookie.MaxAge = int(v) case int32: cookie.MaxAge = int(v) } } cookie.Path = "/" if len(others) > 1 { if v, ok := others[1].(string); ok && len(v) > 0 { cookie.Path = v } } if len(others) > 2 { if v, ok := others[2].(string); ok && len(v) > 0 { cookie.Domain = v } } if len(others) > 3 { switch v := others[3].(type) { case bool: cookie.Secure = v default: if others[3] != nil { cookie.Secure = true } } } if len(others) > 4 { if v, ok := others[4].(bool); ok && v { cookie.HttpOnly = true } } if len(others) > 5 { if v, ok := others[5].(time.Time); ok { cookie.Expires = v cookie.RawExpires = v.Format(time.UnixDate) } } ctx.w.Header().Add("Set-Cookie", cookie.String()) }
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { cookie := http.Cookie{} cookie.Name = name cookie.Value = value if len(others) > 0 { switch v := others[0].(type) { case int: cookie.MaxAge = v case int64: cookie.MaxAge = int(v) case int32: cookie.MaxAge = int(v) } } // default "/" if len(others) > 1 { if v, ok := others[1].(string); ok && len(v) > 0 { cookie.Path = v } } else { cookie.Path = "/" } // default empty if len(others) > 2 { if v, ok := others[2].(string); ok && len(v) > 0 { cookie.Domain = v } } // default empty if len(others) > 3 { switch v := others[3].(type) { case bool: cookie.Secure = v default: if others[3] != nil { cookie.Secure = true } } } // default false. for session cookie default true if len(others) > 4 { if v, ok := others[4].(bool); ok && v { cookie.HttpOnly = true } } ctx.Res.Header().Add("Set-Cookie", cookie.String()) }
func (res *Response) SetCookie(name string, value string, others ...interface{}) { cookie := http.Cookie{} cookie.Name = name cookie.Value = url.QueryEscape(value) if len(others) > 0 { switch v := others[0].(type) { case int: cookie.MaxAge = v case int64: cookie.MaxAge = int(v) case int32: cookie.MaxAge = int(v) } } cookie.Path = "/" if len(others) > 1 { if v, ok := others[1].(string); ok && len(v) > 0 { cookie.Path = v } } if len(others) > 2 { if v, ok := others[2].(string); ok && len(v) > 0 { cookie.Domain = v } } if len(others) > 3 { switch v := others[3].(type) { case bool: cookie.Secure = v default: if others[3] != nil { cookie.Secure = true } } } if len(others) > 4 { if v, ok := others[4].(bool); ok && v { cookie.HttpOnly = true } } res.Header().Add("Set-Cookie", cookie.String()) }
func removeSignedCookie(w http.ResponseWriter, cookie *http.Cookie) { cookie.MaxAge = -1 var signCookie = *cookie signCookie.Name += sign_suffix http.SetCookie(w, cookie) http.SetCookie(w, &signCookie) }
func (ss signedCookieSessionHandler) writeToResponse(s SignedCookieSession, resp goanna.Response) { bytes, err := s.sessionData.Unmarshal() if err != nil { log.Println(err.Error()) } cookie := http.Cookie{ Name: ss.CookieName, Value: base64.URLEncoding.EncodeToString(bytes), HttpOnly: true, Secure: ss.Secure, Path: "/", } ss.CookieSigner.EncodeCookie(&cookie) maxage := int(s.MaxAge() / time.Second) if maxage != 0 { if s.preferExpires { cookie.Expires = time.Now().Add(s.MaxAge()) } else { cookie.MaxAge = maxage } } resp.SetCookie(cookie) }
func Set(w http.ResponseWriter, s string) { secure, _ := strconv.ParseBool(config.Get("session_cookie_secure")) c := new(http.Cookie) c.Name = fmt.Sprintf("%s-flash", config.Get("session_cookie_name")) c.Path = config.Get("session_cookie_path") c.Value = base64.URLEncoding.EncodeToString([]byte(strings.TrimSpace(s))) if c.Value != "" { c.MaxAge = 0 } else { c.MaxAge = -1 } c.Secure = secure http.SetCookie(w, c) logger.Log(w, "SET-COOKIE", c.String()) }
func (r *OkResponse) ClearCookie(name string) { c := http.Cookie{} c.Name = name c.Value = "none" c.MaxAge = -1 c.Expires = time.Unix(1, 0) r.SetCookie(c) }
func commitSession(headers Headers, env Env, key, secret string, newValue string, options *CookieOptions) { cookie := new(http.Cookie) cookie.Name = key cookie.Value = newValue cookie.Path = options.Path cookie.Domain = options.Domain cookie.MaxAge = options.MaxAge cookie.Secure = options.Secure cookie.HttpOnly = options.HttpOnly headers.Add("Set-Cookie", cookie.String()) }
func commitSession(headers Headers, env Env, key, secret string, options *CookieOptions) { cookie := new(http.Cookie) cookie.Name = key cookie.Value = encodeCookie(env["mango.session"].(map[string]interface{}), secret) cookie.Path = options.Path cookie.Domain = options.Domain cookie.MaxAge = options.MaxAge cookie.Secure = options.Secure cookie.HttpOnly = options.HttpOnly headers.Add("Set-Cookie", cookie.String()) }
// Constructs a new CSRFHandler that calls // the specified handler if the CSRF check succeeds. func New(handler http.Handler) *CSRFHandler { baseCookie := http.Cookie{} baseCookie.MaxAge = MaxAge csrf := &CSRFHandler{successHandler: handler, failureHandler: http.HandlerFunc(defaultFailureHandler), baseCookie: baseCookie, } return csrf }
/* Set cookie "name" to "value", where "value" may be a string or interface converted to JSON. The "path" option defaults to "/". Set cookie `name` to `val`, with the given `options`. Options: - `maxAge` max-age in milliseconds, converted to `expires` - `signed` sign the cookie - `path` defaults to "/" Examples: // "Remember Me" for 15 minutes res.Cookie("rememberme", "1", &httpCookie{ expires: new Date(Date.now() + 900000), httpOnly: true }); // save as above res.Cookie("rememberme", "1", &httpCookie{ maxAge: 900000, httpOnly: true }) */ func (this *Response) Cookie(n string, i interface{}, o ...*http.Cookie) { var cookie *http.Cookie /* If we were given cookie options use them. */ if len(o) == 1 { cookie = o[0] } else { cookie = &http.Cookie{} } /* Convert the given interface to a string so it can be used as a cookie value. */ var v string switch i.(type) { default: b, e := json.Marshal(i) v = string(b) if e != nil { v = e.Error() } case string: v = i.(string) } cookie.Name = n cookie.Value = url.QueryEscape(Encode(v)) if cookie.Path == "" { cookie.Path = "/" } if cookie.MaxAge == 0 { // max-age in milliseconds, converted to `expires` // TODO: Check the timing here. cookie.Expires = time.Now().UTC().Add(time.Duration(cookie.MaxAge) * (time.Millisecond * time.Microsecond)) cookie.MaxAge = cookie.MaxAge / 1000 } // cookie.Domain = "" // cookie.Secure = false // cookie.HttpOnly = false /* Possible bug if headers are already sent. */ http.SetCookie(this.Writer, cookie) }
// createCookie 创建cookie func (this *HttpProcessor) createCookie(name string, id string, expire int) *http.Cookie { var cookieValue = new(http.Cookie) cookieValue.Name = name cookieValue.Value = id cookieValue.Path = "/" cookieValue.HttpOnly = true if expire > 0 { cookieValue.MaxAge = expire cookieValue.Expires = time.Now().Add(time.Second * time.Duration(expire)) } return cookieValue }
/* Add the Session to the response Basically this means setting a cookie */ func (sh *BaseSessionHolder) AddToResponse(c web.C, session *Session, w http.ResponseWriter) { cookie := http.Cookie{ Name: "sessionid", Value: session.Id(), Path: "/", HttpOnly: sh.HttpOnly, Secure: sh.Secure, } if sh.PersistentCookie { cookie.MaxAge = sh.Timeout } http.SetCookie(w, &cookie) }
func (s *Session) Save(w http.ResponseWriter, keepalive bool) error { q := ` UPDATE user_session SET valid_until = ? , modified_date = ? WHERE id = ?; ` valid := int64(0) if keepalive { valid = time.Now().Unix() + SESSION_OFFSET } params := []interface{}{ valid, time.Now().Unix(), s.Id, } _, err := dao.Exec(q, params) if err != nil { return err } expires := -1 if keepalive { expires, _ = strconv.Atoi(config.Get("session_cookie_expires")) } secure, _ := strconv.ParseBool(config.Get("session_cookie_secure")) c := new(http.Cookie) c.Name = config.Get("session_cookie_name") if keepalive { c.Value = s.Key } c.Path = config.Get("session_cookie_path") c.MaxAge = expires c.Secure = secure http.SetCookie(w, c) logger.Log(w, "SET-COOKIE", c.String()) return nil }
func logOutHandler(w http.ResponseWriter, r *http.Request, s string) { ctx := appengine.NewContext(r) url, err := user.LogoutURL(ctx, "/") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Deleting session cookie var cookie *http.Cookie cookie, err = r.Cookie(s) if err != http.ErrNoCookie { cookie.MaxAge = -1 http.SetCookie(w, cookie) } // CHANGE NECESSARY DB FIELDS OF USER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! http.Redirect(w, r, url, http.StatusFound) }
// sid="" for remove it now func (this *Session) writeSession(res Response, sid string) { var toSet = http.Cookie{ Name: sid_cookie_key, Value: sid, Path: this.Path, Secure: this.Secure, HttpOnly: this.HttpOnly, } if this.MaxAge > 0 { toSet.MaxAge = this.MaxAge } if sid == "" { removeSignedCookie(res.R(), &toSet) return } setSignedCookie(res.R(), &toSet, this.Secret) }
/* Clear cookie "name". The "path" option defaults to "/". */ func (this *Response) ClearCookie(n string, o ...*http.Cookie) { var opt *http.Cookie if len(o) == 1 { opt = o[0] } else { opt = &http.Cookie{} } opt.MaxAge = -1 if opt.Path == "" { opt.Path = "/" } this.Cookie(n, "", opt) }
func PostLogin(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") username := r.FormValue("username") password := r.FormValue("password") if username == "" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Empty username\n")) return } if password == "" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Empty Password\n")) return } checkedPassword, _, _, err := dba.GetUser(username) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("No Such Username")) return } if checkedPassword != password { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Incorrect Password")) return } var cookie http.Cookie cookie.Name = "session" cookie.Value = sm.GenerateNewSessionId(username) cookie.Domain = "" cookie.Path = "/" cookie.MaxAge = 0 http.SetCookie(w, &cookie) w.WriteHeader(http.StatusOK) w.Write([]byte("")) }
func HandleLoginPost(c *gin.Context) { var userid string var cookieid string var cookie = new(http.Cookie) userid = c.Request.Header.Get("email") password := c.Request.Header.Get("password") if userid == "" { cookie, err := c.Request.Cookie("one") if err != nil { tools.Info(err.Error()) } if cookie != nil { cookieid = cookie.Value tools.Info(cookieid) } } ser := new(Service.PersonalService) ser.ServerType = Service.PERSONAAL_LOGINLOGOUT_SERVICE_TYPE ser.ActionType = Service.PERSONAL_POST_ACTION ser.Params = make(map[string]interface{}) ser.Params["userid"] = userid ser.Params["password"] = password ser.ProcessService() cookie.Name = "one" cookie.Value = userid cookie.MaxAge = 3600 c.Request.AddCookie(cookie) if ser.Result["data"] != nil { tools.Info("user login success") c.Redirect(301, "/people/"+userid) } else { tools.Info("user login failed") c.JSON(200, ser.Result) } }
func (c *Cookie) Set(name, value string, second time.Duration) { cookie := http.Cookie{ Name: name, Value: value, HttpOnly: true, Path: "/", Domain: c.r.URL.Host, } if second == 0 { cookie.MaxAge = 0 } else { expire := time.Now().Add(second * time.Second) cookie.Expires = expire } http.SetCookie(c.w, &cookie) }
func defaultHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { cookieToken, err := r.Cookie("token") if err != nil { if err == http.ErrNoCookie { http.Redirect(w, r, "/auth", http.StatusSeeOther) return } internalServerError(w, err) return } token := auth.NewUserToken() err = token.FromString(cookieToken.Value) if err == nil { err = auth.CheckUserToken(db, token) } if err != nil { if _, ok := err.(auth.AuthError); ok { var c http.Cookie c.Name = "token" c.MaxAge = -1 c.Secure = true c.HttpOnly = true http.SetCookie(w, &c) http.Redirect(w, r, "/", http.StatusSeeOther) return } internalServerError(w, err) return } if r.URL.Path != "/" { http.Redirect(w, r, "/", http.StatusSeeOther) return } chatHandler(w, r, db) }
// addCookie adds a cookie to the response. The cookie value is the base64 // encoding of the json encoding of data. If data is nil, then the cookie is // deleted. func addCookie(w http.ResponseWriter, name string, data interface{}, maxAge time.Duration) error { c := http.Cookie{ Name: name, Path: "/", HttpOnly: true, } if data == nil { maxAge = -10000 * time.Second } else { var b bytes.Buffer if err := json.NewEncoder(&b).Encode(data); err != nil { return err } c.Value = base64.URLEncoding.EncodeToString(b.Bytes()) } if maxAge != 0 { c.MaxAge = int(maxAge / time.Second) c.Expires = time.Now().Add(maxAge) } http.SetCookie(w, &c) return nil }
// SetUserCookie creates a secure cookie for the given username, indicating the // user is authenticated. func SetUserCookie(w http.ResponseWriter, r *http.Request, user string) { // cookie expires in 2 weeks exp := time.Now().Add(Config.CookieExp) // generate cookie valid for 24 hours for user value := authcookie.New(user, exp, Config.CookieSecret) cookie := http.Cookie{ Name: Config.CookieName, Value: value, Path: "/", Domain: r.URL.Host, } // if not a session cookie if Config.CookieMaxAge > 0 { cookie.Expires = exp cookie.MaxAge = Config.CookieMaxAge } http.SetCookie(w, &cookie) }
func TestAddSignedCookie(t *testing.T) { context := MakeTestContext() cookie := new(http.Cookie) cookie.Name = "userId" cookie.Value = "2468" cookie.Path = "/something" cookie.Domain = "domain" cookie.RawExpires = "NOW" cookie.Expires = time.Now() cookie.MaxAge = 123 cookie.Secure = true cookie.HttpOnly = true cookie.Raw = "userId=2468;" signedCookie, err := context.AddSignedCookie(cookie) if err != nil { t.Errorf("AddSignedCookie shouldn't return an error: %s", err) return } assertEqual(t, signedCookie.Name, fmt.Sprintf("%s_signed", cookie.Name), "Cookie name") assertEqual(t, signedCookie.Value, Hash(cookie.Value), "Cookie value (signed)") // assert the rest of the values were also copied assertEqual(t, signedCookie.Path, cookie.Path, "Path") assertEqual(t, signedCookie.Domain, cookie.Domain, "Domain") assertEqual(t, signedCookie.RawExpires, cookie.RawExpires, "RawExpires") assertEqual(t, signedCookie.Expires, cookie.Expires, "Expires") assertEqual(t, signedCookie.MaxAge, cookie.MaxAge, "MaxAge") assertEqual(t, signedCookie.Secure, cookie.Secure, "Secure") assertEqual(t, signedCookie.HttpOnly, cookie.HttpOnly, "HttpOnly") assertEqual(t, signedCookie.Raw, cookie.Raw, "Raw") }
resp, _ := x.ReadResponse() jsessionId := getCookie(proxy.StickyCookieKey, resp.Cookies()) Expect(jsessionId).ToNot(BeNil()) cookie := getCookie(proxy.VcapCookieId, resp.Cookies()) Expect(cookie).ToNot(BeNil()) Expect(cookie.Value).To(Equal("some-id")) Expect(cookie.Secure).To(BeFalse()) Expect(cookie.MaxAge).To(BeZero()) Expect(cookie.Expires).To(BeZero()) }) Context("when the JSESSIONID is expired", func() { BeforeEach(func() { jSessionIdCookie.MaxAge = -1 }) It("expires the VCAP_ID", func() { ln := registerHandlerWithInstanceId(r, "app", "", responseWithJSessionID, "my-id") defer ln.Close() x := dialProxy(proxyServer) req := test_util.NewRequest("GET", "app", "/", nil) x.WriteRequest(req) Eventually(done).Should(Receive()) resp, _ := x.ReadResponse() jsessionId := getCookie(proxy.StickyCookieKey, resp.Cookies()) Expect(jsessionId).ToNot(BeNil())