forked from mojocn/felix
/
mw_jwt.go
46 lines (39 loc) · 1.04 KB
/
mw_jwt.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
package internal
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/libragen/felix/model"
)
const contextKeyUserObj = "authedUserObj"
const bearerLength = len("Bearer ")
func ctxTokenToUser(c *gin.Context, roleId uint) {
token, ok := c.GetQuery("_t")
if !ok {
hToken := c.GetHeader("Authorization")
if len(hToken) < bearerLength {
c.AbortWithStatusJSON(http.StatusPreconditionFailed, gin.H{"msg": "header Authorization has not Bearer token"})
return
}
token = strings.TrimSpace(hToken[bearerLength:])
}
usr, err := model.JwtParseUser(token)
if err != nil {
c.AbortWithStatusJSON(http.StatusPreconditionFailed, gin.H{"msg": err.Error()})
return
}
if (usr.RoleId & roleId) != roleId {
c.AbortWithStatusJSON(http.StatusPreconditionFailed, gin.H{"msg": "roleId 没有权限"})
return
}
//store the user Model in the context
c.Set(contextKeyUserObj, *usr)
c.Next()
// after request
}
func MwUserAdmin(c *gin.Context) {
ctxTokenToUser(c, 2)
}
func MwUserComment(c *gin.Context) {
ctxTokenToUser(c, 8)
}