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 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 }
func HandleComment(c *webapp.Context) { if c.Request.Method == "POST" { IP := strings.Split(c.Request.RemoteAddr, ":")[0] comment := new(Comment) comment.Metadata.Name = UUID() comment.Metadata.IP = IP comment.Metadata.CreatedTime = time.Now().Unix() comment.Metadata.Author = strings.Trim(c.Request.FormValue("author"), " ") comment.Metadata.ArticleName = strings.Trim(c.Request.FormValue("article_name"), " /") comment.Metadata.UAgent = strings.Trim(c.Request.UserAgent(), " ") comment.Metadata.Email = strings.Trim(c.Request.FormValue("email"), " ") comment.Metadata.URL = strings.Trim(c.Request.FormValue("url"), " ") if strings.Index(comment.Metadata.URL, "http://") == -1 && strings.Index(comment.Metadata.URL, "https://") == -1 { comment.Metadata.URL = "http://" + comment.Metadata.URL } comment.Text = template.HTML(strings.Trim(c.Request.FormValue("text"), " ")) var cookie *http.Cookie expires := time.Date(2099, time.November, 10, 23, 0, 0, 0, time.UTC) cookie = new(http.Cookie) cookie.Path = "/" cookie.Expires = expires cookie.Name = "author" cookie.Value = comment.Metadata.Author http.SetCookie(c.Writer, cookie) cookie.Name = "email" cookie.Value = comment.Metadata.Email http.SetCookie(c.Writer, cookie) cookie.Name = "url" cookie.Value = comment.Metadata.URL http.SetCookie(c.Writer, cookie) // verify the form data if len(comment.Metadata.Author) == 0 || len(comment.Metadata.Email) < 3 || len(comment.Text) < 3 || len(comment.Metadata.Author) > 20 || len(comment.Metadata.Email) > 32 { c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound) return } if !webapp.CheckEmailForm(comment.Metadata.Email) || (0 < len(comment.Metadata.URL) && !webapp.CheckURLForm(comment.Metadata.URL)) { c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound) return } if !TattooDB.Has(comment.Metadata.ArticleName) { c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound) return } comment.Text = template.HTML(webapp.TransformTags(string(comment.Text))) comment.Metadata.EmailHash = MD5Sum(comment.Metadata.Email) TattooDB.AddComment(comment) TattooDB.PrependCommentTimeline(comment) c.Redirect("/"+comment.Metadata.ArticleName+"#comment_"+comment.Metadata.Name, http.StatusFound) } else { c.Redirect("/"+c.Request.FormValue("article_name"), http.StatusFound) } }
func (s sessionResponseWriter) WriteHeader(code int) { if atomic.AddInt32(&s.wroteHeader, 1) == 1 { origCookie, err := s.req.Cookie(s.h.CookieName) var origCookieVal string if err != nil { origCookieVal = "" } else { origCookieVal = origCookie.Value } session := s.h.RS.Get(s.req) if len(session) == 0 { // if we have an empty session, but the // request didn't start out that way, we // assume the user wants us to clear the // session if origCookieVal != "" { //log.Println("clearing cookie") var cookie http.Cookie cookie.Name = s.h.CookieName cookie.Value = "" cookie.Path = "/" // a cookie is expired by setting it // with an expiration time in the past cookie.Expires = time.Unix(0, 0).UTC() http.SetCookie(s, &cookie) } goto write } encoded, gobHash, err := encodeCookie(session, s.h.encKey, s.h.hmacKey) if err != nil { log.Printf("createCookie: %s\n", err) goto write } if bytes.Equal(gobHash, s.h.RS.getHash(s.req)) { //log.Println("not re-setting identical cookie") goto write } var cookie http.Cookie cookie.Name = s.h.CookieName cookie.Value = encoded cookie.Path = s.h.CookiePath cookie.HttpOnly = s.h.RS.HttpOnly cookie.Secure = s.h.RS.Secure http.SetCookie(s, &cookie) } write: s.ResponseWriter.WriteHeader(code) }
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) } } }
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 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 (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 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") }
// Answers to /sso, returns the SSO cookie and redirects to /startpage func handler(w http.ResponseWriter, r *http.Request) { re := regexp.MustCompile("CN=([ 0-9A-Za-z_]+)") user := r.Header.Get("Certificate-User") if user == "" { log.Panicf("Did not get user!") } match := re.FindStringSubmatch(user) if len(match) != 2 { log.Panicf("No CN found!") } cn := match[1] sessionid := getSessionID(cn, r.Header.Get("X-Forwarded-For")) token := generate_session_token(sessionid, cn) signature := sign_session_token(token) cookie := http.Cookie{} cookie.Name = "PLAY_SESSION" cookie.Value = signature + "-" + token cookie.Path = "/" cookie.Domain = external_host cookie.Expires = time.Now().Add(356 * 24 * time.Hour) cookie.HttpOnly = true http.SetCookie(w, &cookie) http.Redirect(w, r, "/startpage", http.StatusFound) }
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 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 } }
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 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") } }
// Redirects the User to the OAuth1.0a provider's Login Screen. A RequestToken // is requested from the Provider, and included in the URL's oauth_token param. // // A Successful Login / Authorization should return both the oauth_token and // the oauth_verifier to the callback URL. func (self *OAuth1Mixin) AuthorizeRedirect(w http.ResponseWriter, r *http.Request, endpoint string) error { //Get a Request Token token, err := self.Consumer.RequestToken() if err != nil { return err } //Get the redirect URL url, err := self.Consumer.AuthorizeRedirect(token) if err != nil { return err } //Write the Request Token to a Cookie, so that we can //retrieve it after re-directing the user to the //providers authorization screen. cookie := http.Cookie{} cookie.Name = "_token" cookie.Path = "/" cookie.Domain = r.URL.Host cookie.HttpOnly = true cookie.Secure = Config.CookieSecure cookie.Value = token.Encode() http.SetCookie(w, &cookie) // redirect to the login url http.Redirect(w, r, url, http.StatusSeeOther) return nil }
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 (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 TestSignedCookie(t *testing.T) { key := "whitelove" uc := new(http.Cookie) uc.Name = "rawcookie" uc.Value = "ilovespeed" sc := new(http.Cookie) sc.Name = uc.Name sc.Value = Sign(uc.Value, key) r, _ := http.NewRequest("GET", "http://example.com/foo", nil) r.AddCookie(sc) req := NewRequest(r) c, err := req.SignedCookie(sc.Name, key) if c.Value != uc.Value { t.Errorf("SingedCookie error: (%q)\n"+ "\twant: %q\n\tgot:%q", err, uc.Value, c.Value) } // invalid key case. c, err = req.SignedCookie(sc.Name, "invalidkey") if c != nil { t.Errorf("SingedCookie should not return a cookie but got %v", c) } if err != ErrSignatureModified { t.Errorf("SignedCookie should return an ErrSignatureModified if invalid key is passed, but got none") } // not found case. c, err = req.SignedCookie("notfound", key) if c != nil { t.Errorf("SingedCookie should not return a cookie but got %v", c) } if err != http.ErrNoCookie { t.Errorf("SignedCookie should return http.ErrNoCookie but got %v", err) } // invalid format value passed from a client. sc.Value = "foo" r, _ = http.NewRequest("GET", "http://example.com/foo", nil) r.AddCookie(sc) req = NewRequest(r) c, err = req.SignedCookie(sc.Name, key) if err != ErrWrongSignatureFormat { t.Errorf("SignedCookie should return ErrWrongSignatureFormat but got %v", err) } }
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 (auth *FormsAuthenticator) createAuthCookie(jwtString string) *http.Cookie { cookie := http.Cookie{} cookie.Name = auth.CookieName cookie.Expires = auth.getCookieExpirationTime() cookie.HttpOnly = true cookie.Path = "/" cookie.Value = jwtString return &cookie }
func constructCookie(name string, value string) *http.Cookie { cookie := new(http.Cookie) cookie.Name = name cookie.Value = value cookie.Path = "/" cookie.HttpOnly = false cookie.Secure = false return cookie }
func (s *FormsAuthSuite) createCookie(token string) http.Cookie { cookie := http.Cookie{} cookie.Name = FormsAuthenticatorDefaultCookieName cookie.Expires = time.Now().UTC().Add(24 * 365 * time.Hour) cookie.HttpOnly = true cookie.Path = "/" cookie.Value = token return cookie }
func newCookie(r *http.Request, session *Session) *http.Cookie { cookie := new(http.Cookie) cookie.Name = "UH" cookie.Value = session.Id cookie.Expires = session.Expires cookie.Path = "/" cookie.Domain = r.URL.Host return cookie }
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 }
//setCookie set cookie access=now time,tmpaccess=access var. func (t *threadCGI) setCookie(ca *thread.Cache, access string) []*http.Cookie { const ( saveCookie = 7 * 24 * time.Hour // Seconds ) c := http.Cookie{} c.Expires = time.Now().Add(saveCookie) c.Path = cfg.ThreadURL + "/" + util.StrEncode(util.FileDecode(ca.Datfile)) c.Name = "access" c.Value = strconv.FormatInt(time.Now().Unix(), 10) if access == "" { return []*http.Cookie{&c} } cc := http.Cookie{} cc.Name = "tmpaccess" cc.Value = access return []*http.Cookie{&c, &cc} }
// 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 }
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 cookie(val string) *http.Cookie { c := new(http.Cookie) c.Name = config.Cookie c.Value = val c.Domain = config.ServerDomain c.Path = config.CookiePath c.HttpOnly = config.CookieHttpOnly c.Secure = config.CookieSecure return c }