Golang SetCookie示例

说明

golang setcookie示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: sessions.go 项目: mil-ast/sessions

/*
	получить актуальную сессию
*/
func Get(w http.ResponseWriter, r *http.Request) *Session {
	var (
		err    error
		cookie *http.Cookie
		ses    *Session
		ok     bool
		ses_id string
	)

	cookie, err = r.Cookie(sid)
	if err != nil {
		ses_id, ses = registry.new()

		cookie = &http.Cookie{Name: sid, Value: ses_id, Path: "/", HttpOnly: true, MaxAge: int(maxlifetime.Seconds())}
		http.SetCookie(w, cookie)

		return ses
	}

	ses, ok = registry.get(cookie.Value)
	if !ok {
		ses = registry.create(cookie.Value)

		cookie.MaxAge = int(maxlifetime.Seconds())
		cookie.Path = "/"
		http.SetCookie(w, cookie)

		return ses
	}

	cookie.MaxAge = int(maxlifetime.Seconds())
	http.SetCookie(w, cookie)

	return ses
}

示例#2
文件: lang.go 项目: Iceyer/gutils

func GinLang(cookieName string, domain string) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Request.ParseForm()
		cookieLang, err := c.Request.Cookie(cookieName)
		if nil != err {
			cookieLang = &http.Cookie{
				Name:   cookieName,
				Value:  "zh-cn",
				Path:   "/",
				Domain: domain,
				MaxAge: 3600 * 24 * 365,
			}
			http.SetCookie(c.Writer, cookieLang)
		}

		lang := c.Request.Form.Get("lang")
		if "" == lang {
			lang = langCode[cookieLang.Value]
		} else {
			if lang != langCode[cookieLang.Value] {
				cookieLang.Domain = domain
				cookieLang.Value = codeLang[lang]
				http.SetCookie(c.Writer, cookieLang)
			}
		}
		os.Setenv("LANGUAGE", lang)
		gogettext.SetLocale(gogettext.LC_ALL, "")
		c.Set("lang", lang)
	}
}

示例#3
文件: app.go 项目: gtfour/actuator

func LoginPost() func(c *gin.Context) {
	return func(c *gin.Context) {
		username := c.PostForm("username")
		password := c.PostForm("password")
		redirect_to := c.DefaultQuery("redirect_to", "/index")
		if common.IsIn(redirect_to, settings.ALLOWED_REDIRECTS) == false {
			redirect_to = "/index"
		}
		w, err := webclient.Init(username, password)
		if err != nil {
			c.Redirect(302, settings.SERVER_URL+"/auth/login"+"?redirect_to="+redirect_to)
		} else {
			user := userstorage.FindWrapper(w.UserId, w.TokenId)
			if user == nil {
				userstorage.AddWrapper(w)
			}
			cookie_userid := &http.Cookie{Name: settings.USERID_COOKIE_FIELD_NAME, Value: w.UserId, Path: "/", Domain: settings.SERVER_ADDR}
			cookie_token := &http.Cookie{Name: settings.TOKEN_COOKIE_FIELD_NAME, Value: w.TokenId, Path: "/", Domain: settings.SERVER_ADDR}
			http.SetCookie(c.Writer, cookie_userid)
			http.SetCookie(c.Writer, cookie_token)

			c.Redirect(302, settings.SERVER_URL+redirect_to)
		}
	}
}

示例#4
文件: browse.go 项目: FiloSottile/caddy

// handleSortOrder gets and stores for a Listing the 'sort' and 'order',
// and reads 'limit' if given. The latter is 0 if not given.
//
// This sets Cookies.
func (b Browse) handleSortOrder(w http.ResponseWriter, r *http.Request, scope string) (sort string, order string, limit int, err error) {
	sort, order, limitQuery := r.URL.Query().Get("sort"), r.URL.Query().Get("order"), r.URL.Query().Get("limit")

	// If the query 'sort' or 'order' is empty, use defaults or any values previously saved in Cookies
	switch sort {
	case "":
		sort = "name"
		if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil {
			sort = sortCookie.Value
		}
	case "name", "size", "type":
		http.SetCookie(w, &http.Cookie{Name: "sort", Value: sort, Path: scope, Secure: r.TLS != nil})
	}

	switch order {
	case "":
		order = "asc"
		if orderCookie, orderErr := r.Cookie("order"); orderErr == nil {
			order = orderCookie.Value
		}
	case "asc", "desc":
		http.SetCookie(w, &http.Cookie{Name: "order", Value: order, Path: scope, Secure: r.TLS != nil})
	}

	if limitQuery != "" {
		limit, err = strconv.Atoi(limitQuery)
		if err != nil { // if the 'limit' query can't be interpreted as a number, return err
			return
		}
	}

	return
}

