func (s *sessionData) Validate(r *http.Request) (validSessionID bool, validXSRFToken bool, err error) { validSessionID = false validXSRFToken = false sessionID, err := r.Cookie("Interlock-Token") if err != nil { return } XSRFToken := r.Header.Get("X-XSRFToken") session.Lock() defer session.Unlock() if session.SessionID == sessionID.Value { validSessionID = true } else { err = errors.New("invalid session") } if session.XSRFToken == XSRFToken { validXSRFToken = true } else { err = errors.New("missing XSRFToken") } return }
//Serves index.html func serve_the_webpage(res http.ResponseWriter, req *http.Request) { tpl, err := template.ParseFiles("index.html") if err != nil { log.Fatalln(err) } cookie, err := req.Cookie("session-fino") //create cookie if not exists. if err != nil { id, _ := uuid.NewV4() cookie = &http.Cookie{ Name: "session-fino", HttpOnly: true, } } user := new(User) //create new User instance. b64 := set_user(req, user) if req.FormValue("user_name") != "" { cookie_id := strings.Split(cookie.Value, "|") cookie.Value = cookie_id[0] + "|" + b64 } http.SetCookie(res, cookie) tpl.Execute(res, nil) }
func foo(res http.ResponseWriter, req *http.Request) { templ, error := template.ParseFiles("tpl.gohtml") // Parse template file if error != nil { log.Fatalln(error) } error = templ.Execute(os.Stdout, nil) if error != nil { log.Fatalln(error) } cookie, err := req.Cookie("session-fino") if err != nil { // id, _ := uuid.NewV4() cookie = &http.Cookie{ Name: "session-fino", Value: "0", // Secure: true, HttpOnly: true, } } count, _ := strconv.Atoi(cookie.Value) count++ cookie.Value = strconv.Itoa(count) fmt.Println(cookie) http.SetCookie(res, cookie) templ.ExecuteTemplate(res, "tpl.gohtml", cookie) }
func getID(res http.ResponseWriter, req *http.Request) (string, error) { var id, origin string var cookie *http.Cookie // try to get the id from the COOKIE origin = "COOKIE" cookie, err := req.Cookie("session-id") if err == http.ErrNoCookie { // try to get the id from the URL origin = "URL" id := req.FormValue("id") if id == "" { // no id, so create one BRAND NEW origin = "BRAND NEW VIA LOGOUT" log.Println("ID CAME FROM", origin) http.Redirect(res, req, "/logout", http.StatusSeeOther) return id, errors.New("ERROR: redirect to /logout because no session id accessible") } // try to store id for later use in COOKIE cookie = &http.Cookie{ Name: "session-id", Value: id, // Secure: true, HttpOnly: true, } http.SetCookie(res, cookie) } id = cookie.Value log.Println("ID CAME FROM", origin) return id, nil }
func getID(w http.ResponseWriter, r *http.Request) string { var userUUID string var cookie *http.Cookie cookie, err := r.Cookie("session-id") if err == http.ErrNoCookie { userUUID = r.FormValue("id") if userUUID == "" { uuid, _ := uuid.NewV4() userUUID = uuid.String() http.Redirect(w, r, "/?id="+userUUID, 303) } modelForCookie := model{ Name: "session-id", State: false, Pictures: []string{ "one.jpg", }, ID: userUUID, } makeCookie(modelForCookie, userUUID, r) http.SetCookie(w, cookie) return userUUID } return cookie.Value }
// getSid retrieves session identifier from HTTP Request. // First try to retrieve id by reading from cookie, session cookie name is configurable, // if not exist, then retrieve id from querying parameters. // // error is not nil when there is anything wrong. // sid is empty when need to generate a new session id // otherwise return an valid session id. func (manager *Manager) getSid(r *http.Request) (string, error) { cookie, errs := r.Cookie(manager.config.CookieName) if errs != nil || cookie.Value == "" { var sid string if manager.config.EnableSidInUrlQuery { errs := r.ParseForm() if errs != nil { return "", errs } sid = r.FormValue(manager.config.CookieName) } // if not found in Cookie / param, then read it from request headers if manager.config.EnableSidInHttpHeader && sid == "" { sids, isFound := r.Header[manager.config.SessionNameInHttpHeader] if isFound && len(sids) != 0 { return sids[0], nil } } return sid, nil } // HTTP Request contains cookie for sessionid info. return url.QueryUnescape(cookie.Value) }
// ExtractToken reads an auth token from the request, and parse it as jwt. // The second return argument will be true if the jwt is missind, malformed, or expired. // Caller should make sure the browser will redirect to login page in that case. func (auth *FormsAuthenticator) ExtractToken(r *http.Request) (*jwt.Token, bool) { cookie, err := r.Cookie(auth.CookieName) if err != nil { return nil, true } jwtString := cookie.Value token, err := jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return auth.SignKey, nil }) if err != nil || !token.Valid { if ve, ok := err.(*jwt.ValidationError); ok { // Expiration is not exceptional, so no need to log here. errorIsExpiration := ve.Errors&jwt.ValidationErrorExpired != 0 if !errorIsExpiration { fmt.Printf("Auth token error [%s]: %s\n", jwtString, err.Error()) } } return nil, true } return token, false }
func sendMessageHandle(w http.ResponseWriter, r *http.Request) { if !checkCookie(r) { redirectToLogin(w, r) return } textByte, err := ioutil.ReadAll(r.Body) //the error here can't be that the cookie doesn't exist, since we checked that //in checkCookie()) cookie, err := r.Cookie("Session") check(err) user := findUserBySession(cookie.Value) messageID := user.Uuid.String() + ":" + strconv.Itoa(user.MessageSequence) messageUUID := user.Uuid.String() messageNo := user.MessageSequence originator := user.Username text := string(textByte) toStore := Rumor{messageID, messageUUID, messageNo, originator, text} saveMessage(toStore) incrementMessageNumber(user.ID) }
func (r *room) ServeHTTP(w http.ResponseWriter, req *http.Request) { socket, err := upgrader.Upgrade(w, req, nil) // Upgrade upgrades the HTTP server connection to the WebSocket protocol. if err != nil { log.Fatal("ServeHTTP:", err) return } authCookie, err := req.Cookie("auth") if err != nil { log.Fatal("クッキーの取得に失敗しました:", err) return } client := &client{ socket: socket, send: make(chan *message, messageBufferSize), room: r, userData: objx.MustFromBase64(authCookie.Value), } r.join <- client defer func() { r.leave <- client }() go client.write() client.read() }
// Parse parses the SAMLResponse func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) { allowIdPInitiated := "" possibleRequestIDs := []string{allowIdPInitiated} // Find the request id that relates to this RelayState. relayState := r.PostFormValue("RelayState") if sp.cookieSecret() != nil && relayState != "" { cookieName := fmt.Sprintf("saml_%s", relayState) cookie, err := r.Cookie(cookieName) if err != nil { return nil, fmt.Errorf("cannot find %s cookie", cookieName) } // Verify the integrity of the cookie. state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) { return sp.cookieSecret(), nil }) if err != nil || !state.Valid { return nil, fmt.Errorf("could not decode state JWT: %v", err) } claims := state.Claims.(jwt.MapClaims) id := claims["id"].(string) possibleRequestIDs = append(possibleRequestIDs, id) // delete the cookie cookie.Value = "" cookie.Expires = time.Time{} http.SetCookie(w, cookie) } samlResponse := r.PostFormValue("SAMLResponse") return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs) }
func ControllerAuthenticate(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() switch r.Method { case "GET": case "POST": _, err := r.Cookie("sid") if err != nil { user := r.PostFormValue("username") password := r.PostFormValue("password") expiration := time.Now().Add(365 * 24 * time.Hour) if authenticateUser(user, password) { cookie := http.Cookie{ Name: "sid", Value: user + password, Expires: expiration} http.SetCookie(w, &cookie) } } http.Redirect(w, r, "/", http.StatusSeeOther) case "PUT": case "DELETE": default: } }
// IsAuthenticatedMiddleware ... func (h *Handler) IsAuthenticatedMiddleware(ctx context.Context, rw http.ResponseWriter, r *http.Request) context.Context { cookie, err := r.Cookie("sid") if err != nil { switch err { case http.ErrNoCookie: return h.renderTemplate400(rw, ctx) default: return h.renderTemplate500(rw, ctx, err) } } session := mnemosyne.Session{} err = h.Container.Mnemosyne.Call("Store.Get", mnemosyne.SessionID(cookie.Value), &session) if err != nil { switch err.Error() { case mnemosyne.ErrSessionNotFound.Error(): return h.renderTemplate403(rw, ctx) default: return h.renderTemplate500(rw, ctx, err) } } // TODO(piotr): current user status need to be checked (is_active, is_confirmed etc) return context.WithValue(ctx, "session", session) }
func currentLocale(req *http.Request) string { locale := "en-US" if cookie, err := req.Cookie("locale"); err == nil { locale = cookie.Value } return locale }
func Handle(w http.ResponseWriter, r *http.Request) { context := appengine.NewContext(r) now := time.Now() expire := now.AddDate(30, 0, 0) zcookie, _ := r.Cookie("z") if zcookie == nil { zcookie = &http.Cookie{} zcookie.Name = "z" zcookie.Value = make_hash("127.0.0.1", r.RemoteAddr, now.UnixNano()) zcookie.Expires = expire zcookie.Path = "/" zcookie.Domain = config.DOMAIN http.SetCookie(w, zcookie) } context.Infof("%s", zcookie.Value) w.Header().Set("Content-type", "image/gif") w.Header().Set("Cache-control", "no-cache, must-revalidate") w.Header().Set("Expires", "Sat, 26 Jul 1997 05:00:00 GMT") fmt.Fprintf(w, "%s", GIF) channel.Send(context, "pi", zcookie.Value+"\n"+r.RemoteAddr+"\n"+r.Referer()+"\n"+r.FormValue("r")+"\n"+r.UserAgent()) }
// Loads a session based on the session ID in the Cookie HTTP header or URL // query string, or creates a new session if neither exists func (store *BASessionStore) Get(w http.ResponseWriter, r *http.Request) *BASession { // Find the session ID: var sessionID string // - #1: look at the value of the "sessid" cookie in the Cookie HTTP header if c, err := r.Cookie(SESSION_ID_COOKIE_NAME); err == nil && regexp.MustCompile("^[0-9a-f]{40}").MatchString(c.Value) { sessionID = c.Value //log.Printf("BASessionStore Get(): got session ID from cookie: %s", sessionID) // - #2: look at the value of the "sessid" key in the URL query string } else if r.ParseForm(); r.Form[SESSION_ID_COOKIE_NAME] != nil && regexp.MustCompile("^[0-9a-f]{40}").MatchString(r.Form.Get(SESSION_ID_COOKIE_NAME)) { sessionID = r.Form.Get(SESSION_ID_COOKIE_NAME) //log.Printf("BASessionStore Get(): got session ID from query string: %s", sessionID) // - Otherwise, no session ID was sent with this request: generate a new one // based on the session ID salt in server.cfg, the remote IP and user agent // string, and set it as the value of the "sessid" cookie } else { newSession := store.New(w, r) //log.Printf("BASessionStore Get(): no session ID found, set new: %s", newSession.Id) return newSession } return &BASession{ MemcachedClient: store.MemcachedClient, Id: sessionID, } }
func login(c *api.Context, w http.ResponseWriter, r *http.Request) { if !CheckBrowserCompatability(c, r) { return } params := mux.Vars(r) teamName := params["team"] var team *model.Team if tResult := <-api.Srv.Store.Team().GetByName(teamName); tResult.Err != nil { l4g.Error("Couldn't find team name=%v, teamURL=%v, err=%v", teamName, c.GetTeamURL(), tResult.Err.Message) http.Redirect(w, r, api.GetProtocol(r)+"://"+r.Host, http.StatusTemporaryRedirect) return } else { team = tResult.Data.(*model.Team) } // If we are already logged into this team then go to home if len(c.Session.UserId) != 0 && c.Session.TeamId == team.Id { page := NewHtmlTemplatePage("home", "Home") page.Props["TeamURL"] = c.GetTeamURL() page.Render(c, w) return } // We still might be able to switch to this team because we've logged in before if multiCookie, err := r.Cookie(model.MULTI_SESSION_TOKEN); err == nil { multiToken := multiCookie.Value if len(multiToken) > 0 { tokens := strings.Split(multiToken, " ") for _, token := range tokens { if sr := <-api.Srv.Store.Session().Get(token); sr.Err == nil { s := sr.Data.(*model.Session) if !s.IsExpired() && s.TeamId == team.Id { w.Header().Set(model.HEADER_TOKEN, s.Token) sessionCookie := &http.Cookie{ Name: model.SESSION_TOKEN, Value: s.Token, Path: "/", MaxAge: model.SESSION_TIME_WEB_IN_SECS, HttpOnly: true, } http.SetCookie(w, sessionCookie) http.Redirect(w, r, c.GetSiteURL()+"/"+team.Name+"/channels/town-square", http.StatusTemporaryRedirect) return } } } } } page := NewHtmlTemplatePage("login", "Login") page.Props["TeamDisplayName"] = team.DisplayName page.Props["TeamName"] = team.Name page.Render(c, w) }
func logout(res http.ResponseWriter, req *http.Request, _ httprouter.Params) { ctx := appengine.NewContext(req) cookie, err := req.Cookie("session") // cookie is not set if err != nil { http.Redirect(res, req, "/", 302) return } // clear memcache sd := memcache.Item{ Key: cookie.Value, Value: []byte(""), Expiration: time.Duration(1 * time.Microsecond), } memcache.Set(ctx, &sd) // clear the cookie cookie.MaxAge = -1 http.SetCookie(res, cookie) // redirect http.Redirect(res, req, "/", 302) }
func cookieid(w http.ResponseWriter, r *http.Request) { name := r.FormValue("name") age := r.FormValue("age") data := foo(name, age) code := getCode(data) cookie, err := r.Cookie("sessio-info") if err != nil { id, _ := uuid.NewV4() cookie = &http.Cookie{ Name: "session-info", Value: id.String() + "|" + name + "|" + age + "|" + data + "|" + code, HttpOnly: true, } http.SetCookie(w, cookie) io.WriteString(w, `<!DOCTYPE html> <html> <head> <title>Project-5</title> </head> <body> <form method="POST"> Name: <input type="text" name="name"><br> Age: <input type="text" name="age"><br> <input type="submit"> </form> </body> </html> `) } fmt.Fprint(w, "Value: ", cookie.Value) }
func Handler(response http.ResponseWriter, request *http.Request) { fmt.Println(request.Method) fmt.Println("Entrou no handler") fmt.Println(len(request.Cookies())) token, err := request.Cookie("token") fmt.Println(token.Value, err) data := url.Values{} data.Set("access_token", token.Value) //req = http.NewRequest("POST", "https://www.googleapis.com/oauth2/v1/tokeninfo", nil) resp, err := http.Post("https://www.googleapis.com/oauth2/v1/tokeninfo", "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode())) //req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param="+token) //http. var retorno ValidaToken json.NewDecoder(resp.Body).Decode(&retorno) fmt.Println(retorno.Error, retorno.Email) switch request.Method { case "GET": provas := Provas() fmt.Println(provas) js, _ := json.MarshalIndent(provas, " ", " ") response.Write(js) case "POST": var prova Prova json.NewDecoder(request.Body).Decode(&prova) err := Insere(&prova) fmt.Println(err) } }
func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) { sid := manager.sessionId(r) cookie, err := r.Cookie(manager.cookieName) if err != nil && cookie.Value == "" { //delete old cookie session, _ = manager.provider.SessionRead(sid) cookie = &http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: manager.secure, } } else { oldsid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRegenerate(oldsid, sid) cookie.Value = url.QueryEscape(sid) cookie.HttpOnly = true cookie.Path = "/" } if manager.maxage >= 0 { cookie.MaxAge = manager.maxage } http.SetCookie(w, cookie) r.AddCookie(cookie) return }
// TokenFromRequest extracts the ID token from the HTTP request if present. func (c *Client) TokenFromRequest(req *http.Request) string { cookie, _ := req.Cookie(c.config.CookieName) if cookie == nil { return "" } return cookie.Value }
func putCookie(res http.ResponseWriter, req *http.Request, fname string) (map[string]bool, error) { mss := make(map[string]bool) cookie, _ := req.Cookie("file-names") if cookie != nil { bs, err := base64.URLEncoding.DecodeString(cookie.Value) if err != nil { return nil, fmt.Errorf("ERROR handler base64.URLEncoding.DecodeString: %s", err) } err = json.Unmarshal(bs, &mss) if err != nil { return nil, fmt.Errorf("ERROR handler json.Unmarshal: %s", err) } } mss[fname] = true bs, err := json.Marshal(mss) if err != nil { return mss, fmt.Errorf("ERROR putCookie json.Marshal: ", err) } b64 := base64.URLEncoding.EncodeToString(bs) // FYI ctx := appengine.NewContext(req) log.Infof(ctx, "COOKIE JSON: %s", string(bs)) http.SetCookie(res, &http.Cookie{ Name: "file-names", Value: b64, }) return mss, nil }
func serve_the_webpage(res http.ResponseWriter, req *http.Request) { tpl, err := template.ParseFiles("appform.html") if err != nil { log.Fatalln(err) } cookie, err := req.Cookie("session-information") if err != nil { id, _ := uuid.NewV4() cookie = &http.Cookie{ Name: "session-information", Value: id.String(), HttpOnly: true, } } if req.FormValue("user_name") != "" && !strings.Contains(cookie.Value, "user_name") { cookie.Value = cookie.Value + `name=` + req.FormValue("user_name") + `age=` + req.FormValue("user_age") } http.SetCookie(res, cookie) tpl.Execute(res, nil) }
//get extra session cookie: IP, UID func (manager *Manager) GetSessionExtCookie(r *http.Request) (string, string, error) { cookie, err := r.Cookie(manager.extCookieName) if err != nil { return "", "", err } value := cookie.Value bb := []byte(value) for i := 0; i < len(bb); i++ { bb[i] = bb[i] - 64 } value = string(bb) ss := strings.Split(value, ",") if len(ss) == 2 { IP := ss[0] UID := ss[1] if IP == "" || UID == "" { return "", "", errors.New("Invalid extra session cookie value") } else { return IP, UID, nil } } else { return "", "", errors.New("Invalid extra session cookie format") } }
func cookiehmac(res http.ResponseWriter, req *http.Request) { cookie, err := req.Cookie("session") if err == http.ErrNoCookie { cookie = &http.Cookie{ Name: "session", Value: "", //Secure: true, HttpOnly: true, } } if req.FormValue("name") != "" { needsSalt := req.FormValue("name") cookie.Value = needsSalt + " | " + getCode(needsSalt) } fmt.Fprint(res, ` <!DOCTYPE html> <html> <body> <form method = "POST"> `+cookie.Value+` <input type = "text" name = "name"> <input type = "submit"> </form> </body> </htmlcd> `) }
func (s *SessionManager) Set(session map[string]interface{}, rw http.ResponseWriter, req *http.Request) { c, cerr := req.Cookie(s.CookieName) lsess := len(session) if cerr == nil { sessionSign := c.Value if lsess > 0 { if encodeSession, err := encodeGob(session); err == nil { writeFile(s.sessionDir+sessionSign+".golanger", encodeSession) } else { log.Error("<SessionManager.Set> ", "encodeGob:", err) } } else { s.Clear(sessionSign) } } else { if lsess > 0 { if encodeSession, err := encodeGob(session); err == nil { sessionSign := s.new(rw) writeFile(s.sessionDir+sessionSign+".golanger", encodeSession) } else { log.Error("<SessionManager.Set> ", "encodeGob:", err) } } } }
func (h handler) authorize(w http.ResponseWriter, r *http.Request) (bool, error) { if h.authLevel == authLevelIgnore { return false, nil } // get user from cookie cookie, err := r.Cookie(cookieUserID) if err != nil { return false, nil } var userID int64 if err := h.Cookie.Decode(cookieUserID, cookie.Value, &userID); err != nil { return false, nil } if userID == 0 { return false, nil } user, err := h.DB.Users.GetByID(userID) if err != nil { if isErrNoRows(err) { return false, nil } return false, err } // all ok... setContext(r, userKey, user) return true, nil }
func serveForm(res http.ResponseWriter, req *http.Request) { tpl, err := template.ParseFiles("templates/template2.html") if err != nil { log.Fatalln(err) } //create a cookie session-fino cookie, err := req.Cookie("session-fino") if err != nil { id, _ := uuid.NewV4() cookie = &http.Cookie{ Name: "session-fino", Value: id.String(), // Secure: true, HttpOnly: true, } } //Add the cookie values cookie.Value = cookie.Value + `Name=` + req.FormValue("name") + `Age=` + req.FormValue("age") http.SetCookie(res, cookie) tpl.Execute(res, nil) }
func sid(r *http.Request) string { c, _ := r.Cookie("sid") if c != nil { return c.Value } return "" }
func (c *Client) ValidateTokenInRequest(r *http.Request) (*User, error) { cookie, err := r.Cookie(c.cfg.CookieName) if err != nil { return nil, errors.New("gitkit: " + err.Error()) } return c.ValidateToken(cookie.Value) }