-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsession.go
59 lines (49 loc) · 1.27 KB
/
session.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
package fir
import (
"errors"
"net/http"
"strings"
"github.com/google/uuid"
"github.com/gorilla/securecookie"
)
var errInvalidSession = errors.New("invalid session")
var errEmptySession = errors.New("empty session")
func decodeSession(sc securecookie.SecureCookie, cookieName, cookieValue string) (string, string, error) {
var session string
if err := sc.Decode(cookieName, cookieValue, &session); err != nil {
return "", "", err
}
if session == "" {
return "", "", errEmptySession
}
parts := strings.Split(session, ":")
if len(parts) != 2 {
return "", "", errInvalidSession
}
return parts[0], parts[1], nil
}
func encodeSession(opt routeOpt, w http.ResponseWriter, r *http.Request) error {
var sessionID string
cookie, err := r.Cookie(opt.cookieName)
if err == nil && cookie != nil {
sessionID, _, _ = decodeSession(*opt.secureCookie, opt.cookieName, cookie.Value)
if sessionID == "" {
sessionID = uuid.New().String()
}
}
if sessionID == "" {
sessionID = uuid.New().String()
}
session := sessionID + ":" + opt.id
encodedSessionID, err := opt.secureCookie.Encode(opt.cookieName, session)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: opt.cookieName,
Value: encodedSessionID,
MaxAge: 0,
Path: "/",
})
return nil
}