示例#5
文件: cookieSigning.go 项目: levythu/Gurgling

func removeSignedCookie(w http.ResponseWriter, cookie *http.Cookie) {
	cookie.MaxAge = -1
	var signCookie = *cookie
	signCookie.Name += sign_suffix
	http.SetCookie(w, cookie)
	http.SetCookie(w, &signCookie)
}

示例#6
文件: session.go 项目: rose312/beego

//get Session
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) {
	cookie, err := r.Cookie(manager.cookieName)
	if err != nil || cookie.Value == "" {
		sid := manager.sessionId(r)
		session, _ = manager.provider.SessionRead(sid)
		cookie = &http.Cookie{Name: manager.cookieName,
			Value:    url.QueryEscape(sid),
			Path:     "/",
			HttpOnly: true,
			Secure:   manager.secure}
		if manager.maxage >= 0 {
			cookie.MaxAge = manager.maxage
		}
		//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
		http.SetCookie(w, cookie)
		r.AddCookie(cookie)
	} else {
		//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
		cookie.HttpOnly = true
		cookie.Path = "/"
		if manager.maxage >= 0 {
			cookie.MaxAge = manager.maxage
			http.SetCookie(w, cookie)
		}
		sid, _ := url.QueryUnescape(cookie.Value)
		session, _ = manager.provider.SessionRead(sid)
	}
	return
}

示例#7
文件: session.go 项目: itsyouonline/identityserver

//SetLoggedInUser creates a session for an authenticated user and clears the login session
func (service *Service) SetLoggedInUser(w http.ResponseWriter, request *http.Request, username string) (err error) {
	authenticatedSession, err := service.GetSession(request, SessionInteractive, "authenticatedsession")
	if err != nil {
		log.Error(err)
		return
	}
	authenticatedSession.Values["username"] = username

	//TODO: rework this, is not really secure I think
	// Set user cookie after successful login
	cookie := &http.Cookie{
		Name:  "itsyou.online.user",
		Path:  "/",
		Value: username,
	}
	http.SetCookie(w, cookie)

	// Clear login session
	loginCookie := &http.Cookie{
		Name:    "loginsession",
		Path:    "/",
		Value:   "",
		Expires: time.Unix(1, 0),
	}
	http.SetCookie(w, loginCookie)

	return
}

示例#8
文件: home.go 项目: Ikanant/GolangWebApp

func (this *homeController) logout(w http.ResponseWriter, req *http.Request) {

	ck, err := req.Cookie("goSessionId")

	if err == nil {
		removedS := models.RemoveSession(ck.Value)
		if removedS {
			cookieMonster := &http.Cookie{
				Name:    "goSessionId",
				Expires: time.Now(),
				Value:   strconv.FormatInt(time.Now().Unix(), 10),
			}
			cookieMonster2 := &http.Cookie{
				Name:    "loggedName",
				Expires: time.Now(),
				Value:   strconv.FormatInt(time.Now().Unix(), 10),
			}

			http.SetCookie(w, cookieMonster)
			http.SetCookie(w, cookieMonster2)

			http.Redirect(w, req, "/home", http.StatusFound)
		}
	}
}

示例#9
文件: admin.go 项目: Qesy/web

