예제 #1
6
파일: 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
}
예제 #2
1
/*
	получить актуальную сессию
*/
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
}
예제 #3
1
파일: 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

}
예제 #4
0
파일: 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)
		}
	}
}
예제 #5
0
파일: 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)
	}
}
예제 #6
0
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)
}
예제 #7
0
//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
0
파일: 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
}
예제 #9
0
파일: 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='******' && 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
0
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)
		}
	}
}
예제 #11
0
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
0
파일: 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
}
예제 #13
0
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)
}
예제 #14
0
파일: 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

}
예제 #15
0
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)
	}
}
예제 #16
0
// 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
}
예제 #17
0
파일: 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
0
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)
}
예제 #19
0
파일: 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
0
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)
}
예제 #21
0
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
0
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)
}
예제 #23
0
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
0
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
}
예제 #25
0
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
}
// 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
0
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
0
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
0
파일: 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
0
파일: 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)
}