// Get the session from the cookie in the request // Creates a new session and cookie if none can be found func getSession(w http.ResponseWriter, req *http.Request) (*Session, bool) { cookie, err := req.Cookie("id") if err == nil { s, ok := sessionSync(cookie.Value) if ok { return s, ok } log.Println("Invalid session cookie presented: ", cookie.Value) } // Create a session s := newSession() config.Debug("Creating new session ", s.id) sessions.Create(s) // Write the session to the HTTP response newcookie := http.Cookie{ Name: "id", Value: s.id, Path: "/", MaxAge: math.MaxInt32, HttpOnly: true} w.Header().Add("Set-Cookie", newcookie.String()) s.mutex.Lock() return s, true }
//User login func (uc UsersController) login(request *restful.Request, response *restful.Response) { loginCredentials := new(UserLoginCredentials) err := request.ReadEntity(loginCredentials) if err != nil { LogError(request, response, err) WriteIllegalRequestError(response) return } cookieAuth, err := new(UserManager).Login(loginCredentials) if err != nil { LogError(request, response, err) WriteError(err, response) return } //Create an Auth cookie authCookie := http.Cookie{ Name: "AuthSession", Value: cookieAuth.AuthToken, Path: "/", HttpOnly: true, } //Create a CSRF cookie for this session //Subsequent requests must include this in a header field //X-Csrf-Token csrfCookie := http.Cookie{ Name: "CsrfToken", Value: util.GenHashString(cookieAuth.AuthToken), Path: "/", HttpOnly: false, } response.AddHeader("Set-Cookie", authCookie.String()) response.AddHeader("Set-Cookie", csrfCookie.String()) response.WriteEntity(BooleanResponse{Success: true}) }
func (this *loginController) login(w http.ResponseWriter, req *http.Request) { w.Header().Add("Content-Type", "text/html") responseWriter := util.GetResponseWriter(w, req) defer responseWriter.Close() if req.Method == "POST" { email := req.FormValue("email") password := req.FormValue("password") member, err := models.GetMember(email, password) if err != nil { responseWriter.Write([]byte(err.Error())) return } session, err := models.CreateSession(member) if err != nil { responseWriter.Write([]byte(err.Error())) return } var cookie http.Cookie cookie.Name = "sessionId" cookie.Value = session.SessionId() responseWriter.Header().Add("Set-Cookie", cookie.String()) } vm := viewmodels.GetLogin() this.template.Execute(responseWriter, vm) }
//User logout func (uc UsersController) logout(request *restful.Request, response *restful.Response) { token := func() string { for _, cookie := range request.Request.Cookies() { if cookie.Name == "AuthSession" { return cookie.Value } } return "" }() err := new(UserManager).Logout(token) if err != nil { LogError(request, response, err) WriteError(err, response) return } //Because CouchDB doesn't actually destroy the session, //best we can do is clear the cookie in the browser. //This is apparently "not a bug" :| //http://webmail.dev411.com/t/couchdb/dev/141xwf5vb0/jira-created-couchdb-2042-session-not-cleared-after-delete-session-cookie-auth theCookie := http.Cookie{ Name: "AuthSession", Value: "", Path: "/", HttpOnly: true, } response.AddHeader("Set-Cookie", theCookie.String()) response.WriteEntity(BooleanResponse{Success: true}) }
func (h *homeController) login(w http.ResponseWriter, req *http.Request) { responseWriter := util.GetResponseWriter(w, req) defer responseWriter.Close() w.Header().Add("Content Type", "text/html") if req.Method == "POST" { email := req.FormValue("email") password := req.FormValue("password") member, err := models.GetMember(email, password) if err == nil { session, err := models.CreateSession(member) log.Printf("create session err: %v", err) if err == nil { var cookie http.Cookie cookie.Name = "sessionId" cookie.Value = session.SessionId() responseWriter.Header().Add("Set-Cookie", cookie.String()) } } else { log.Print("User not found!") } } vm := viewmodels.GetLogin() h.loginTemplate.Execute(responseWriter, vm) }
func commitSession(headers Headers, env Env, key, secret, domain string) { cookie := new(http.Cookie) cookie.Name = key cookie.Value = encodeCookie(env["mango.session"].(map[string]interface{}), secret) cookie.Domain = domain headers.Add("Set-Cookie", cookie.String()) }
func setStickyCookieBackend(res *http.Response, backend string, cookieKey [32]byte) { cookie := http.Cookie{ Name: stickyCookie, Value: base64.StdEncoding.EncodeToString(encrypt([]byte(backend), cookieKey)), Path: "/", } res.Header.Add("Set-Cookie", cookie.String()) }
func (s *Session) DeleteCookie(options cookieOptions, response http.ResponseWriter) { cookie := http.Cookie{ Name: options.Name, Value: "-", MaxAge: -1, } response.Header().Set("Set-Cookie", cookie.String()) }
func clearAllCookies(rw http.ResponseWriter, req *http.Request) { for _, ck := range req.Cookies() { ck2 := http.Cookie{ Name: ck.Name, MaxAge: -1, } rw.Header().Add("Set-Cookie", ck2.String()) } }
func AddCsrfCookie(rw http.ResponseWriter, sessToken string) { csrfCookie := http.Cookie{ Name: "CsrfToken", Value: util.GenHashString(sessToken), Path: "/", HttpOnly: false, } rw.Header().Add("Set-Cookie", csrfCookie.String()) }
// 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()) }
// Duration is the cookie time-to-live in seconds (0 = forever). func (ctx *Context) SetCookie(name, value string, age int64) { var utctime time.Time if age == 0 { // 2^31 - 1 seconds (roughly 2038) utctime = time.Unix(2147483647, 0) } else { utctime = time.Unix(time.Now().Unix()+age, 0) } cookie := http.Cookie{Name: name, Value: value, Expires: utctime, Path: "/"} ctx.Header().Add("Set-Cookie", cookie.String()) }
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()) }
func (s *Session) WriteCookie(options cookieOptions, response http.ResponseWriter) { cookie := http.Cookie{ Name: options.Name, Value: s.ID, Expires: time.Now().Add(options.MaxAge), HttpOnly: options.HttpOnly, Secure: options.Secure, } response.Header().Set("Set-Cookie", cookie.String()) }
func ClearAuth(rw http.ResponseWriter) { //Clear the session cookie theCookie := http.Cookie{ Name: "AuthSession", Value: "", Path: "/", MaxAge: -1, HttpOnly: true, } rw.Header().Add("Set-Cookie", theCookie.String()) }
func (self *Cookie) Set(writer http.ResponseWriter, value string) { cookie := http.Cookie{ Name: self.Key, Value: value, Expires: expires, MaxAge: 630720000, } writer.Header().Set("Set-Cookie", cookie.String()) return }
func fetchHandler(w http.ResponseWriter, urlStr string, ctx appengine.Context) { ctx.Infof("fetchHandler urlStr arg is %s", urlStr) i := strings.LastIndex(urlStr, "/") baseUrlStr := urlStr[0 : i+1] expires := time.Now().Add(time.Minute) ctx.Infof("Setting expires to %s", expires) cookie := http.Cookie{Name: PROXY_BASE_URL_COOKIE, Value: baseUrlStr, Expires: expires} ctx.Infof("Setting cookie to %s", cookie.String()) http.SetCookie(w, &cookie) }
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()) }
//Add 增加,写入一条Cookie,可以写入多条Cookie保存至浏览器 func (c *Cookie) Add(name, value, path, domain string, maxAge int, secure, only bool) { var cookie = http.Cookie{ Name: name, Value: value, Path: path, Domain: domain, Expires: time.Now(), MaxAge: maxAge, Secure: secure, HttpOnly: only, } c.w.Header().Add("Set-Cookie", cookie.String()) }
// SetCookie adds a cookie header to the response. func (ctx *Context) SetCookie(name string, value string, a ...int) { var utctime time.Time var age int64 // seconds if len(a) > 0 { age = int64(a[0]) } if age == 0 { utctime = time.Unix(time.Now().Unix()+86400, 0) } else { utctime = time.Unix(time.Now().Unix()+age, 0) } cookie := http.Cookie{Name: name, Value: value, Expires: utctime} ctx.SetHeader("Set-Cookie", cookie.String()) }
func (this *homeController) login(w http.ResponseWriter, req *http.Request) { responseWriter := util.GetResponseWriter(w, req) defer responseWriter.Close() responseWriter.Header().Add("Content-Type", "text/html") vm := viewmodels.GetLogin() if req.FormValue("submit") == "signup" { http.Redirect(w, req, "/signup", http.StatusFound) } else { if req.Method == "POST" { email := req.FormValue("email") password := req.FormValue("password") member, err := models.GetMember(email, password) if err == nil { session, err := models.CreateSession(member) if err == nil { var cookie http.Cookie cookie.Name = "goSessionId" cookie.Expires = time.Now().Add(10 * time.Minute) cookie.Value = strconv.Itoa(session.MemberId()) responseWriter.Header().Add("Set-Cookie", cookie.String()) var cookie2 http.Cookie cookie2.Name = "loggedName" cookie2.Expires = time.Now().Add(10 * time.Minute) cookie2.Value = member.FirstName() responseWriter.Header().Add("Set-Cookie", cookie2.String()) } vmh := viewmodels.GetHome() vmh.LoggedIn = true vmh.LoggedName = member.FirstName() this.template.Execute(responseWriter, vmh) } else { this.loginTemplate.Execute(responseWriter, vm) } } else { this.loginTemplate.Execute(responseWriter, vm) } } }
// SetCookie adds a cookie header to the response. func (ctx *Context) SetCookie(name string, value string, a ...int) { var utctime time.Time var age int64 if len(a) > 0 { age = int64(a[0]) } if age == 0 { // 2^31 - 1 seconds (roughly 2038) utctime = time.Unix(2147483647, 0) } else { utctime = time.Unix(time.Now().Unix()+age, 0) } cookie := http.Cookie{Name: name, Value: value, Expires: utctime} ctx.AddHeader("Set-Cookie", cookie.String()) }
func (h *AuthCookieHandler) GenerateCookie(w http.ResponseWriter, req *http.Request) { authorization := req.Header.Get("Authorization") if authorization != "" { cookie := http.Cookie{ Name: receptor.AuthorizationCookieName, Value: authorization, MaxAge: 0, HttpOnly: true, } w.Header().Set("Set-Cookie", cookie.String()) } w.WriteHeader(http.StatusNoContent) }
func cookieString(ck *http.Cookie, reset_domain *string, setCookie bool) string { if !setCookie { // inaccurate return ck.Name + "=" + ck.Value } if reset_domain != nil { dot := strings.IndexByte(*reset_domain, '.') if dot > 1 { ck.Domain = *reset_domain } else { ck.Domain = NULL } } return ck.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 SetAuth(rw http.ResponseWriter, ca couchdb.Auth) { authData := ca.GetUpdatedAuth() if authData == nil { return } if val, ok := authData["AuthSession"]; ok { authCookie := http.Cookie{ Name: "AuthSession", Value: val, Path: "/", HttpOnly: true, } rw.Header().Add("Set-Cookie", authCookie.String()) AddCsrfCookie(rw, util.GenHashString(val)) } }
func (this *homeController) signup(w http.ResponseWriter, req *http.Request) { responseWriter := util.GetResponseWriter(w, req) defer responseWriter.Close() responseWriter.Header().Add("Content-Type", "text/html") if req.Method == "POST" { firstName := req.FormValue("firstName") email := req.FormValue("email") password := req.FormValue("password") err := models.InsertMember(firstName, email, password) if err == nil { member, _ := models.GetMember(email, password) member, errr := models.GetMember(email, password) if errr == nil { session, err := models.CreateSession(member) if err == nil { var cookie http.Cookie cookie.Name = "goSessionId" cookie.Expires = time.Now().Add(10 * time.Minute) cookie.Value = strconv.Itoa(session.MemberId()) responseWriter.Header().Add("Set-Cookie", cookie.String()) var cookie2 http.Cookie cookie2.Name = "loggedName" cookie2.Expires = time.Now().Add(10 * time.Minute) cookie2.Value = member.FirstName() responseWriter.Header().Add("Set-Cookie", cookie2.String()) } http.Redirect(w, req, "/home", http.StatusFound) } } } vm := viewmodels.GetSignup() this.signupTemplate.Execute(responseWriter, vm) }
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 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()) }