-
Notifications
You must be signed in to change notification settings - Fork 25
/
adminmdw.go
111 lines (96 loc) · 2.22 KB
/
adminmdw.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
105
106
107
108
109
110
111
package mdw
import (
"encoding/gob"
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/i2eco/egoshop/appgo/model/mysql"
)
const SessionDefaultKey = "i2eco/mdw/session"
const ContextUser = "mdw/member"
func init() {
gob.Register(mysql.User{})
}
// 后台取用户
func LoginRequired() gin.HandlerFunc {
return func(c *gin.Context) {
one := mysql.User{}
// 从session中获取用户信息
if user, ok := DefaultSessionUser(c); ok && user.Id > 0 {
one = user
} else {
}
c.Set(ContextUser, one)
c.Next()
}
}
// 后台取用户
func LoginAPIRequired() gin.HandlerFunc {
return func(c *gin.Context) {
one := mysql.User{}
// 从session中获取用户信息
if user, ok := DefaultSessionUser(c); ok && user.Id > 0 {
one = user
} else {
c.JSON(http.StatusOK, gin.H{
"code": 401,
"data": "",
"msg": "user not login",
})
c.Abort()
return
}
c.Set(ContextUser, one)
c.Next()
}
}
// 后台取用户
func DefaultSessionUser(c *gin.Context) (mysql.User, bool) {
resp, flag := sessions.Default(c).Get(SessionDefaultKey).(mysql.User)
return resp, flag
}
// 后台取用户
func DefaultContextUser(c *gin.Context) mysql.User {
var resp mysql.User
respI, flag := c.Get(ContextUser)
if flag {
resp = respI.(mysql.User)
}
return resp
}
// Authed 鉴权通过
func AdminAuthed(c *gin.Context) bool {
if user, ok := DefaultSessionUser(c); ok && user.Id > 0 {
return true
}
return false
}
// 后台 Uid 返回uid
func AdminUid(c *gin.Context) int {
return DefaultContextUser(c).Id
}
// UpdateUser updates the User object stored in the session. This is useful incase a change
// is made to the user model that needs to persist across requests.
func UpdateUser(c *gin.Context, a mysql.User) error {
s := sessions.Default(c)
s.Options(sessions.Options{
Path: "/",
MaxAge: 24 * 3600,
Secure: false,
HttpOnly: true,
})
s.Set(SessionDefaultKey, a)
return s.Save()
}
// Logout will clear out the session and call the Logout() user function.
func Logout(c *gin.Context) error {
s := sessions.Default(c)
s.Options(sessions.Options{
Path: "/",
MaxAge: -1,
Secure: false,
HttpOnly: true,
})
s.Delete(SessionDefaultKey)
return s.Save()
}