/
session_user.go
52 lines (43 loc) · 1.34 KB
/
session_user.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
package gotuna
import (
"errors"
"net/http"
)
const (
// UserIDKey is used as session key to store the current's user unique ID.
UserIDKey = "_user_id"
// UserLocaleKey is used as session key for the current's user locale settings.
UserLocaleKey = "_user_locale"
)
// IsGuest checks if current user is not logged in into the app.
func (s Session) IsGuest(r *http.Request) bool {
id, err := s.GetUserID(r)
if err != nil || id == "" {
return true
}
return false
}
// SetUserID will save the current user's unique ID into the session.
func (s Session) SetUserID(w http.ResponseWriter, r *http.Request, id string) error {
return s.Put(w, r, UserIDKey, id)
}
// GetUserID retrieves the current user's unique ID from the session.
func (s Session) GetUserID(r *http.Request) (string, error) {
id, err := s.Get(r, UserIDKey)
if err != nil || id == "" {
return "", errors.New("no user in the session")
}
return id, nil
}
// SetLocale will store the user's locale string into the session.
func (s Session) SetLocale(w http.ResponseWriter, r *http.Request, id string) error {
return s.Put(w, r, UserLocaleKey, id)
}
// GetLocale retrieves the current user's locale string from the session.
func (s Session) GetLocale(r *http.Request) string {
locale, err := s.Get(r, UserLocaleKey)
if err != nil {
return "" // TODO: default locale
}
return locale
}