This repository has been archived by the owner on Oct 15, 2019. It is now read-only.
forked from seven5/seven5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookie.go
79 lines (69 loc) · 2.34 KB
/
cookie.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package seven5
import (
"errors"
"fmt"
"net/http"
"strings"
)
const (
SESSION_COOKIE = "%s-seven5-session"
)
var (
NO_SUCH_COOKIE = errors.New("Cannot find cookie")
)
//CookieMapper mediates the interaction between requests and cookies. Most applications probably
//want to implement the SessionManager not the CookieMapper. CookieMapper is primarily of interest
//for those who need to interact with the Set-Cookie and Cookie headers from/to the browser.
type CookieMapper interface {
CookieName() string
Value(*http.Request) (string, error)
AssociateCookie(http.ResponseWriter, Session)
RemoveCookie(http.ResponseWriter)
}
//SimpleCookieMapper is a default, cookie mapper that maps UDID strings to Session
//objects and uses a simple cookie scheme to extract the UDIDs from requests generated by the
//browser.
type SimpleCookieMapper struct {
cook string
}
//NewSimpleCookieMapper creates an instance of CookieMapper with the given application name.
func NewSimpleCookieMapper(appName string) CookieMapper {
result := &SimpleCookieMapper{
cook: fmt.Sprintf(SESSION_COOKIE, appName),
}
return result
}
//AssociateCookie is used to effectively "Log in" a particular user by associating a session
//with a response w that will be sent back to their browser.
func (self *SimpleCookieMapper) AssociateCookie(w http.ResponseWriter, s Session) {
cookie := &http.Cookie{
Name: self.CookieName(),
Value: s.SessionId(),
Path: "/",
}
http.SetCookie(w, cookie)
}
//RemoveCookie is used to effectively "Log out" a particular user by removing the association of a session
//with a response w that will be sent back to their browser.
func (self *SimpleCookieMapper) RemoveCookie(w http.ResponseWriter) {
cookie := &http.Cookie{
Name: self.CookieName(),
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(w, cookie)
}
//Value returns the cookie value associated with a given request or an error if that cookie is not
//present. Usually the value is the UDID of the session.
func (self *SimpleCookieMapper) Value(r *http.Request) (string, error) {
c, err := r.Cookie(self.CookieName())
if err == http.ErrNoCookie {
return "", NO_SUCH_COOKIE
}
return strings.TrimSpace(c.Value), nil
}
//CookieName returns the name of the cookie used for this application by this session manager.
func (self *SimpleCookieMapper) CookieName() string {
return self.cook
}