-
Notifications
You must be signed in to change notification settings - Fork 16
/
auth.go
61 lines (51 loc) · 1.08 KB
/
auth.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
package admin
import (
"net/http"
"time"
)
func (a *Admin) getUserSession(req *http.Request) *session {
cookie, err := req.Cookie("admin")
if err != nil {
return nil
}
if sess, ok := a.sessions[cookie.Value]; ok {
return sess
}
return nil
}
func (a *Admin) logIn(rw http.ResponseWriter, username, password string) bool {
if username != a.username || password != a.password {
return false
}
sessKey := randString(32)
a.sessions[sessKey] = &session{
time: time.Now(),
messages: []*flashMessage{},
}
http.SetCookie(rw, &http.Cookie{
Name: "admin",
Value: sessKey,
Path: a.path,
})
return true
}
type session struct {
time time.Time
messages []*flashMessage
}
func (s *session) addMessage(class, text string) {
s.messages = append(s.messages, &flashMessage{class, text})
}
func (s *session) getMessages() []*flashMessage {
// If empty, there's no need to create a new slice.
if len(s.messages) == 0 {
return s.messages
}
messages := s.messages
s.messages = []*flashMessage{}
return messages
}
type flashMessage struct {
Class string
Text string
}