• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang sessions.Save函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/gorilla/sessions.Save函数的典型用法代码示例。如果您正苦于以下问题:Golang Save函数的具体用法?Golang Save怎么用?Golang Save使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Save函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:itsyouonline,项目名称:identityserver,代码行数:60,代码来源:login.go


示例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
}
开发者ID:KarolBedkowski,项目名称:secproxy,代码行数:8,代码来源:session.go


示例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)
		}
	}
}
开发者ID:BlueMasters,项目名称:thymio-captain,代码行数:35,代码来源:main.go


示例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)
}
开发者ID:robsix,项目名称:rps,代码行数:7,代码来源:oak.go


示例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)
}
开发者ID:rtfb,项目名称:rtfblog,代码行数:29,代码来源:controllers.go


示例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)
}
开发者ID:mohabusama,项目名称:identityserver,代码行数:26,代码来源:registration.go


示例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)
	}
}
开发者ID:nguyentuananh1993,项目名称:ghostbin,代码行数:8,代码来源:auth.go


示例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)
	}
}
开发者ID:Saectar,项目名称:ghostbin,代码行数:11,代码来源:permissions.go


示例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)
}
开发者ID:itsyouonline,项目名称:identityserver,代码行数:43,代码来源:login.go


示例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)
	}
}
开发者ID:jonahgeorge,项目名称:jobgenius,代码行数:10,代码来源:users.go


示例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)
}
开发者ID:ernestoalejo,项目名称:gaelib,代码行数:55,代码来源:router.go


示例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)
}
开发者ID:robsix,项目名称:rps,代码行数:11,代码来源:oak.go


示例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)
	}
}
开发者ID:BlueMasters,项目名称:thymio-captain,代码行数:20,代码来源:main.go


示例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)
}
开发者ID:itsyouonline,项目名称:identityserver,代码行数:12,代码来源:service.go


示例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)
}
开发者ID:itsyouonline,项目名称:identityserver,代码行数:11,代码来源:registration.go


示例16: GetSmsCode

//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)
}
开发者ID:itsyouonline,项目名称:identityserver,代码行数:52,代码来源:login.go


示例17: SaveAll

// 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
	}
}
开发者ID:frazy,项目名称:babou,代码行数:15,代码来源:session.go


示例18: LogOut

// 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)
	}
}
开发者ID:jonahgeorge,项目名称:featherlabel.com,代码行数:15,代码来源:auth.go


示例19: renderLoginForm

//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)
}
开发者ID:mohabusama,项目名称:identityserver,代码行数:15,代码来源:login.go


示例20: ExampleStore_Save

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)
	}
}
开发者ID:MJDSys,项目名称:boltstore,代码行数:37,代码来源:store_test.go



注:本文中的github.com/gorilla/sessions.Save函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang sessions.CookieStore类代码示例发布时间:2022-05-23
下一篇:
Golang sessions.NewSession函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap