func LogoutHandler(c *gin.Context) { var userCookie http.Cookie userCookie.Name = "user" userCookie.MaxAge = -1 http.SetCookie(c.Writer, &userCookie) c.Redirect(http.StatusMovedPermanently, "/") }
func (p *Login) addUuidCookie(c *gin.Context, uuid string) { cookie := new(http.Cookie) cookie.Name = "uuid" cookie.Value = uuid cookie.Path = "/" http.SetCookie(c.Writer, cookie) }
/* получить актуальную сессию */ 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 TestSignedCookie(t *testing.T) { context := MakeTestContext() cookie := new(http.Cookie) cookie.Name = "userId" cookie.Value = "2468" signedCookie, err := context.AddSignedCookie(cookie) if err != nil { t.Errorf("Shouldn't error: %s", err) } // set the request headers context.Request.Header = make(http.Header) context.Request.AddCookie(cookie) context.Request.AddCookie(signedCookie) returnedCookie, cookieErr := context.SignedCookie(cookie.Name) if cookieErr != nil { t.Errorf("SignedCookie shouldn't return error: %s", cookieErr) return } if returnedCookie == nil { t.Errorf("SignedCookie shouldn't return nil") return } assertEqual(t, returnedCookie.Name, cookie.Name, "name") }
func TestSignedCookie_Tempered(t *testing.T) { context := MakeTestContext() cookie := new(http.Cookie) cookie.Name = "userId" cookie.Value = "2468" signedCookie, err := context.AddSignedCookie(cookie) if err != nil { t.Errorf("Shouldn't error: %s", err) } // temper with the cookie cookie.Value = "something-else" // set the request headers context.Request.Header = make(http.Header) context.Request.AddCookie(cookie) context.Request.AddCookie(signedCookie) returnedCookie, cookieErr := context.SignedCookie(cookie.Name) if cookieErr == nil { t.Errorf("SignedCookie SHOULD return error") } if returnedCookie != nil { t.Errorf("ReturnedCookie should be nil") } }
//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 CreateCookie(u string, db *sql.DB, persistent bool, app bool) (http.Cookie, error) { alphaNum := []byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv") randValue := "" for i := 0; i < 32; i++ { num, err := RandKey(58) if err != nil { return http.Cookie{}, err } randValue = randValue + string(alphaNum[num]) } authCookie := http.Cookie{ Name: "5sur", Value: randValue, Path: "/", Domain: "5sur.com", // Add domain name in the future Secure: true, // SSL only HttpOnly: true, // HTTP(S) only } if persistent { authCookie.Expires = time.Now().AddDate(0, 1, 0) // One month from now } else { // Session cookie } err := updateSession(randValue, u, db, app) if err != nil { return http.Cookie{}, err } return authCookie, nil }
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) }
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 (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 HandleGuard(c *webapp.Context) { var err error action := c.Request.FormValue("action") if action == "logout" { RevokeSessionTokon() c.Redirect("/guard", http.StatusFound) return } if c.Request.Method == "POST" { cert := c.Request.FormValue("certificate") if len(cert) == 0 { c.Redirect("/guard", http.StatusFound) return } if SHA256Sum(cert) == GetConfig().Certificate { cookie := new(http.Cookie) cookie.Name = "token" cookie.Path = "/" cookie.Value = GenerateSessionToken() http.SetCookie(c.Writer, cookie) c.Redirect("/writer", http.StatusFound) } else { err = RenderGuard(c, "Your password is not correct") if err != nil { c.Error(fmt.Sprintf("%s: %s", webapp.ErrInternalServerError, err), http.StatusInternalServerError) } } } else if c.Request.Method == "GET" { err = RenderGuard(c, "") if err != nil { c.Error(fmt.Sprintf("%s: %s", webapp.ErrInternalServerError, err), http.StatusInternalServerError) } } }
func TestValidateSignedCookie_MissingCookie(t *testing.T) { context := MakeTestContext() cookie := new(http.Cookie) cookie.Name = "userId" cookie.Value = "2468" signedCookie, err := context.AddSignedCookie(cookie) if err != nil { t.Errorf("Shouldn't error: %s", err) } // set the request headers context.Request.Header = make(http.Header) context.Request.AddCookie(signedCookie) valid, validErr := context.cookieIsValid(cookie.Name) if validErr != CookieIsMissing { t.Errorf("Should error CookieIsMissing") } assertEqual(t, valid, false, "cookieIsValid should be false") }
func roothandler(w http.ResponseWriter, r *http.Request) { u := getUser(r) if r.Method == "GET" { var filename string if u != nil { filename = "static/index.html" } else { filename = "static/login.html" } file, err := os.Open(filename) if err != nil { http.NotFound(w, r) } else { io.Copy(w, file) file.Close() } return } if r.Method == "POST" { r.ParseForm() var u *User var err error if len(r.Form["login"]) > 0 { username := r.Form["username"][0] password := r.Form["password"][0] u, err = dbAuthUser(username, password) } else if len(r.Form["register"]) > 0 { username := r.Form["username"][0] password := r.Form["password"][0] email := r.Form["email"][0] u, err = dbAddUser(username, password, email) } else { http.NotFound(w, r) return } if err != nil { w.WriteHeader(401) w.Write([]byte(err.Error())) return } value, err := authenticateUser(u) if err != nil { w.WriteHeader(401) w.Write([]byte(err.Error())) return } c := new(http.Cookie) c.Name = "auth" c.Value = *value http.SetCookie(w, c) http.Redirect(w, r, "spmc/", 301) return } }
// 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 }
// cookie returns an http.Cookie containing the signed session. func (s Session) cookie() *http.Cookie { var sessionValue string ts := s.getExpiration() s[TIMESTAMP_KEY] = getSessionExpirationCookie(ts) for key, value := range s { if strings.ContainsAny(key, ":\x00") { panic("Session keys may not have colons or null bytes") } if strings.Contains(value, "\x00") { panic("Session values may not have null bytes") } sessionValue += "\x00" + key + ":" + value + "\x00" } sessionData := url.QueryEscape(sessionValue) cookie := http.Cookie{ Name: revel.CookiePrefix + "_SESSION", Value: revel.Sign(sessionData) + "-" + sessionData, Path: "/", HttpOnly: revel.CookieHttpOnly, Secure: revel.CookieSecure, Expires: ts.UTC(), } if cookieDomain != "" { cookie.Domain = cookieDomain } return &cookie }
func handleLogin(w http.ResponseWriter, r *http.Request) { login := r.FormValue("login") password := r.FormValue("password") usersConfiguration := GetUsersConfiguration() user, userFindErr := usersConfiguration.getUserByName(login) if userFindErr != nil { fmt.Fprint(w, RenderLoginPage(&userFindErr)) return } if user.Password != password { passwordMistmatchError := errors.New("Password mistmatch") fmt.Fprint(w, RenderLoginPage(&passwordMistmatchError)) return } cookie := new(http.Cookie) cookie.Name = "loginToken" cookie.Value = login http.SetCookie(w, cookie) runner := GetAnalyzeRunner() fmt.Fprint(w, RenderMainPage(runner.IsRunning(), user)) }
func SetCookieVal(w http.ResponseWriter, name string, value string, path string) { var C http.Cookie C.Name = name C.Value = value C.Path = path C.Expires = time.Now().AddDate(0, 1, 0) http.SetCookie(w, &C) }
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 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 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()) }
func createCookie(key, val string) *http.Cookie { cookie := new(http.Cookie) cookie.Name = key cookie.Value = val cookie.HttpOnly = false cookie.Path = "/" // Without this ang js cant read cookies we send //cookie.Expires = expire return cookie }
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 (this *Ctx) SetCookie(key string, value string, expires int64) { var cookie http.Cookie cookie.Name = key cookie.Value = value cookie.Expires = time.Unix(time.Now().Unix()+expires, 0) // this.W.Header().Add("Set-Cookie", cookie.String()) http.SetCookie(this.W, cookie) }
func SetCookie(w http.ResponseWriter, k, v string, exp int32) { var ck http.Cookie ck.Name = k ck.Path = "/" ck.Value = v if exp != 0 { ck.Expires = time.Now().Add(time.Second * time.Duration(exp)) } http.SetCookie(w, &ck) }
func getRequest(port int) *http.Request { req, _ := http.NewRequest("GET", "http://localhost:"+strconv.Itoa(port)+"/test", nil) ck1 := new(http.Cookie) ck1.Name = "test" ck1.Value = "value" req.AddCookie(ck1) return req }
// TestMinSessionHandlerBadCookie tests if a MinSessionHandler recognizes a bad // cookie. // // Steps: // 1. Create a new MinSessionHandler to test. // 2. Run the cookie mask in order to get a good cookie. // 3. Tamper with the cookie. // 4. Run the cookie mask with the tampered cookie. // 5. Verify that the bad cookie was rejected and replaced by another good // cookie. func TestMinSessionHandlerBadCookie(t *testing.T) { /* setup */ var local_cookies []*http.Cookie var bad_cookie http.Cookie /* run */ handler := NewMinSessionHandler("testHandler", "/", "example.com") sesh1, err := handler.GetSession() assert.NoError(t, err) fwd1, stc1, err1 := sesh1.CookieMask(nil) for _, cookie := range stc1 { cookie.Value = cookie.Value + "bad" bad_cookie.Name = cookie.Name bad_cookie.Value = cookie.Value local_cookies = append(local_cookies, cookie) } sesh2, err := handler.GetSession() assert.NoError(t, err) fwd2, stc2, err2 := sesh2.CookieMask(local_cookies) /* check */ assert.NoError(t, err1) assert.NoError(t, err2) assert.Nil(t, fwd1) assert.Nil(t, fwd2) assert.NotNil(t, stc1) if stc1 != nil { assert.Equal(t, 1, len(stc1)) } assert.NotNil(t, stc2) if stc2 != nil { assert.Equal(t, 2, len(stc2)) } bad_cookie_deleted := false for _, cookie := range stc2 { if cookie.Name == bad_cookie.Name { assert.Equal(t, bad_cookie.Value, cookie.Value) assert.Equal(t, -1, cookie.MaxAge) bad_cookie_deleted = true } } assert.True(t, bad_cookie_deleted) assert.NotNil(t, sesh1) /* if sesh1 != nil { assert.Equal(t, 0, len(sesh1)) } */ assert.NotNil(t, sesh2) /* if sesh2 != nil { assert.Equal(t, 0, len(sesh2)) } */ }
// 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 }
// 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 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) }