-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
55 lines (48 loc) · 911 Bytes
/
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
package main
import (
"github.com/gin-gonic/gin"
)
const (
XAuthToken = "X-Auth-Token"
CurrentUserKey = "current_user"
)
// 身份中间件
func authen() gin.HandlerFunc {
return func(c *gin.Context) {
var (
tok string
uid string
cu *User
)
if tok = c.Request.Header.Get(XAuthToken); tok == "" {
return
}
// 从redis中获取用户的uid
if uid = getFromCacheString(tok); uid == "" {
return
}
if cu = getUserById(uid); cu == nil {
return
}
c.Set(CurrentUserKey, cu)
}
}
// 需要登陆
func needLogin() gin.HandlerFunc {
return func(c *gin.Context) {
_, ok := c.Get(CurrentUserKey)
if !ok {
// Todo: 直接重定向到登陆页面
c.JSON(200, RespResult{ErrCodeNeedLogin, ErrMsgNeedLogin, nil})
c.Abort()
return
}
}
}
func getCurrent(c *gin.Context) *User {
v, ok := c.Get(CurrentUserKey)
if !ok {
return nil
}
return v.(*User)
}