chore: sync with gin-template

This commit is contained in:
JustSong
2022-11-22 11:04:06 +08:00
parent 8247192977
commit 5913266969
41 changed files with 813 additions and 490 deletions
+62 -7
View File
@@ -4,6 +4,7 @@ import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"message-pusher/common"
"message-pusher/model"
"net/http"
)
@@ -13,13 +14,34 @@ func authHelper(c *gin.Context, minRole int) {
role := session.Get("role")
id := session.Get("id")
status := session.Get("status")
authByToken := false
if username == nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无权进行此操作,用户未登录",
})
c.Abort()
return
// Check token
token := c.Request.Header.Get("Authorization")
if token == "" {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无权进行此操作,未登录或 token 无效",
})
c.Abort()
return
}
user := model.ValidateUserToken(token)
if user != nil && user.Username != "" {
// Token is valid
username = user.Username
role = user.Role
id = user.Id
status = user.Status
} else {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无权进行此操作,token 无效",
})
c.Abort()
return
}
authByToken = true
}
if status.(int) == common.UserStatusDisabled {
c.JSON(http.StatusOK, gin.H{
@@ -32,7 +54,7 @@ func authHelper(c *gin.Context, minRole int) {
if role.(int) < minRole {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无权进行此操作,用户未登录或没有权限",
"message": "无权进行此操作,权限不足",
})
c.Abort()
return
@@ -40,6 +62,7 @@ func authHelper(c *gin.Context, minRole int) {
c.Set("username", username)
c.Set("role", role)
c.Set("id", id)
c.Set("authByToken", authByToken)
c.Next()
}
@@ -60,3 +83,35 @@ func RootAuth() func(c *gin.Context) {
authHelper(c, common.RoleRootUser)
}
}
// NoTokenAuth You should always use this after normal auth middlewares.
func NoTokenAuth() func(c *gin.Context) {
return func(c *gin.Context) {
authByToken := c.GetBool("authByToken")
if authByToken {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "本接口不支持使用 token 进行验证",
})
c.Abort()
return
}
c.Next()
}
}
// TokenOnlyAuth You should always use this after normal auth middlewares.
func TokenOnlyAuth() func(c *gin.Context) {
return func(c *gin.Context) {
authByToken := c.GetBool("authByToken")
if !authByToken {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "本接口仅支持使用 token 进行验证",
})
c.Abort()
return
}
c.Next()
}
}