func (p *Entry) Admin_login(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")
	if r.Method == "POST" {
		if VERI != r.FormValue("veri") {
			fmt.Fprintf(w, Exec_script("alert('验证码错误');history.back();"))
			return
		}
		userInfo := ConnDb.GetUser(" WHERE username='"+r.FormValue("username")+"' && password='"+r.FormValue("password")+"'", "*", "limit 0,1")
		if len(userInfo) >= 1 {
			timeStr := time.Now().AddDate(1, 0, 0)
			cookie := http.Cookie{Name: "adminId", Value: strconv.Itoa(userInfo[0].Id), Path: "/", Expires: timeStr}
			http.SetCookie(w, &cookie)
			cookie = http.Cookie{Name: "adminName", Value: userInfo[0].Username, Path: "/", Expires: timeStr}
			http.SetCookie(w, &cookie)
			fmt.Fprintf(w, Exec_script("alert('登录成功');window.location.href='/admin'"))

		} else {
			fmt.Fprintf(w, Exec_script("alert('登录失败');history.back();"))
			return
		}
		return
	}
	t, _ := template.ParseFiles("templates/admin/login.html")
	t.Execute(w, nil)
}

示例#10
文件: session.go 项目: pokerG/beego

//get Session
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) {
	cookie, err := r.Cookie(manager.cookieName)
	if err != nil || cookie.Value == "" {
		sid := manager.sessionId()
		session, _ = manager.provider.SessionRead(sid)
		secure := false
		if len(manager.options) > 0 {
			secure = manager.options[0].(bool)
		}
		cookie := http.Cookie{Name: manager.cookieName,
			Value:    url.QueryEscape(sid),
			Path:     "/",
			HttpOnly: true,
			Secure:   secure}
		//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
		http.SetCookie(w, &cookie)
		r.AddCookie(&cookie)
	} else {
		//cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second)
		cookie.HttpOnly = true
		cookie.Path = "/"
		http.SetCookie(w, cookie)
		sid, _ := url.QueryUnescape(cookie.Value)
		session, _ = manager.provider.SessionRead(sid)
	}
	return
}

示例#11
文件: cookie.go 项目: GoesToEleven/golang-web

func genCookie(res http.ResponseWriter, req *http.Request) *http.Cookie {

	cookie, err := req.Cookie("session-id")
	if err != nil {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	// make sure set cookie uses our current structure
	if strings.Count(cookie.Value, "|") != 2 {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	if tampered(cookie.Value) {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	ctx := appengine.NewContext(req)
	id := strings.Split(cookie.Value, "|")[0]
	item, _ := memcache.Get(ctx, id)
	if item == nil {
		cookie = newVisitor(req)
		http.SetCookie(res, cookie)
		return cookie
	}

	return cookie
}

示例#12
文件: context.go 项目: 2young2simple/platform

func (c *Context) RemoveSessionCookie(w http.ResponseWriter, r *http.Request) {

	sessionCache.Remove(c.Session.Token)

	cookie := &http.Cookie{
		Name:     model.SESSION_TOKEN,
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
	}

	http.SetCookie(w, cookie)

	multiToken := ""
	if oldMultiCookie, err := r.Cookie(model.MULTI_SESSION_TOKEN); err == nil {
		multiToken = oldMultiCookie.Value
	}

	multiCookie := &http.Cookie{
		Name:     model.MULTI_SESSION_TOKEN,
		Value:    strings.TrimSpace(strings.Replace(multiToken, c.Session.Token, "", -1)),
		Path:     "/",
		MaxAge:   model.SESSION_TIME_WEB_IN_SECS,
		HttpOnly: true,
	}

	http.SetCookie(w, multiCookie)
}

示例#13
文件: main.go 项目: yash0690/Golang

func genCookie(res http.ResponseWriter, req *http.Request) *http.Cookie {

	cookie, err := req.Cookie("session-ferret")
	if err != nil {
		cookie = newVisitor()
		http.SetCookie(res, cookie)
		//return cause if we made the cookie... welll theres no need to
		//check if it was tampered...
		return cookie
	}

	return cookie

	if strings.Count(cookie.Value, "|") != 2 {
		cookie = newVisitor()
		http.SetCookie(res, cookie)
	}

	if tampered(cookie.Value) {
		cookie = newVisitor()
		http.SetCookie(res, cookie)
	}
	return cookie

}

示例#14
文件: main.go 项目: Reddygaricsufresno/mygolang

func snackWells(res http.ResponseWriter, req *http.Request) {
	tpl, err := template.ParseFiles("hmac.html")
	if err != nil {
		log.Fatalln("Something went wrong: ", err)
	}
	x := user{
		Name: req.FormValue("Name"),
		Age:  req.FormValue("Age"),
	}
	b, err := json.Marshal(x)
	if err != nil {
		fmt.Println("Error: ", err)
	}
	y := base64.StdEncoding.EncodeToString(b)
	cookie, err := req.Cookie("session-fino")
	if err != nil {
		id, _ := uuid.NewV4()
		cookie = &http.Cookie{
			Name:     "session-fino",
			Value:    id.String() + "|" + getCode(id.String()),
			HttpOnly: true,
		}
		http.SetCookie(res, cookie)
	}
	cookie.Value = cookie.Value + "|" + y + "|" + getCode(y)
	http.SetCookie(res, cookie)
	err = tpl.Execute(res, nil)
	if err != nil {
		log.Fatalln(err)
	}
}

示例#15
文件: pgstore.go 项目: starkandwayne/shield

// Save saves the given session into the database and deletes cookies if needed
func (db *PGStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
	// Set delete if max-age is < 0
	if session.Options.MaxAge < 0 {
		if err := db.destroy(session); err != nil {
			return err
		}
		http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
		return nil
	}

	if session.ID == "" {
		// Generate a random session ID key suitable for storage in the DB
		session.ID = strings.TrimRight(
			base32.StdEncoding.EncodeToString(
				securecookie.GenerateRandomKey(32)), "=")
	}

	if err := db.save(session); err != nil {
		return err
	}

	// Keep the session ID key in a cookie so it can be looked up in DB later.
	encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, db.Codecs...)
	if err != nil {
		return err
	}

	http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))
	return nil
}

