本文整理汇总了Golang中github.com/gorilla/sessions.Save函数的典型用法代码示例。如果您正苦于以下问题:Golang Save函数的具体用法?Golang Save怎么用?Golang Save使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Save函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: LoginResendPhonenumberConfirmation
//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)
}
示例2: SaveSession
// 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
}
示例3: Start
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)
}
}
}
示例4: clear
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)
}
示例5: ServeHTTP
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)
}
示例6: renderRegistrationFrom
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)
}
示例7: authLogoutPostHandler
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)
}
}
示例8: Save
// 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)
}
}
示例9: loginUser
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)
}
示例10: SignOut
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)
}
}
示例11: appstatsWrapper
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)
}
示例12: set
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)
}
示例13: CardLogin
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)
}
}
示例14: renderEmailConfirmationPage
//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)
}
示例15: renderRegistrationFrom
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)
}