Example #1
0
// Get the session from the cookie in the request
// Creates a new session and cookie if none can be found
func getSession(w http.ResponseWriter, req *http.Request) (*Session, bool) {

	cookie, err := req.Cookie("id")
	if err == nil {
		s, ok := sessionSync(cookie.Value)
		if ok {
			return s, ok
		}

		log.Println("Invalid session cookie presented: ", cookie.Value)
	}

	// Create a session
	s := newSession()
	config.Debug("Creating new session ", s.id)
	sessions.Create(s)

	// Write the session to the HTTP response
	newcookie := http.Cookie{
		Name:     "id",
		Value:    s.id,
		Path:     "/",
		MaxAge:   math.MaxInt32,
		HttpOnly: true}
	w.Header().Add("Set-Cookie", newcookie.String())

	s.mutex.Lock()
	return s, true
}
Example #2
0
//User login
func (uc UsersController) login(request *restful.Request,
	response *restful.Response) {
	loginCredentials := new(UserLoginCredentials)
	err := request.ReadEntity(loginCredentials)
	if err != nil {
		LogError(request, response, err)
		WriteIllegalRequestError(response)
		return
	}
	cookieAuth, err := new(UserManager).Login(loginCredentials)
	if err != nil {
		LogError(request, response, err)
		WriteError(err, response)
		return
	}
	//Create an Auth cookie
	authCookie := http.Cookie{
		Name:     "AuthSession",
		Value:    cookieAuth.AuthToken,
		Path:     "/",
		HttpOnly: true,
	}
	//Create a CSRF cookie for this session
	//Subsequent requests must include this in a header field
	//X-Csrf-Token
	csrfCookie := http.Cookie{
		Name:     "CsrfToken",
		Value:    util.GenHashString(cookieAuth.AuthToken),
		Path:     "/",
		HttpOnly: false,
	}
	response.AddHeader("Set-Cookie", authCookie.String())
	response.AddHeader("Set-Cookie", csrfCookie.String())
	response.WriteEntity(BooleanResponse{Success: true})
}
Example #3
0
func (this *loginController) login(w http.ResponseWriter, req *http.Request) {
	w.Header().Add("Content-Type", "text/html")
	responseWriter := util.GetResponseWriter(w, req)
	defer responseWriter.Close()

	if req.Method == "POST" {
		email := req.FormValue("email")
		password := req.FormValue("password")

		member, err := models.GetMember(email, password)
		if err != nil {
			responseWriter.Write([]byte(err.Error()))
			return
		}

		session, err := models.CreateSession(member)
		if err != nil {
			responseWriter.Write([]byte(err.Error()))
			return
		}

		var cookie http.Cookie
		cookie.Name = "sessionId"
		cookie.Value = session.SessionId()
		responseWriter.Header().Add("Set-Cookie", cookie.String())
	}
	vm := viewmodels.GetLogin()
	this.template.Execute(responseWriter, vm)
}
Example #4
0
//User logout
func (uc UsersController) logout(request *restful.Request,
	response *restful.Response) {
	token := func() string {
		for _, cookie := range request.Request.Cookies() {
			if cookie.Name == "AuthSession" {
				return cookie.Value
			}
		}
		return ""
	}()
	err := new(UserManager).Logout(token)
	if err != nil {
		LogError(request, response, err)
		WriteError(err, response)
		return
	}
	//Because CouchDB doesn't actually destroy the session,
	//best we can do is clear the cookie in the browser.
	//This is apparently "not a bug" :|
	//http://webmail.dev411.com/t/couchdb/dev/141xwf5vb0/jira-created-couchdb-2042-session-not-cleared-after-delete-session-cookie-auth
	theCookie := http.Cookie{
		Name:     "AuthSession",
		Value:    "",
		Path:     "/",
		HttpOnly: true,
	}
	response.AddHeader("Set-Cookie", theCookie.String())
	response.WriteEntity(BooleanResponse{Success: true})
}
Example #5
0
func (h *homeController) login(w http.ResponseWriter, req *http.Request) {
	responseWriter := util.GetResponseWriter(w, req)
	defer responseWriter.Close()

	w.Header().Add("Content Type", "text/html")

	if req.Method == "POST" {
		email := req.FormValue("email")
		password := req.FormValue("password")

		member, err := models.GetMember(email, password)

		if err == nil {
			session, err := models.CreateSession(member)
			log.Printf("create session err: %v", err)
			if err == nil {
				var cookie http.Cookie
				cookie.Name = "sessionId"
				cookie.Value = session.SessionId()
				responseWriter.Header().Add("Set-Cookie", cookie.String())
			}
		} else {
			log.Print("User not found!")
		}
	}

	vm := viewmodels.GetLogin()

	h.loginTemplate.Execute(responseWriter, vm)
}
Example #6
0
func commitSession(headers Headers, env Env, key, secret, domain string) {
	cookie := new(http.Cookie)
	cookie.Name = key
	cookie.Value = encodeCookie(env["mango.session"].(map[string]interface{}), secret)
	cookie.Domain = domain
	headers.Add("Set-Cookie", cookie.String())
}
Example #7
0
func setStickyCookieBackend(res *http.Response, backend string, cookieKey [32]byte) {
	cookie := http.Cookie{
		Name:  stickyCookie,
		Value: base64.StdEncoding.EncodeToString(encrypt([]byte(backend), cookieKey)),
		Path:  "/",
	}
	res.Header.Add("Set-Cookie", cookie.String())
}
Example #8
0
func (s *Session) DeleteCookie(options cookieOptions, response http.ResponseWriter) {
	cookie := http.Cookie{
		Name:   options.Name,
		Value:  "-",
		MaxAge: -1,
	}

	response.Header().Set("Set-Cookie", cookie.String())
}
Example #9
0
func clearAllCookies(rw http.ResponseWriter, req *http.Request) {
	for _, ck := range req.Cookies() {
		ck2 := http.Cookie{
			Name:   ck.Name,
			MaxAge: -1,
		}
		rw.Header().Add("Set-Cookie", ck2.String())
	}
}
Example #10
0
func AddCsrfCookie(rw http.ResponseWriter, sessToken string) {
	csrfCookie := http.Cookie{
		Name:     "CsrfToken",
		Value:    util.GenHashString(sessToken),
		Path:     "/",
		HttpOnly: false,
	}
	rw.Header().Add("Set-Cookie", csrfCookie.String())
}
Example #11
0
File: ctx.go Project: 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())
}
Example #12
0
// Duration is the cookie time-to-live in seconds (0 = forever).
func (ctx *Context) SetCookie(name, value string, age int64) {
	var utctime time.Time
	if age == 0 {
		// 2^31 - 1 seconds (roughly 2038)
		utctime = time.Unix(2147483647, 0)
	} else {
		utctime = time.Unix(time.Now().Unix()+age, 0)
	}
	cookie := http.Cookie{Name: name, Value: value, Expires: utctime, Path: "/"}
	ctx.Header().Add("Set-Cookie", cookie.String())
}
Example #13
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())
}
Example #14
0
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())
}
Example #15
0
func (s *Session) WriteCookie(options cookieOptions, response http.ResponseWriter) {
	cookie := http.Cookie{
		Name:     options.Name,
		Value:    s.ID,
		Expires:  time.Now().Add(options.MaxAge),
		HttpOnly: options.HttpOnly,
		Secure:   options.Secure,
	}

	response.Header().Set("Set-Cookie", cookie.String())
}
Example #16
0
func ClearAuth(rw http.ResponseWriter) {
	//Clear the session cookie
	theCookie := http.Cookie{
		Name:     "AuthSession",
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
	}
	rw.Header().Add("Set-Cookie", theCookie.String())
}
Example #17
0
func (self *Cookie) Set(writer http.ResponseWriter, value string) {
	cookie := http.Cookie{
		Name:    self.Key,
		Value:   value,
		Expires: expires,
		MaxAge:  630720000,
	}
	writer.Header().Set("Set-Cookie", cookie.String())

	return
}
Example #18
0
func fetchHandler(w http.ResponseWriter, urlStr string, ctx appengine.Context) {
	ctx.Infof("fetchHandler urlStr arg is %s", urlStr)
	i := strings.LastIndex(urlStr, "/")
	baseUrlStr := urlStr[0 : i+1]

	expires := time.Now().Add(time.Minute)
	ctx.Infof("Setting expires to %s", expires)
	cookie := http.Cookie{Name: PROXY_BASE_URL_COOKIE, Value: baseUrlStr, Expires: expires}
	ctx.Infof("Setting cookie to %s", cookie.String())
	http.SetCookie(w, &cookie)
}
Example #19
0
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())
}
Example #20
0
//Add 增加,写入一条Cookie,可以写入多条Cookie保存至浏览器
func (c *Cookie) Add(name, value, path, domain string, maxAge int, secure, only bool) {
	var cookie = http.Cookie{
		Name:     name,
		Value:    value,
		Path:     path,
		Domain:   domain,
		Expires:  time.Now(),
		MaxAge:   maxAge,
		Secure:   secure,
		HttpOnly: only,
	}
	c.w.Header().Add("Set-Cookie", cookie.String())
}
Example #21
0
// SetCookie adds a cookie header to the response.
func (ctx *Context) SetCookie(name string, value string, a ...int) {
	var utctime time.Time
	var age int64 // seconds
	if len(a) > 0 {
		age = int64(a[0])
	}
	if age == 0 {
		utctime = time.Unix(time.Now().Unix()+86400, 0)
	} else {
		utctime = time.Unix(time.Now().Unix()+age, 0)
	}
	cookie := http.Cookie{Name: name, Value: value, Expires: utctime}
	ctx.SetHeader("Set-Cookie", cookie.String())
}
Example #22
0
func (this *homeController) login(w http.ResponseWriter, req *http.Request) {

	responseWriter := util.GetResponseWriter(w, req)
	defer responseWriter.Close()

	responseWriter.Header().Add("Content-Type", "text/html")

	vm := viewmodels.GetLogin()

	if req.FormValue("submit") == "signup" {
		http.Redirect(w, req, "/signup", http.StatusFound)
	} else {

		if req.Method == "POST" {

			email := req.FormValue("email")
			password := req.FormValue("password")

			member, err := models.GetMember(email, password)

			if err == nil {
				session, err := models.CreateSession(member)

				if err == nil {
					var cookie http.Cookie
					cookie.Name = "goSessionId"
					cookie.Expires = time.Now().Add(10 * time.Minute)
					cookie.Value = strconv.Itoa(session.MemberId())
					responseWriter.Header().Add("Set-Cookie", cookie.String())

					var cookie2 http.Cookie
					cookie2.Name = "loggedName"
					cookie2.Expires = time.Now().Add(10 * time.Minute)
					cookie2.Value = member.FirstName()
					responseWriter.Header().Add("Set-Cookie", cookie2.String())
				}
				vmh := viewmodels.GetHome()

				vmh.LoggedIn = true
				vmh.LoggedName = member.FirstName()

				this.template.Execute(responseWriter, vmh)
			} else {
				this.loginTemplate.Execute(responseWriter, vm)
			}
		} else {
			this.loginTemplate.Execute(responseWriter, vm)
		}
	}
}
Example #23
0
// SetCookie adds a cookie header to the response.
func (ctx *Context) SetCookie(name string, value string, a ...int) {
	var utctime time.Time
	var age int64
	if len(a) > 0 {
		age = int64(a[0])
	}
	if age == 0 {
		// 2^31 - 1 seconds (roughly 2038)
		utctime = time.Unix(2147483647, 0)
	} else {
		utctime = time.Unix(time.Now().Unix()+age, 0)
	}
	cookie := http.Cookie{Name: name, Value: value, Expires: utctime}
	ctx.AddHeader("Set-Cookie", cookie.String())
}
func (h *AuthCookieHandler) GenerateCookie(w http.ResponseWriter, req *http.Request) {
	authorization := req.Header.Get("Authorization")

	if authorization != "" {
		cookie := http.Cookie{
			Name:     receptor.AuthorizationCookieName,
			Value:    authorization,
			MaxAge:   0,
			HttpOnly: true,
		}
		w.Header().Set("Set-Cookie", cookie.String())
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #25
0
func cookieString(ck *http.Cookie, reset_domain *string, setCookie bool) string {
	if !setCookie {
		// inaccurate
		return ck.Name + "=" + ck.Value
	}
	if reset_domain != nil {
		dot := strings.IndexByte(*reset_domain, '.')
		if dot > 1 {
			ck.Domain = *reset_domain
		} else {
			ck.Domain = NULL
		}
	}
	return ck.String()
}
Example #26
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())
}
Example #27
0
func SetAuth(rw http.ResponseWriter, ca couchdb.Auth) {
	authData := ca.GetUpdatedAuth()
	if authData == nil {
		return
	}
	if val, ok := authData["AuthSession"]; ok {
		authCookie := http.Cookie{
			Name:     "AuthSession",
			Value:    val,
			Path:     "/",
			HttpOnly: true,
		}
		rw.Header().Add("Set-Cookie", authCookie.String())
		AddCsrfCookie(rw, util.GenHashString(val))
	}
}
Example #28
0
func (this *homeController) signup(w http.ResponseWriter, req *http.Request) {

	responseWriter := util.GetResponseWriter(w, req)
	defer responseWriter.Close()

	responseWriter.Header().Add("Content-Type", "text/html")

	if req.Method == "POST" {
		firstName := req.FormValue("firstName")
		email := req.FormValue("email")
		password := req.FormValue("password")

		err := models.InsertMember(firstName, email, password)

		if err == nil {
			member, _ := models.GetMember(email, password)

			member, errr := models.GetMember(email, password)

			if errr == nil {
				session, err := models.CreateSession(member)

				if err == nil {
					var cookie http.Cookie
					cookie.Name = "goSessionId"
					cookie.Expires = time.Now().Add(10 * time.Minute)
					cookie.Value = strconv.Itoa(session.MemberId())
					responseWriter.Header().Add("Set-Cookie", cookie.String())

					var cookie2 http.Cookie
					cookie2.Name = "loggedName"
					cookie2.Expires = time.Now().Add(10 * time.Minute)
					cookie2.Value = member.FirstName()
					responseWriter.Header().Add("Set-Cookie", cookie2.String())
				}

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

	vm := viewmodels.GetSignup()

	this.signupTemplate.Execute(responseWriter, vm)

}
Example #29
0
func (s *Session) Save(w http.ResponseWriter, keepalive bool) error {
	q := `
        UPDATE user_session SET
            valid_until = ?
            , modified_date = ?
        WHERE id = ?;
    `

	valid := int64(0)

	if keepalive {
		valid = time.Now().Unix() + SESSION_OFFSET
	}

	params := []interface{}{
		valid,
		time.Now().Unix(),
		s.Id,
	}

	_, err := dao.Exec(q, params)
	if err != nil {
		return err
	}

	expires := -1

	if keepalive {
		expires, _ = strconv.Atoi(config.Get("session_cookie_expires"))
	}

	secure, _ := strconv.ParseBool(config.Get("session_cookie_secure"))

	c := new(http.Cookie)
	c.Name = config.Get("session_cookie_name")
	if keepalive {
		c.Value = s.Key
	}
	c.Path = config.Get("session_cookie_path")
	c.MaxAge = expires
	c.Secure = secure

	http.SetCookie(w, c)
	logger.Log(w, "SET-COOKIE", c.String())
	return nil
}
Example #30
0
func Set(w http.ResponseWriter, s string) {
	secure, _ := strconv.ParseBool(config.Get("session_cookie_secure"))

	c := new(http.Cookie)
	c.Name = fmt.Sprintf("%s-flash", config.Get("session_cookie_name"))
	c.Path = config.Get("session_cookie_path")
	c.Value = base64.URLEncoding.EncodeToString([]byte(strings.TrimSpace(s)))
	if c.Value != "" {
		c.MaxAge = 0
	} else {
		c.MaxAge = -1
	}
	c.Secure = secure

	http.SetCookie(w, c)
	logger.Log(w, "SET-COOKIE", c.String())
}