示例#16
文件: authenticate.go 项目: janiukjf/GoAdmin

func Logout(w http.ResponseWriter, r *http.Request) {
	// expire cookie
	cook, err := r.Cookie("userID")

	if err == nil {
		cook.Expires = time.Now().AddDate(0, 0, -1)
		http.SetCookie(w, cook)
	}

	cook2, err := r.Cookie("username")
	if err == nil {
		cook2.Expires = time.Now().AddDate(0, 0, -1)
		http.SetCookie(w, cook2)
	}

	cook3, err := r.Cookie("superUser")
	if err == nil {
		cook3.Expires = time.Now().AddDate(0, 0, -1)
		http.SetCookie(w, cook3)
	}

	cook4, err := r.Cookie("name")
	if err == nil {
		cook4.Expires = time.Now().AddDate(0, 0, -1)
		http.SetCookie(w, cook4)
	}

	http.Redirect(w, r, "/authenticate", http.StatusFound)
}

示例#17
文件: security.go 项目: ItsOnMe/selfie

//Setup setups and configure security package.
func Setup(conf *config.Config) {
	setupTokenAuth(conf.JWT.SecretKey)

	SetJwtCookie = func(token string, w http.ResponseWriter) {
		cookie := http.Cookie{
			Name:     "jwt",
			Domain:   conf.JWT.Domain,
			Path:     conf.JWT.Path,
			Secure:   conf.JWT.Secure,
			MaxAge:   conf.JWT.MaxAge,
			HttpOnly: true,
			Value:    token,
		}
		http.SetCookie(w, &cookie)
	}

	RemoveJwtCookie = func(w http.ResponseWriter) {
		cookie := http.Cookie{
			Name:     "jwt",
			Domain:   conf.JWT.Domain,
			Path:     conf.JWT.Path,
			Secure:   conf.JWT.Secure,
			MaxAge:   -1,
			HttpOnly: true,
			Value:    "",
		}
		http.SetCookie(w, &cookie)
	}
}

示例#18
文件: main.go 项目: GoesToEleven/golang-web

func index(res http.ResponseWriter, req *http.Request) {

	cookie, err := req.Cookie("session-id")
	if err != nil {
		cookie = newVisitor()
		http.SetCookie(res, cookie)
		fmt.Println("no cookie newvisitor ran") // DEBUGGING
	}

	if tampered(cookie.Value) {
		fmt.Println("INSIDE IF TAMPERED COOKIE") // DEBUGGING
		cookie = newVisitor()
		http.SetCookie(res, cookie)
		fmt.Println("tampered cookie newvisitor ran") // DEBUGGING
	}

	if req.Method == "POST" {
		src, hdr, err := req.FormFile("data")
		if err != nil {
			log.Println("error uploading photo: ", err)
			// TODO: create error page to show user
		}
		cookie = uploadPhoto(src, hdr, cookie)
		http.SetCookie(res, cookie)
		fmt.Println("upload photo ran") // DEBUGGING
	}

	m := Model(cookie)
	tpl.ExecuteTemplate(res, "index.html", m)
}

