示例#1
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

}
示例#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
func (p *Login) addUuidCookie(c *gin.Context, uuid string) {
	cookie := new(http.Cookie)
	cookie.Name = "uuid"
	cookie.Value = uuid
	cookie.Path = "/"
	http.SetCookie(c.Writer, cookie)
}
示例#4
0
文件: ctx.go 项目: elago/ela
// set cookie
// args: name, value, max age, path, domain, secure, http only, expires
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
	cookie := http.Cookie{}
	cookie.Name = name
	cookie.Value = url.QueryEscape(value)

	if len(others) > 0 {
		switch v := others[0].(type) {
		case int:
			cookie.MaxAge = v
		case int64:
			cookie.MaxAge = int(v)
		case int32:
			cookie.MaxAge = int(v)
		}
	}

	cookie.Path = "/"
	if len(others) > 1 {
		if v, ok := others[1].(string); ok && len(v) > 0 {
			cookie.Path = v
		}
	}

	if len(others) > 2 {
		if v, ok := others[2].(string); ok && len(v) > 0 {
			cookie.Domain = v
		}
	}

	if len(others) > 3 {
		switch v := others[3].(type) {
		case bool:
			cookie.Secure = v
		default:
			if others[3] != nil {
				cookie.Secure = true
			}
		}
	}

	if len(others) > 4 {
		if v, ok := others[4].(bool); ok && v {
			cookie.HttpOnly = true
		}
	}

	if len(others) > 5 {
		if v, ok := others[5].(time.Time); ok {
			cookie.Expires = v
			cookie.RawExpires = v.Format(time.UnixDate)
		}
	}

	ctx.w.Header().Add("Set-Cookie", cookie.String())
}
示例#5
0
文件: context.go 项目: numo16/gogs
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
	cookie := http.Cookie{}
	cookie.Name = name
	cookie.Value = value

	if len(others) > 0 {
		switch v := others[0].(type) {
		case int:
			cookie.MaxAge = v
		case int64:
			cookie.MaxAge = int(v)
		case int32:
			cookie.MaxAge = int(v)
		}
	}

	// default "/"
	if len(others) > 1 {
		if v, ok := others[1].(string); ok && len(v) > 0 {
			cookie.Path = v
		}
	} else {
		cookie.Path = "/"
	}

	// default empty
	if len(others) > 2 {
		if v, ok := others[2].(string); ok && len(v) > 0 {
			cookie.Domain = v
		}
	}

	// default empty
	if len(others) > 3 {
		switch v := others[3].(type) {
		case bool:
			cookie.Secure = v
		default:
			if others[3] != nil {
				cookie.Secure = true
			}
		}
	}

	// default false. for session cookie default true
	if len(others) > 4 {
		if v, ok := others[4].(bool); ok && v {
			cookie.HttpOnly = true
		}
	}

	ctx.Res.Header().Add("Set-Cookie", cookie.String())
}
示例#6
0
func (s sessionResponseWriter) WriteHeader(code int) {
	if atomic.AddInt32(&s.wroteHeader, 1) == 1 {
		origCookie, err := s.req.Cookie(s.h.CookieName)
		var origCookieVal string
		if err != nil {
			origCookieVal = ""
		} else {
			origCookieVal = origCookie.Value
		}

		session := s.h.RS.Get(s.req)
		if len(session) == 0 {
			// if we have an empty session, but the
			// request didn't start out that way, we
			// assume the user wants us to clear the
			// session
			if origCookieVal != "" {
				//log.Println("clearing cookie")
				var cookie http.Cookie
				cookie.Name = s.h.CookieName
				cookie.Value = ""
				cookie.Path = "/"
				// a cookie is expired by setting it
				// with an expiration time in the past
				cookie.Expires = time.Unix(0, 0).UTC()
				http.SetCookie(s, &cookie)
			}
			goto write
		}
		encoded, gobHash, err := encodeCookie(session, s.h.encKey, s.h.hmacKey)
		if err != nil {
			log.Printf("createCookie: %s\n", err)
			goto write
		}

		if bytes.Equal(gobHash, s.h.RS.getHash(s.req)) {
			//log.Println("not re-setting identical cookie")
			goto write
		}

		var cookie http.Cookie
		cookie.Name = s.h.CookieName
		cookie.Value = encoded
		cookie.Path = s.h.CookiePath
		cookie.HttpOnly = s.h.RS.HttpOnly
		cookie.Secure = s.h.RS.Secure
		http.SetCookie(s, &cookie)
	}
write:
	s.ResponseWriter.WriteHeader(code)
}
示例#7
0
func (res *Response) SetCookie(name string, value string, others ...interface{}) {
	cookie := http.Cookie{}
	cookie.Name = name
	cookie.Value = url.QueryEscape(value)

	if len(others) > 0 {
		switch v := others[0].(type) {
		case int:
			cookie.MaxAge = v
		case int64:
			cookie.MaxAge = int(v)
		case int32:
			cookie.MaxAge = int(v)
		}
	}

	cookie.Path = "/"
	if len(others) > 1 {
		if v, ok := others[1].(string); ok && len(v) > 0 {
			cookie.Path = v
		}
	}

	if len(others) > 2 {
		if v, ok := others[2].(string); ok && len(v) > 0 {
			cookie.Domain = v
		}
	}

	if len(others) > 3 {
		switch v := others[3].(type) {
		case bool:
			cookie.Secure = v
		default:
			if others[3] != nil {
				cookie.Secure = true
			}
		}
	}

	if len(others) > 4 {
		if v, ok := others[4].(bool); ok && v {
			cookie.HttpOnly = true
		}
	}

	res.Header().Add("Set-Cookie", cookie.String())
}
示例#8
0
// Redirects the User to the OAuth1.0a provider's Login Screen. A RequestToken
// is requested from the Provider, and included in the URL's oauth_token param.
//
// A Successful Login / Authorization should return both the oauth_token and
// the oauth_verifier to the callback URL.
func (self *OAuth1Mixin) AuthorizeRedirect(w http.ResponseWriter, r *http.Request, endpoint string) error {

	//Get a Request Token
	token, err := self.Consumer.RequestToken()
	if err != nil {
		return err
	}

	//Get the redirect URL
	url, err := self.Consumer.AuthorizeRedirect(token)
	if err != nil {
		return err
	}

	//Write the Request Token to a Cookie, so that we can
	//retrieve it after re-directing the user to the
	//providers authorization screen.
	cookie := http.Cookie{}
	cookie.Name = "_token"
	cookie.Path = "/"
	cookie.Domain = r.URL.Host
	cookie.HttpOnly = true
	cookie.Secure = Config.CookieSecure
	cookie.Value = token.Encode()
	http.SetCookie(w, &cookie)

	// redirect to the login url
	http.Redirect(w, r, url, http.StatusSeeOther)
	return nil
}
示例#9
0
func HandleGuard(c *webapp.Context) {
	var err error
	action := c.Request.FormValue("action")
	if action == "logout" {
		RevokeSessionTokon()
		c.Redirect("/guard", http.StatusFound)
		return
	}
	if c.Request.Method == "POST" {
		cert := c.Request.FormValue("certificate")
		if len(cert) == 0 {
			c.Redirect("/guard", http.StatusFound)
			return
		}
		if SHA256Sum(cert) == GetConfig().Certificate {
			cookie := new(http.Cookie)
			cookie.Name = "token"
			cookie.Path = "/"
			cookie.Value = GenerateSessionToken()
			http.SetCookie(c.Writer, cookie)
			c.Redirect("/writer", http.StatusFound)
		} else {
			err = RenderGuard(c, "Your password is not correct")
			if err != nil {
				c.Error(fmt.Sprintf("%s: %s", webapp.ErrInternalServerError, err), http.StatusInternalServerError)
			}
		}
	} else if c.Request.Method == "GET" {
		err = RenderGuard(c, "")
		if err != nil {
			c.Error(fmt.Sprintf("%s: %s", webapp.ErrInternalServerError, err), http.StatusInternalServerError)
		}
	}
}
示例#10
0
// Answers to /sso, returns the SSO cookie and redirects to /startpage
func handler(w http.ResponseWriter, r *http.Request) {
	re := regexp.MustCompile("CN=([ 0-9A-Za-z_]+)")

	user := r.Header.Get("Certificate-User")
	if user == "" {
		log.Panicf("Did not get user!")
	}

	match := re.FindStringSubmatch(user)

	if len(match) != 2 {
		log.Panicf("No CN found!")
	}

	cn := match[1]

	sessionid := getSessionID(cn, r.Header.Get("X-Forwarded-For"))
	token := generate_session_token(sessionid, cn)
	signature := sign_session_token(token)

	cookie := http.Cookie{}
	cookie.Name = "PLAY_SESSION"
	cookie.Value = signature + "-" + token
	cookie.Path = "/"
	cookie.Domain = external_host
	cookie.Expires = time.Now().Add(356 * 24 * time.Hour)
	cookie.HttpOnly = true
	http.SetCookie(w, &cookie)

	http.Redirect(w, r, "/startpage", http.StatusFound)
}
示例#11
0
func SetCookieVal(w http.ResponseWriter, name string, value string, path string) {
	var C http.Cookie
	C.Name = name
	C.Value = value
	C.Path = path
	C.Expires = time.Now().AddDate(0, 1, 0)
	http.SetCookie(w, &C)
}
示例#12
0
func constructCookie(name string, value string) *http.Cookie {
	cookie := new(http.Cookie)
	cookie.Name = name
	cookie.Value = value
	cookie.Path = "/"
	cookie.HttpOnly = false
	cookie.Secure = false
	return cookie
}
示例#13
0
文件: monim.go 项目: LDCS/monim
func createCookie(key, val string) *http.Cookie {
	cookie := new(http.Cookie)
	cookie.Name = key
	cookie.Value = val
	cookie.HttpOnly = false
	cookie.Path = "/" // Without this ang js cant read cookies we send
	//cookie.Expires = expire
	return cookie
}
示例#14
0
func (auth *FormsAuthenticator) createAuthCookie(jwtString string) *http.Cookie {
	cookie := http.Cookie{}
	cookie.Name = auth.CookieName
	cookie.Expires = auth.getCookieExpirationTime()
	cookie.HttpOnly = true
	cookie.Path = "/"
	cookie.Value = jwtString
	return &cookie
}
示例#15
0
func (s *FormsAuthSuite) createCookie(token string) http.Cookie {
	cookie := http.Cookie{}
	cookie.Name = FormsAuthenticatorDefaultCookieName
	cookie.Expires = time.Now().UTC().Add(24 * 365 * time.Hour)
	cookie.HttpOnly = true
	cookie.Path = "/"
	cookie.Value = token
	return cookie
}
示例#16
0
文件: main.go 项目: Joinhack/gae_blog
func newCookie(r *http.Request, session *Session) *http.Cookie {
	cookie := new(http.Cookie)
	cookie.Name = "UH"
	cookie.Value = session.Id
	cookie.Expires = session.Expires
	cookie.Path = "/"
	cookie.Domain = r.URL.Host
	return cookie
}
示例#17
0
// parse parses a Set-Cookie header into a cookie.
// It supports space in name unlike net/http.
// Returns nil if invalid.
func parse(s string) *http.Cookie {
	var c http.Cookie
	for i, field := range strings.Split(s, ";") {
		if len(field) == 0 {
			continue
		}
		nv := strings.SplitN(field, "=", 2)
		name := strings.TrimSpace(nv[0])
		value := ""
		if len(nv) > 1 {
			value = strings.TrimSpace(nv[1])
		}
		if i == 0 {
			if len(nv) != 2 {
				continue
			}
			c.Name = name
			c.Value = value
			continue
		}
		switch strings.ToLower(name) {
		case "secure":
			c.Secure = true
		case "httponly":
			c.HttpOnly = true
		case "domain":
			c.Domain = value
		case "max-age":
			secs, err := strconv.Atoi(value)
			if err != nil || secs != 0 && value[0] == '0' {
				continue
			}
			if secs <= 0 {
				c.MaxAge = -1
			} else {
				c.MaxAge = secs
			}
		case "expires":
			exptime, err := time.Parse(time.RFC1123, value)
			if err != nil {
				exptime, err = time.Parse("Mon, 02-Jan-2006 15:04:05 MST", value)
				if err != nil {
					c.Expires = time.Time{}
					continue
				}
			}
			c.Expires = exptime.UTC()
		case "path":
			c.Path = value
		}
	}
	if c.Name == "" {
		return nil
	}
	return &c
}
示例#18
0
文件: cookie.go 项目: juztin/wombat
func cookie(val string) *http.Cookie {
	c := new(http.Cookie)
	c.Name = config.Cookie
	c.Value = val
	c.Domain = config.ServerDomain
	c.Path = config.CookiePath
	c.HttpOnly = config.CookieHttpOnly
	c.Secure = config.CookieSecure
	return c
}
示例#19
0
文件: monim.go 项目: LDCS/monim
func createBlankCookie(key string) *http.Cookie {
	cookie := new(http.Cookie)
	cookie.Name = key
	cookie.Value = ""
	l, _ := time.LoadLocation("UTC")
	cookie.Expires = time.Date(1970, time.January, 1, 0, 0, 0, 0, l)
	cookie.HttpOnly = false
	cookie.Path = "/" // Without this ang js cant read cookies we send
	return cookie
}
示例#20
0
func SetCookie(w http.ResponseWriter, k, v string, exp int32) {
	var ck http.Cookie
	ck.Name = k
	ck.Path = "/"
	ck.Value = v
	if exp != 0 {
		ck.Expires = time.Now().Add(time.Second * time.Duration(exp))
	}
	http.SetCookie(w, &ck)
}
示例#21
0
func HandleComment(c *webapp.Context) {
	if c.Request.Method == "POST" {
		IP := strings.Split(c.Request.RemoteAddr, ":")[0]
		comment := new(Comment)
		comment.Metadata.Name = UUID()
		comment.Metadata.IP = IP
		comment.Metadata.CreatedTime = time.Now().Unix()
		comment.Metadata.Author = strings.Trim(c.Request.FormValue("author"), " ")
		comment.Metadata.ArticleName = strings.Trim(c.Request.FormValue("article_name"), " /")
		comment.Metadata.UAgent = strings.Trim(c.Request.UserAgent(), " ")
		comment.Metadata.Email = strings.Trim(c.Request.FormValue("email"), " ")
		comment.Metadata.URL = strings.Trim(c.Request.FormValue("url"), " ")
		if strings.Index(comment.Metadata.URL, "http://") == -1 && strings.Index(comment.Metadata.URL, "https://") == -1 {
			comment.Metadata.URL = "http://" + comment.Metadata.URL
		}
		comment.Text = template.HTML(strings.Trim(c.Request.FormValue("text"), " "))

		var cookie *http.Cookie

		expires := time.Date(2099, time.November, 10, 23, 0, 0, 0, time.UTC)
		cookie = new(http.Cookie)
		cookie.Path = "/"
		cookie.Expires = expires
		cookie.Name = "author"
		cookie.Value = comment.Metadata.Author
		http.SetCookie(c.Writer, cookie)
		cookie.Name = "email"
		cookie.Value = comment.Metadata.Email
		http.SetCookie(c.Writer, cookie)
		cookie.Name = "url"
		cookie.Value = comment.Metadata.URL
		http.SetCookie(c.Writer, cookie)

		// verify the form data
		if len(comment.Metadata.Author) == 0 || len(comment.Metadata.Email) < 3 || len(comment.Text) < 3 || len(comment.Metadata.Author) > 20 || len(comment.Metadata.Email) > 32 {
			c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound)
			return
		}
		if !webapp.CheckEmailForm(comment.Metadata.Email) || (0 < len(comment.Metadata.URL) && !webapp.CheckURLForm(comment.Metadata.URL)) {
			c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound)
			return
		}
		if !TattooDB.Has(comment.Metadata.ArticleName) {
			c.Redirect("/"+comment.Metadata.ArticleName+"#respond", http.StatusFound)
			return
		}
		comment.Text = template.HTML(webapp.TransformTags(string(comment.Text)))
		comment.Metadata.EmailHash = MD5Sum(comment.Metadata.Email)
		TattooDB.AddComment(comment)
		TattooDB.PrependCommentTimeline(comment)
		c.Redirect("/"+comment.Metadata.ArticleName+"#comment_"+comment.Metadata.Name, http.StatusFound)
	} else {
		c.Redirect("/"+c.Request.FormValue("article_name"), http.StatusFound)
	}
}
示例#22
0
文件: sessions.go 项目: kobeld/mango
func commitSession(headers Headers, env Env, key, secret string, options *CookieOptions) {
	cookie := new(http.Cookie)
	cookie.Name = key
	cookie.Value = encodeCookie(env["mango.session"].(map[string]interface{}), secret)
	cookie.Path = options.Path
	cookie.Domain = options.Domain
	cookie.MaxAge = options.MaxAge
	cookie.Secure = options.Secure
	cookie.HttpOnly = options.HttpOnly
	headers.Add("Set-Cookie", cookie.String())
}
示例#23
0
func commitSession(headers Headers, env Env, key, secret string, newValue string, options *CookieOptions) {
	cookie := new(http.Cookie)
	cookie.Name = key
	cookie.Value = newValue
	cookie.Path = options.Path
	cookie.Domain = options.Domain
	cookie.MaxAge = options.MaxAge
	cookie.Secure = options.Secure
	cookie.HttpOnly = options.HttpOnly
	headers.Add("Set-Cookie", cookie.String())
}
示例#24
0
/*
   Set cookie "name" to "value", where "value" may be a string or interface
   converted to JSON. The "path" option defaults to "/".

   Set cookie `name` to `val`, with the given `options`.

   Options:

       - `maxAge`   max-age in milliseconds, converted to `expires`
       - `signed`   sign the cookie
       - `path`     defaults to "/"

   Examples:

       // "Remember Me" for 15 minutes
       res.Cookie("rememberme", "1", &httpCookie{ expires: new Date(Date.now() + 900000), httpOnly: true });

       // save as above
       res.Cookie("rememberme", "1", &httpCookie{ maxAge: 900000, httpOnly: true })
*/
func (this *Response) Cookie(n string, i interface{}, o ...*http.Cookie) {

	var cookie *http.Cookie

	/*
	   If we were given cookie options use them.
	*/

	if len(o) == 1 {
		cookie = o[0]
	} else {
		cookie = &http.Cookie{}
	}

	/*
	   Convert the given interface to a string so it can be used as a cookie value.
	*/

	var v string
	switch i.(type) {
	default:
		b, e := json.Marshal(i)
		v = string(b)
		if e != nil {
			v = e.Error()
		}
	case string:
		v = i.(string)
	}

	cookie.Name = n
	cookie.Value = url.QueryEscape(Encode(v))

	if cookie.Path == "" {
		cookie.Path = "/"
	}

	if cookie.MaxAge == 0 {
		// max-age in milliseconds, converted to `expires`
		// TODO: Check the timing here.
		cookie.Expires = time.Now().UTC().Add(time.Duration(cookie.MaxAge) * (time.Millisecond * time.Microsecond))
		cookie.MaxAge = cookie.MaxAge / 1000
	}

	// cookie.Domain = ""
	// cookie.Secure = false
	// cookie.HttpOnly = false

	/*
	   Possible bug if headers are already sent.
	*/

	http.SetCookie(this.Writer, cookie)
}
示例#25
0
func DeleteSessionId(w http.ResponseWriter) {
	// Resets sessionId.
	// When user logs out, his session id is set to
	// none, and thus Gorila will not be able to decode
	// the username of the user.

	var C http.Cookie
	C.Name = "sessionid"
	C.Value = "none"
	C.Path = "/"
	http.SetCookie(w, &C)
}
示例#26
0
文件: processor.go 项目: kdada/tinygo
// createCookie 创建cookie
func (this *HttpProcessor) createCookie(name string, id string, expire int) *http.Cookie {
	var cookieValue = new(http.Cookie)
	cookieValue.Name = name
	cookieValue.Value = id
	cookieValue.Path = "/"
	cookieValue.HttpOnly = true
	if expire > 0 {
		cookieValue.MaxAge = expire
		cookieValue.Expires = time.Now().Add(time.Second * time.Duration(expire))
	}
	return cookieValue
}
示例#27
0
// Needed due to https://github.com/couchbase/sync_gateway/issues/1345
func AddDbPathToCookie(rq *http.Request, cookie *http.Cookie) {

	// "/db/foo" -> "db/foo"
	urlPathWithoutLeadingSlash := strings.TrimPrefix(rq.URL.Path, "/")

	dbPath := "/"
	pathComponents := strings.Split(urlPathWithoutLeadingSlash, "/")
	if len(pathComponents) > 0 && pathComponents[0] != "" {
		dbPath = fmt.Sprintf("/%v", pathComponents[0])
	}
	cookie.Path = dbPath

}
示例#28
0
func TestIsLoggedInTrue(t *testing.T) {

	request, _ := http.NewRequest("GET", "/signin", nil)
	cookie := new(http.Cookie)
	cookie.Name = "gA"
	cookie.Value = "AAAAKmhlbGxvIHdvcmxksnOCwg1ctG-rNJ-g3gQinf-VSz3jTuP9jnitCs9ueZE="
	cookie.Path = "/"
	request.AddCookie(cookie)

	if !IsLoggedIn(request) {
		t.Errorf("expected login does not work")
	}
}
示例#29
0
func setUserKeyCookie(c *gin.Context, userKey, passCode string) {
	jwtIns := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uky": userKey,
		"upc": passCode,
	})

	encStr, _ := jwtIns.SignedString([]byte(conf.NodeAuth))
	cookie := new(http.Cookie)
	cookie.Name = "op_user"
	cookie.Expires = time.Now().Add(time.Duration(30*86400) * time.Second)
	cookie.Value = encStr
	cookie.Path = "/op"
	http.SetCookie(c.Writer, cookie)
}
示例#30
-1
func (c *Context) addLoginAs(name string, id string, timeduration ...time.Duration) {
	expire := time.Now().AddDate(0, 0, 1)
	if timeduration != nil {
		expire = time.Now().Add(timeduration[0])
	}
	cookie := new(http.Cookie)
	cookie.Name = name + "Id"
	cookie.Value = id
	cookie.Expires = expire
	cookie.Path = "/"
	cookie.RawExpires = expire.Format(time.UnixDate)
	c.AddSignedCookie(cookie)
}