-
Notifications
You must be signed in to change notification settings - Fork 40
/
cookie.go
77 lines (61 loc) · 1.61 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
package authenticate
import (
"net/http"
"os"
"time"
"github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/models"
"github.com/gorilla/securecookie"
)
var hashKey []byte
var blockKey []byte
var s *securecookie.SecureCookie
func CreateSecureCookie(u *models.User, sessionID string, w http.ResponseWriter, r *http.Request) error {
value := map[string]string{
"username": u.Username,
"sid": sessionID,
}
if encoded, err := s.Encode("session", value); err == nil {
cookie := &http.Cookie{
Name: "session",
Value: encoded,
Path: "/",
Secure: false,
HttpOnly: true,
}
http.SetCookie(w, cookie)
} else {
return err
}
return nil
}
func ReadSecureCookieValues(w http.ResponseWriter, r *http.Request) (map[string]string, error) {
if cookie, err := r.Cookie("session"); err == nil {
value := make(map[string]string)
if err = s.Decode("session", cookie.Value, &value); err == nil {
return value, nil
} else {
return nil, err
}
} else {
return nil, nil
}
}
func ExpireSecureCookie(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "session",
Value: "",
Path: "/",
MaxAge: -1,
}
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
w.Header().Set("Expires", time.Unix(0, 0).Format(http.TimeFormat))
w.Header().Set("Pragma", "no-cache")
w.Header().Set("X-Accel-Expires", "0")
http.SetCookie(w, cookie)
http.Redirect(w, r, "/login", 301)
}
func init() {
hashKey = []byte(os.Getenv("GOPHERFACE_HASH_KEY"))
blockKey = []byte(os.Getenv("GOPHERFACE_BLOCK_KEY"))
s = securecookie.New(hashKey, blockKey)
}