示例#19
文件: auth.go 项目: lessos/lesscreator

func (c Auth) CbAction() {

	session, err := idclient.Instance(c.Params.Get("access_token"))
	if err != nil {
		c.Redirect(idclient.AuthServiceUrl(
			config.Config.InstanceID,
			fmt.Sprintf("//%s%s/auth/cb", c.Request.Host, config.HttpSrvBasePath("")), c.Params.Get("state")))
		return
	}

	http.SetCookie(c.Response.Out, &http.Cookie{
		Name:     "access_userid",
		Value:    session.UserID,
		Path:     "/",
		HttpOnly: false,
		Expires:  time.Now().Add(time.Second * time.Duration(c.Params.Int64("expires_in"))),
	})

	http.SetCookie(c.Response.Out, &http.Cookie{
		Name:     idclient.AccessTokenKey,
		Value:    c.Params.Get("access_token"),
		Path:     "/",
		HttpOnly: true,
		Expires:  time.Now().Add(time.Second * time.Duration(c.Params.Int64("expires_in"))),
	})

	if c.Params.Get("state") != "" {
		c.Redirect(c.Params.Get("state"))
	} else {
		c.Redirect(config.HttpSrvBasePath(""))
	}
}

示例#20
文件: hackyslack.go 项目: arkie/hackyslack2

func Oauth(w http.ResponseWriter, r *http.Request) {
	code := r.URL.Query()["code"]
	if len(code) == 0 {
		http.Redirect(w, r, "/", 303)
		return
	}
	c := appengine.NewContext(r)
	tok, err := conf.Exchange(c, code[0])
	if err != nil || !tok.Valid() {
		log.Errorf(c, "Failed to exchange token %v: %v", tok, err)
		http.SetCookie(w, &http.Cookie{
			Name:  Cookie,
			Value: Error,
		})
		http.Redirect(w, r, "/", 303)
		return
	}
	team := TeamToken{
		AccessToken:  tok.AccessToken,
		TokenType:    tok.TokenType,
		RefreshToken: tok.RefreshToken,
		Expiry:       tok.Expiry,
		TeamId:       tok.Extra("team_id").(string),
		TeamName:     tok.Extra("team_name").(string),
		Scope:        tok.Extra("scope").(string),
		Created:      time.Now(),
	}
	key := datastore.NewKey(c, "token", team.TeamId, 0, nil)
	datastore.Put(c, key, &team)
	http.SetCookie(w, &http.Cookie{
		Name:  Cookie,
		Value: Okay,
	})
	http.Redirect(w, r, "/", 303)
}

示例#21
文件: cookiesession.go 项目: newthinker/framework

func (s *SessionManager) Set(session map[string]interface{}, rw http.ResponseWriter, req *http.Request) {
	origCookie, err := req.Cookie(s.CookieName)
	var origCookieVal string
	if err != nil {
		origCookieVal = ""
	} else {
		origCookieVal = origCookie.Value
	}

	if len(session) == 0 {
		if origCookieVal != "" {
			cookie := &http.Cookie{
				Name:    s.CookieName,
				Value:   "",
				Path:    "/",
				Expires: time.Now().Add(-3600),
			}

			http.SetCookie(rw, cookie)
		}
	} else {
		if encoded, err := encodeCookie(session, s.key, s.iv); err == nil {
			if encoded != origCookieVal {
				cookie := &http.Cookie{
					Name:  s.CookieName,
					Value: encoded,
					Path:  "/",
				}

				http.SetCookie(rw, cookie)
			}
		}
	}
}

示例#22
文件: user.go 项目: shudiwsh2009/reservation_thxx_go

