-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
83 lines (66 loc) · 2.3 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package session
import (
"net/http"
"strconv"
"github.com/gorilla/sessions"
"github.com/pkg/errors"
"github.com/skeswa/chorro/apps/server/cache"
)
// Encapsulates the session information encoded within a particular request.
type Session struct {
// True if the user is logged in.
IsUserLoggedIn bool
// Unique identifier of the logged in user if the user is logged in.
UserID uint
// Session instance wrapped by this struct.
inner *sessions.Session
// HTTP request with which this Session is associated.
request *http.Request
// HTTP repsonse writer paired with request.
responseWriter http.ResponseWriter
}
// Attaches a user to this Session.
func (session *Session) LogIn(userID uint) error {
userIDString := strconv.FormatUint(uint64(userID), 10)
session.inner.Values[userIDSessionKey] = userIDString
if err := session.inner.Save(session.request, session.responseWriter); err != nil {
return errors.Wrapf(err, "Failed to attach user with \"%d\" to session", userID)
}
session.IsUserLoggedIn = true
session.UserID = userID
return nil
}
// Ends this Session, effectively logging the user out.
func (session *Session) LogOut() error {
// Expire the session to "destroy" it.
session.inner.Options.MaxAge = -1
if err := session.inner.Save(session.request, session.responseWriter); err != nil {
return errors.Wrap(err, "Failed to destroy the session")
}
session.IsUserLoggedIn = false
session.UserID = 0
return nil
}
// Reads the Session of the specified request, and its associated response writer.
func read(cache *cache.Cache, request *http.Request, responseWriter http.ResponseWriter) *Session {
// Get the innersession. We're ignoring the error resulting from decoding an
// existing session: Get() always returns a session, even if empty.
inner, _ := cache.SessionStore.Get(request, sessionName)
session := Session{
IsUserLoggedIn: false,
UserID: 0,
inner: inner,
request: request,
responseWriter: responseWriter,
}
rawUserID, hasRawUserID := inner.Values[userIDSessionKey]
if hasRawUserID {
if userIDString, isRawUserIDAString := rawUserID.(string); isRawUserIDAString {
if userIDInt64, err := strconv.ParseUint(userIDString, 10, 32); err == nil {
session.IsUserLoggedIn = true
session.UserID = uint(userIDInt64)
}
}
}
return &session
}