-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
session.go
104 lines (82 loc) · 2.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package api
import (
"errors"
"net/http"
"github.com/stashapp/stash-box/pkg/manager/config"
"github.com/stashapp/stash-box/pkg/user"
"github.com/gorilla/sessions"
)
const cookieName = "session"
const usernameFormKey = "username"
const passwordFormKey = "password"
const userIDKey = "userID"
const maxCookieAge = 60 * 60 * 1 // 1 hours
var sessionStore *sessions.CookieStore
func InitializeSession() {
sessionStore = sessions.NewCookieStore(config.GetSessionStoreKey())
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
newSession, err := sessionStore.Get(r, cookieName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
username := r.FormValue(usernameFormKey)
password := r.FormValue(passwordFormKey)
fac := getRepo(r.Context())
// authenticate the user
userID, err := user.Authenticate(fac, username, password)
if errors.Is(err, user.ErrAccessDenied) {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
newSession.Values[userIDKey] = userID
newSession.Options.MaxAge = maxCookieAge
newSession.Options.HttpOnly = true
if config.GetIsProduction() {
newSession.Options.Secure = true
}
err = newSession.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
session, err := sessionStore.Get(r, cookieName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
delete(session.Values, userIDKey)
session.Options.MaxAge = -1
err = session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func getSessionUserID(w http.ResponseWriter, r *http.Request) (string, error) {
session, err := sessionStore.Get(r, cookieName)
if err != nil {
session.Options.MaxAge = -1
if err = session.Save(r, w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return "", nil
}
if !session.IsNew {
userIDInt := session.Values[userIDKey]
userID, _ := userIDInt.(string)
// refresh the cookie
err = session.Save(r, w)
if err != nil {
return "", err
}
return userID, nil
}
return "", nil
}