func Logout(w http.ResponseWriter, r *http.Request, userId string, userType models.UserType) interface{} {
	var result = map[string]interface{}{"state": "SUCCESS"}

	if userType == models.ADMIN {
		result["url"] = "/appointment/admin"
	} else {
		result["url"] = "/appointment/entry"
	}
	http.SetCookie(w, &http.Cookie{
		Name:   "user_id",
		Path:   "/",
		MaxAge: -1,
	})
	http.SetCookie(w, &http.Cookie{
		Name:   "username",
		Path:   "/",
		MaxAge: -1,
	})
	http.SetCookie(w, &http.Cookie{
		Name:   "user_type",
		Path:   "/",
		MaxAge: -1,
	})

	return result
}

示例#23
文件: cookieSigning.go 项目: levythu/Gurgling

func setSignedCookie(w http.ResponseWriter, cookie *http.Cookie, secret string) {
	var signCookie = *cookie
	signCookie.Name += sign_suffix
	signCookie.Value = _hash(secret + mid_salt + signCookie.Value)
	http.SetCookie(w, cookie)
	http.SetCookie(w, &signCookie)
}

示例#24
文件: main.go 项目: bpadilla11/IntroWebDevS15

func projectWebpage(res http.ResponseWriter, req *http.Request) {
	// load cookie if it exists
	cookie, err := req.Cookie("session-fino")
	if err != nil { // if no cookie exists, then create one
		id, _ := uuid.NewV4()  // generate new id
		cookie = &http.Cookie{ // create new session
			Name:  "session-fino", // set session name
			Value: id.String(),    // set session id
			//Secure: true, // for HTTPS use, we're not using this
			HttpOnly: true, // standard HTTP website
		}
		http.SetCookie(res, cookie)    // set the generated cookie
		fmt.Println("Created cookie!") // debug message for created cookie
	}

	if req.Method == "POST" { // if a cookie exists and user submits data, then update cookie
		newValue := req.FormValue("userName") + " " + req.FormValue("userAge") // get user name and age from the index.html file
		tempValue := strings.Split(cookie.Value, " | ")                        // split the session id and newValue
		cookie.Value = tempValue[0] + " | " + newValue                         // keep current session id from tempValue, but update user name and age
		tempValue = nil                                                        // not necessary, but thought the tempValue array should be cleared of the id
		http.SetCookie(res, cookie)                                            // set the updated cookie
		fmt.Println("Updated cookie!")                                         // debug message for updated cookie
	}

	// establish the webpage by parsing the index file
	tpl, err := template.ParseFiles("index.html")
	if err != nil { // if index.html does not exist, give user a error
		log.Fatalln(err) // stops program if file does not exist
	}

	tpl.Execute(res, nil) // execute the html file
}

示例#25
文件: cookies.go 项目: extrame/goweb

// 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

}

示例#26
文件: httpsessionstore.go 项目: stackdocker/http-session-redis-sentinel-backend

// Save adds a single session to the response.
func (s *SentinelFailoverStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
	if session.Options.MaxAge < 0 {
		if err := s.delete(session); err != nil {
			return err
		}
		http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
		return nil
	}
	if session.ID == "" {
		// Because the ID is not initialized when newly created, encode it to
		// use alphanumeric characters only.
		session.ID = strings.TrimRight(
			base32.StdEncoding.EncodeToString(
				securecookie.GenerateRandomKey(32)), "=")
	}
	if err := s.save(session); err != nil {
		return err
	}

	encoded, err := securecookie.EncodeMulti(session.Name(), session.ID,
		s.Codecs...)
	if err != nil {
		return err
	}
	http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))
	return nil
}

示例#27
文件: session.go 项目: yamnikov-oleg/gin-sample

func FromContext(c *gin.Context) *Session {
	if val, ok := c.Get("session"); ok {
		if s, ok := val.(*Session); ok {
			return s
		}
	}

	cookie, err := c.Request.Cookie(CookieKey)
	if err != nil {
		s := Create()
		s.storeInContext(c)
		http.SetCookie(c.Writer, s.cookie())
		return s
	}

	s, err := Load(cookie.Value)
	if err != nil {
		s := Create()
		s.storeInContext(c)
		http.SetCookie(c.Writer, s.cookie())
		return s
	}

	s.storeInContext(c)
	return s
}

