-
Notifications
You must be signed in to change notification settings - Fork 93
/
cookie.go
72 lines (64 loc) · 1.46 KB
/
cookie.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
package drivers
import (
"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"
"morningo/config"
"net/http"
)
var store = sessions.NewCookieStore([]byte(config.GetEnv().AppSecret))
type cookieAuthManager struct {
name string
}
func NewCookieAuthDriver() *cookieAuthManager {
return &cookieAuthManager{
name: config.GetCookieConfig().NAME,
}
}
func (cookie *cookieAuthManager) Check(c *gin.Context) bool {
// read cookie
session, err := store.Get(c.Request, cookie.name)
if err != nil {
return false
}
if session == nil {
return false
}
if session.Values == nil {
return false
}
if session.Values["id"] == nil {
return false
}
return true
}
func (cookie *cookieAuthManager) User(c *gin.Context) interface{} {
// get model user
session, err := store.Get(c.Request, cookie.name)
if session == nil {
panic("wrong session")
}
if err != nil {
return session.Values
}
return session.Values
}
func (cookie *cookieAuthManager) Login(http *http.Request, w http.ResponseWriter, user map[string]interface{}) interface{} {
// write cookie
session, err := store.Get(http, cookie.name)
if err != nil {
return false
}
session.Values["id"] = user["id"]
_ = session.Save(http, w)
return true
}
func (cookie *cookieAuthManager) Logout(http *http.Request, w http.ResponseWriter) bool {
// del cookie
session, err := store.Get(http, cookie.name)
if err != nil {
return false
}
session.Values["id"] = nil
_ = session.Save(http, w)
return true
}