//LoginResendPhonenumberConfirmation resend the phone number confirmation after logging in to a possibly new phone number func (service *Service) LoginResendPhonenumberConfirmation(w http.ResponseWriter, request *http.Request) { values := struct { PhoneNumber string `json:"phonenumber"` }{} response := struct { Error string `json:"error"` }{} if err := json.NewDecoder(request.Body).Decode(&values); err != nil { log.Debug("Error decoding the ResendPhonenumberConfirmation request: ", err) http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } loginSession, err := service.GetSession(request, SessionLogin, "loginsession") if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if loginSession.IsNew { sessions.Save(request, w) log.Debug("Login session expired") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } username, _ := loginSession.Values["username"].(string) //Invalidate the previous validation request, ignore a possible error validationkey, _ := loginSession.Values["phonenumbervalidationkey"].(string) _ = service.phonenumberValidationService.ExpireValidation(request, validationkey) phonenumber := user.Phonenumber{Label: "main", Phonenumber: values.PhoneNumber} if !phonenumber.IsValid() { log.Debug("Invalid phone number") w.WriteHeader(422) response.Error = "invalid_phonenumber" json.NewEncoder(w).Encode(&response) return } uMgr := user.NewManager(request) err = uMgr.SavePhone(username, phonenumber) if err != nil { log.Error("ResendPhonenumberConfirmation: Could not save phonenumber: ", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } validationkey, err = service.phonenumberValidationService.RequestValidation(request, username, phonenumber, fmt.Sprintf("https://%s/phonevalidation", request.Host)) if err != nil { log.Error("ResendPhonenumberConfirmation: Could not get validationkey: ", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } loginSession.Values["phonenumbervalidationkey"] = validationkey sessions.Save(request, w) w.WriteHeader(http.StatusNoContent) }
// SaveSession - shortcut func SaveSession(w http.ResponseWriter, r *http.Request) error { err := sessions.Save(r, w) if err != nil { logSession.Error("SaveSession error", "err", err) } return err }
func Start(w http.ResponseWriter, r *http.Request) { vars, session, err := initSession(w, r) if err != nil { return } if *startSecretKey == "" || isValidToken(vars["CardId"], *startSecretKey) { log.Debugf("Valid Start page: %v", vars["CardId"]) session.Values["cardId"] = vars["CardId"] sessions.Save(r, w) var fileName string if session.Values["admin"] == "1" { log.Debug("Sending Admin UI") fileName = root + "/admin.html" } else { log.Debug("Sending User UI") fileName = root + "/public.html" } f, err := os.Open(fileName) if err == nil { http.ServeContent(w, r, fileName, time.Time{}, f) } else { log.Error(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) } } else { log.Infof("Bad Start page: %v", vars["CardId"]) err = templates["bad-cards.html"].Execute(w, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } }
func (s *session) clear() error { s.userId = `` s.entityId = `` s.entity = nil s.internalSession.Values = map[interface{}]interface{}{} return sessions.Save(s.request, s.writer) }
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { startTime := time.Now().UTC() if h.logRq { defer logger.LogRq(req, startTime) } //create the context ctx, err := NewContext(req, h.c) if err != nil { internalError(ctx, w, req, err, "New context err") return } //defer ctx.Close() // We're using httpbuf here to satisfy an unobvious requirement: // sessions.Save() *must* be called before anything is written to // ResponseWriter. So we pass this buffer in place of writer here, then // call Save() and finally apply the buffer to the real writer. buf := new(httpbuf.Buffer) err = h.h(buf, req, ctx) if err != nil { internalError(ctx, w, req, err, "Error in handler") return } //save the session if err = sessions.Save(req, w); err != nil { internalError(ctx, w, req, err, "Session save err") return } buf.Apply(w) }
func (service *Service) renderRegistrationFrom(w http.ResponseWriter, request *http.Request, validationErrors []string, totpsecret string) { htmlData, err := html.Asset(registrationFileName) if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } //Don't use go templates since angular uses "{{ ... }}" syntax as well and this way the standalone page also works htmlData = bytes.Replace(htmlData, []byte("secret=1234123412341234"), []byte("secret="+totpsecret), 2) errorMap := make(map[string]bool) for _, errorkey := range validationErrors { errorMap[errorkey] = true } jsonErrors, err := json.Marshal(errorMap) if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } htmlData = bytes.Replace(htmlData, []byte(`{"invalidsomething": true}`), jsonErrors, 1) sessions.Save(request, w) w.Write(htmlData) }
func authLogoutPostHandler(w http.ResponseWriter, r *http.Request) { ses, _ := clientLongtermSessionStore.Get(r, "authentication") delete(ses.Values, "account") err := sessions.Save(r, w) if err != nil { glog.Errorln(err) } }
// Save emits the PastePermissionSet to disk, either as part of the anonymous // session or as part of the authenticated user's data. func (p *PastePermissionSet) Save(w http.ResponseWriter, r *http.Request) { if p.u != nil { p.u.Save() } else { cookieSession, _ := sessionStore.Get(r, "session") cookieSession.Values["permissions"] = p sessions.Save(r, w) } }
func (service *Service) loginUser(w http.ResponseWriter, request *http.Request, username string) { if err := service.SetLoggedInUser(w, request, username); err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } sessions.Save(request, w) log.Debugf("Successfull login by '%s'", username) redirectURL := "/" queryValues := request.URL.Query() endpoint := queryValues.Get("endpoint") if endpoint != "" { queryValues.Del("endpoint") redirectURL = endpoint + "?" + queryValues.Encode() } else { registrationSession, _ := service.GetSession(request, SessionForRegistration, "registrationdetails") if !registrationSession.IsNew && registrationSession.Values["redirectparams"] != nil { splitted := strings.Split(registrationSession.Values["redirectparams"].(string), "&") if len(splitted) > 3 { for _, part := range splitted { kv := strings.Split(part, "=") if len(kv) == 2 { key, _ := url.QueryUnescape(kv[0]) value, _ := url.QueryUnescape(kv[1]) queryValues.Set(key, value) } } endpoint, _ = url.QueryUnescape(queryValues.Get("endpoint")) queryValues.Del("endpoint") redirectURL = endpoint + "?" + queryValues.Encode() } } } sessions.Save(request, w) response := struct { Redirecturl string `json:"redirecturl"` }{} response.Redirecturl = redirectURL log.Debug("Redirecting to:", redirectURL) json.NewEncoder(w).Encode(response) }
func (u UserController) SignOut() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "user") session.Options.MaxAge = -1 sessions.Save(r, w) http.Redirect(w, r, "/", http.StatusTemporaryRedirect) } }
func appstatsWrapper(h Handler) http.Handler { f := func(c appengine.Context, w http.ResponseWriter, req *http.Request) { // Emit some compatibility & anti-cache headers for IE (you can overwrite // them from the handlers) w.Header().Set("X-UA-Compatible", "chrome=1") w.Header().Set("Cache-Control", "max-age=0,no-cache,no-store,"+ "post-check=0,pre-check=0") w.Header().Set("Expires", "Mon, 26 Jul 1997 05:00:00 GMT") // Build the request & session objects rw := newResponseWriter(w) r := &Request{Req: req, W: rw, C: c, N: goon.FromContext(c)} session, token, err := getSession(req, rw) if err != nil { r.processError(fmt.Errorf("build session failed: %s", err)) return } r.Session = session // Check XSRF token if req.Method != "GET" { if ok, err := checkXsrfToken(req, token); err != nil { r.processError(fmt.Errorf("check xsrf token failed: %s", err)) return } else if !ok { c.Errorf("xsrf token header check failed") r.processError(Forbidden()) return } } // Fatal errors recovery defer func() { if rec := recover(); rec != nil { err := fmt.Errorf("panic recovered error: %s", rec) r.processError(err) } }() // Handle the request if err := h(r); err != nil { r.processError(err) } // Save the session & copy the buffered output if err := sessions.Save(req, w); err != nil { r.processError(err) } if err := rw.output(); err != nil { r.processError(err) } } return appstats.NewHandler(f) }
func (s *session) set(userId string, entityId string, entity Entity) error { s.userId = userId s.entityId = entityId s.entity = entity s.internalSession.Values = map[interface{}]interface{}{ _USER_ID: userId, _ENTITY_ID: entityId, _ENTITY: entity, } return sessions.Save(s.request, s.writer) }
func CardLogin(w http.ResponseWriter, r *http.Request) { vars, session, err := initSession(w, r) if err != nil { return } if isValidToken(vars["CardId"], *adminSecretKey) { log.Debugf("Valid Card Login: %v", vars["CardId"]) session.Values["admin"] = "1" sessions.Save(r, w) err = templates["login-ok.html"].Execute(w, nil) } else { log.Infof("Bad Card Login: %v", vars["CardId"]) session.Values["admin"] = "0" sessions.Save(r, w) err = templates["login-failed.html"].Execute(w, nil) } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
//renderEmailConfirmationPage renders a small mobile friendly confirmation page after a user follows a link in an email func (service *Service) renderEmailConfirmationPage(w http.ResponseWriter, request *http.Request, text string) { htmlData, err := html.Asset(emailconfirmationPage) if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } htmlData = bytes.Replace(htmlData, []byte(`{{ text }}`), []byte(text), 1) sessions.Save(request, w) w.Write(htmlData) }
func (service *Service) renderRegistrationFrom(w http.ResponseWriter, request *http.Request) { htmlData, err := html.Asset(registrationFileName) if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } sessions.Save(request, w) w.Write(htmlData) }
//GetSmsCode returns an sms code for a specified phone label func (service *Service) GetSmsCode(w http.ResponseWriter, request *http.Request) { phoneLabel := mux.Vars(request)["phoneLabel"] loginSession, err := service.GetSession(request, SessionLogin, "loginsession") if err != nil { log.Error("Error getting login session", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } sessionInfo, err := newLoginSessionInformation() if err != nil { log.Error("Error creating login session information", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } username, ok := loginSession.Values["username"].(string) if username == "" || !ok { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } userMgr := user.NewManager(request) userFromDB, err := userMgr.GetByName(username) if err != nil { log.Error("Error getting user", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } phoneNumber, err := userFromDB.GetPhonenumberByLabel(phoneLabel) if err != nil { log.Debug(userFromDB.Phonenumbers) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } loginSession.Values["sessionkey"] = sessionInfo.SessionKey authClientId := loginSession.Values["auth_client_id"] authenticatingOrganization := "" if authClientId != nil { authenticatingOrganization = authClientId.(string) } mgoCollection := db.GetCollection(db.GetDBSession(request), mongoLoginCollectionName) mgoCollection.Insert(sessionInfo) organizationText := "" if authenticatingOrganization != "" { split := strings.Split(authenticatingOrganization, ".") organizationText = fmt.Sprintf("to authorize the organization %s, ", split[len(split)-1]) } smsmessage := fmt.Sprintf("To continue signing in at itsyou.online %senter the code %s in the form or use this link: https://%s/sc?c=%s&k=%s", organizationText, sessionInfo.SMSCode, request.Host, sessionInfo.SMSCode, url.QueryEscape(sessionInfo.SessionKey)) sessions.Save(request, w) go service.smsService.Send(phoneNumber.Phonenumber, smsmessage) w.WriteHeader(http.StatusNoContent) }
// Saves all currently open sessions for this request to disk. func (sc *SessionContext) SaveAll() { //TODO: Can I somehow defer this save until the request is finished processing? // Maybe a callback from the context-chain. // TODO TODO: Is that even a good idea though? Is there an instance where you expect the session // perhaps I'd need some kind of "ForceSave()" method in case a controller actually wnats to persist // state _now._ //tl;dr: premature optimization. if sc.isInit { sessions.Save(sc.request, sc.response) return } }
// End the current user session func (a AuthenticationController) LogOut() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // retrieve user session session, _ := store.Get(r, "user") // kill session session.Options.MaxAge = -1 sessions.Save(r, w) // redirect to home page http.Redirect(w, r, "/", http.StatusFound) } }
//renderLoginForm shows the user login page func (service *Service) renderLoginForm(w http.ResponseWriter, request *http.Request, indicateError bool, postbackURL string) { htmlData, err := html.Asset(loginFileName) if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if indicateError { htmlData = bytes.Replace(htmlData, []byte(`{"invalidsomething": true}`), []byte(`{"invalidcredentials": true}`), 1) } htmlData = bytes.Replace(htmlData, []byte(`action="login"`), []byte(fmt.Sprintf("action=\"%s\"", postbackURL)), 1) sessions.Save(request, w) w.Write(htmlData) }
func ExampleStore_Save() { // db(*bolt.DB) should be opened beforehand and passed by the other function. var db *bolt.DB // w(http.ResponseWriter) should be passed by the other function. var w http.ResponseWriter // r(*http.Request) should be passed by the other function. var r *http.Request // Create a store. str, err := New(db, Config{}, []byte("secret-key")) if err != nil { panic(err) } // Create a session. session, err := str.New(r, "session-key") if err != nil { panic(err) } // Add a value on the session. session.Values["foo"] = "bar" // Save the session. if err := sessions.Save(r, w); err != nil { panic(err) } // You can delete the session by setting the session options's MaxAge // to a minus value. session.Options.MaxAge = -1 if err := sessions.Save(r, w); err != nil { panic(err) } }
func checkUserIn(user, pass string, w http.ResponseWriter, r *http.Request) bool { if users.CheckPassword(user, pass) { session, err := GetSession(r) if err != nil { return false } session.Values["expires"] = time.Now().Add(time.Hour * 24) session.Values["user"] = user if err := sessions.Save(r, w); err != nil { return false } return true } return false }
func Logout(w http.ResponseWriter, r *http.Request) { _, session, err := initSession(w, r) if err != nil { return } log.Debug("Logout") session.Values["admin"] = "0" sessions.Save(r, w) err = templates["logout.html"].Execute(w, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
// Internal handler for running the route, that way different functions can be exposed but all handled the same. func (f *Fogo) runRoute(w http.ResponseWriter, r *http.Request, hf FogoHandler, path string) { context := f.newContext(w, r) defer handleError(f, context, path) f.runBeforeMiddleware(context) // Call registered handler status, output := hf(context) f.runAfterMiddlware(context) // Saving all session values svErr := sessions.Save(r, w) if svErr != nil { f.logger.LogError(svErr) } // Checking for redirects if context.Redirect { http.Redirect(w, r, context.RedirectPath, http.StatusSeeOther) return } // Writing out a request log f.logger.LogInterfaces("Status:", status, "Path:", path) // Generating the output instance := reflect.ValueOf(output) if instance.Type().Kind() == reflect.Ptr { instance = instance.Elem() } out_str := "" switch instance.Type().Kind() { case reflect.String: out_str = output.(string) case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: j, err := json.Marshal(output) if err != nil { f.logger.LogInterfaces("luar.Route", path, err) http.Error(w, `{ "success": false, "error_message": "unable to serialize output json." }`, http.StatusInternalServerError) return } w.Header().Add("Content-Type", "application/json") out_str = string(j) } w.WriteHeader(status) w.Write([]byte(out_str)) }
func (a *Api) authCallback(w http.ResponseWriter, r *http.Request) { code := r.FormValue("code") client, err := a.getOAuthClient(code) u := getGithubURL("/user") resp, err := client.Get(u) if err != nil { log.Errorf("error getting user info: %s", err) return } var userInfo *GithubUser if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil { log.Errorf("error parsing github user info: %s", err) return } shpdToken, err := a.manager.GenerateToken(userInfo.Login) if err != nil { log.Errorf("error generating token: %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } // write to session session, _ := a.getSession(r) session.Values["username"] = shpdToken.Username session.Values["token"] = shpdToken.Token session.Values["code"] = code sessions.Save(r, w) log.Debugf("authenticated user: username=%s", shpdToken.Username) // check allowed user if !a.isValidUser(shpdToken.Username) { log.Warnf("unauthorized login: username=%s ip=%s", shpdToken.Username, r.RemoteAddr) //http.Error(w, "forbidden", http.StatusForbidden) http.Redirect(w, r, "/#/403", http.StatusFound) return } // redirect to domains http.Redirect(w, r, "/", http.StatusFound) }
//ShowLoginForm shows the user login page on the initial request func (service *Service) ShowLoginForm(w http.ResponseWriter, request *http.Request) { htmlData, err := html.Asset(loginFileName) if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } loginSession, err := service.GetSession(request, SessionLogin, "loginsession") if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } loginSession.Values["auth_client_id"] = request.URL.Query().Get("client_id") sessions.Save(request, w) w.Write(htmlData) }
// This function will be called each time the request hits the location with this middleware activated func (a *AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { //Check session session, _ := store.Get(r, "session") if session.Values["active"] != "true" { //No session - try to log in username, password, ok := r.BasicAuth() // Reject the request by writing forbidden response if !ok || !isAuthorized(a.cfg, username, password) { w.WriteHeader(http.StatusUnauthorized) w.Header().Set("WWW-Authenticate", "Basic realm=\"Please log in\"") return } session.Values["active"] = "true" // Save all sessions. sessions.Save(r, w) } // Pass the request to the next middleware in chain a.next.ServeHTTP(w, r) }
//HomePage shows the home page when logged in, if not, delegate to showing the public website func (service *Service) HomePage(w http.ResponseWriter, request *http.Request) { loggedinuser, err := service.GetLoggedInUser(request, w) if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if loggedinuser == "" { service.ShowPublicSite(w, request) return } htmlData, err := html.Asset(homepageFileName) if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } sessions.Save(request, w) w.Write(htmlData) }
func authenticatePastePOSTHandler(w http.ResponseWriter, r *http.Request) { if throttleAuthForRequest(r) { RenderError(fmt.Errorf("Cool it."), 420, w) return } id := PasteIDFromString(mux.Vars(r)["id"]) password := r.FormValue("password") p, err := pasteStore.Get(id, nil) if p == nil { RenderError(err, http.StatusNotFound, w) return } key := p.EncryptionKeyWithPassword(password) if key != nil { cliSession, _ := clientOnlySessionStore.Get(r, "c_session") pasteKeys, ok := cliSession.Values["paste_keys"].(map[PasteID][]byte) if !ok { pasteKeys = map[PasteID][]byte{} } pasteKeys[id] = key cliSession.Values["paste_keys"] = pasteKeys sessions.Save(r, w) if err != nil { glog.Errorln(err) } } url, _ := pasteRouter.Get("show").URL("id", id.String()) dest := url.String() if destCookie, err := r.Cookie("destination"); err != nil { dest = destCookie.Value } w.Header().Set("Location", dest) w.WriteHeader(http.StatusSeeOther) }
func TwitterLoginHandler(w http.ResponseWriter, r *http.Request) { requestToken, err := models.GetRequestTokenAndURL("http://localhost:3000/twitter/callback") if err != nil { glog.Info("Failed to obtain request token") http.Error(w, "Failed to obtain request token", http.StatusInternalServerError) } session, err := models.GetSession(r, "twitter_login") if err != nil { glog.Error("failed to get session") http.Error(w, "failed to get session", http.StatusInternalServerError) } session.Values["request_token"] = requestToken if err = sessions.Save(r, w); err != nil { glog.Fatalf("Error saving session: %v", err) } glog.Infof("url: %s", requestToken.Url) }
func (service *Service) GetConfig(w http.ResponseWriter, request *http.Request) { token, err := totp.NewToken() if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } totpsession, err := service.GetSession(request, SessionForRegistration, "totp") if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } totpsession.Values["secret"] = token.Secret sessions.Save(request, w) data := struct { TotpSecret string `json:"totpsecret"` GithubClientId string `json:"githubclientid"` FacebookClientId string `json:"facebookclientid"` }{} data.TotpSecret = token.Secret data.GithubClientId, _ = identityservice.GetOauthClientID("github") data.FacebookClientId, _ = identityservice.GetOauthClientID("facebook") json.NewEncoder(w).Encode(&data) }