示例#28
文件: cookie.go 项目: jarias/stormpath-sdk-go

func clearAuthentication(w http.ResponseWriter, r *http.Request, application *stormpath.Application) {
	accessTokenCookie, err := r.Cookie(Config.AccessTokenCookieName)
	if err == nil {
		accessToken := &stormpath.OAuthToken{}
		accessToken.Href = stormpath.GetClient().ClientConfiguration.BaseURL + "accessTokens/" + getJwtID(accessTokenCookie.Value)
		accessToken.Delete()
	}

	refreshTokenCookie, err := r.Cookie(Config.RefreshTokenCookieName)
	if err == nil {
		refreshToken := &stormpath.OAuthToken{}
		refreshToken.Href = stormpath.GetClient().ClientConfiguration.BaseURL + "refreshTokens/" + getJwtID(refreshTokenCookie.Value)
		refreshToken.Delete()
	}

	http.SetCookie(w, &http.Cookie{Name: Config.AccessTokenCookieName, Expires: time.Now().Add(-1 * time.Second)})
	http.SetCookie(w, &http.Cookie{Name: Config.RefreshTokenCookieName, Expires: time.Now().Add(-1 * time.Second)})

	//Check Authorization header and revoke that token too
	authorizationHeader := r.Header.Get("Authorization")
	if authorizationHeader != "" && strings.Contains(authorizationHeader, "Bearer") {
		token := authorizationHeader[strings.Index(authorizationHeader, "Bearer ")+7:]
		accessToken := &stormpath.OAuthToken{}
		accessToken.Href = stormpath.GetClient().ClientConfiguration.BaseURL + "accessTokens/" + getJwtID(token)
		accessToken.Delete()

		refreshToken := &stormpath.OAuthToken{}
		refreshToken.Href = stormpath.GetClient().ClientConfiguration.BaseURL + "refreshTokens/" + getJwtClaim("rti", token)
		refreshToken.Delete()
	}
}

示例#29
文件: session.go 项目: dmcgowan/mcgoweb

func SessionMiddleware(handler RequestHandler, context *RequestContext) {
	cookie, err := context.Request.Cookie("SID")
	if err == nil && len(cookie.Value) > 0 {
		session := GetSession(cookie.Value, context.sessionCache)
		if session == nil {
			cookie.Value = ""
			cookie.Expires = time.Unix(0, 0)
			http.SetCookie(context.Writer, cookie)
		} else if time.Now().After(session.expiration) {
			session.Expire()
			cookie.Value = ""
			cookie.Expires = time.Unix(0, 0)
			http.SetCookie(context.Writer, cookie)
		} else {
			context.Session = session
			if time.Now().After(session.expiration.Add(SessionUpdateWindow)) {
				session.expiration = time.Now().Add(SessionDuration)
				cookie.Expires = session.expiration
				session.Store()
				http.SetCookie(context.Writer, cookie)
			}
		}
	}
	handler(context)
}

示例#30
文件: auth.go 项目: raygenbogen/wiki

func Logout(w http.ResponseWriter, r *http.Request) {
	expiration := time.Now()
	invalidcookie := http.Cookie{Name: "User", Value: "expired", Path: "/", Expires: expiration}
	cookie, err := r.Cookie("User")
	if err != nil {
		http.Redirect(w, r, "/auth/", http.StatusFound)
		return
	}
	username := cookie.Value
	filename := "./users/" + username
	file, erro := os.Open(filename)
	if erro != nil {
		println("Error opening the file")
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	var user User
	err = decoder.Decode(&user)
	if err != nil {
		println("Error decoding json")
	}
	h := md5.New()
	hashedStoredPassword := hex.EncodeToString(h.Sum([]byte(user.Password)))
	_, err = r.Cookie(hashedStoredPassword)
	if err != nil {
		println("no cookie found")
		http.Redirect(w, r, "/auth/", http.StatusFound)
		return
	}
	invalidcookie2 := http.Cookie{Name: hashedStoredPassword, Value: "expired", Path: "/", Expires: expiration}
	http.SetCookie(w, &invalidcookie)
	http.SetCookie(w, &invalidcookie2)
	http.Redirect(w, r, "/view/start", http.StatusFound)
}

展开阅读全文