ai-gateway/middleware/auth.go

89 lines
1.7 KiB
Go
Raw Normal View History

2023-04-22 12:39:27 +00:00
package middleware
import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
2023-04-22 13:14:09 +00:00
"one-api/common"
"one-api/model"
2023-04-23 10:24:11 +00:00
"strings"
2023-04-22 12:39:27 +00:00
)
func authHelper(c *gin.Context, minRole int) {
session := sessions.Default(c)
username := session.Get("username")
role := session.Get("role")
id := session.Get("id")
status := session.Get("status")
if username == nil {
2023-04-23 10:24:11 +00:00
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无权进行此操作,未登录",
})
c.Abort()
return
2023-04-22 12:39:27 +00:00
}
if status.(int) == common.UserStatusDisabled {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "用户已被封禁",
})
c.Abort()
return
}
if role.(int) < minRole {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "无权进行此操作,权限不足",
})
c.Abort()
return
}
c.Set("username", username)
c.Set("role", role)
c.Set("id", id)
c.Next()
}
func UserAuth() func(c *gin.Context) {
return func(c *gin.Context) {
authHelper(c, common.RoleCommonUser)
}
}
func AdminAuth() func(c *gin.Context) {
return func(c *gin.Context) {
authHelper(c, common.RoleAdminUser)
}
}
func RootAuth() func(c *gin.Context) {
return func(c *gin.Context) {
authHelper(c, common.RoleRootUser)
}
}
2023-04-23 10:24:11 +00:00
func TokenAuth() func(c *gin.Context) {
2023-04-22 12:39:27 +00:00
return func(c *gin.Context) {
2023-04-23 10:24:11 +00:00
key := c.Request.Header.Get("Authorization")
parts := strings.Split(key, "-")
key = parts[0]
token, err := model.ValidateUserToken(key)
if err != nil {
2023-04-22 12:39:27 +00:00
c.JSON(http.StatusOK, gin.H{
2023-04-23 10:24:11 +00:00
"error": gin.H{
"message": err.Error(),
"type": "one_api_error",
},
2023-04-22 12:39:27 +00:00
})
c.Abort()
return
}
2023-04-23 10:24:11 +00:00
c.Set("id", token.UserId)
if len(parts) > 1 {
c.Set("channelId", parts[1])
2023-04-22 12:39:27 +00:00
}
c.Next()
}
}