forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
92 lines (83 loc) · 1.63 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
package uadmin
import (
"crypto/md5"
"encoding/base64"
"fmt"
"time"
)
// Session !
type Session struct {
Model
Key string
User User `uadmin:"filter"`
UserID uint
LoginTime time.Time
LastLogin time.Time
Active bool `uadmin:"filter"`
IP string `uadmin:"filter"`
PendingOTP bool `uadmin:"filter"`
ExpiresOn *time.Time
}
// String return string
func (s Session) String() string {
return s.Key
}
// Save !
func (s *Session) Save() {
u := s.User
s.User = User{}
// Verify required date fields
if s.LoginTime.IsZero() {
s.LoginTime = time.Now()
}
if s.LastLogin.IsZero() {
s.LastLogin = time.Now()
}
Save(s)
s.User = u
if CacheSessions {
if s.Active {
Preload(s)
cachedSessions[s.Key] = *s
} else {
delete(cachedSessions, s.Key)
}
}
}
// GenerateKey !
func (s *Session) GenerateKey() {
session := Session{}
hash := md5.New()
hash.Write([]byte(fmt.Sprint(s.UserID)))
userID := hash.Sum(nil)
for {
s.Key = GenerateBase64(102) + base64.URLEncoding.EncodeToString(userID)
s.Key = s.Key[:124]
Get(&session, "`key` = ?", s.Key)
if session.ID == 0 {
break
}
}
}
// Logout deactivates a session
func (s *Session) Logout() {
s.Active = false
s.Save()
}
// HideInDashboard to return false and auto hide this from dashboard
func (Session) HideInDashboard() bool {
return true
}
func loadSessions() {
if !CacheSessions {
return
}
sList := []Session{}
Filter(&sList, "`active` = ? AND (expires_on IS NULL OR expires_on > ?)", true, time.Now())
cachedSessions = map[string]Session{}
for _, s := range sList {
Preload(&s)
Preload(&s.User)
cachedSessions[s.Key] = s
}
}