wireguard-dashboard/http/middleware/authorization.go
2024-07-05 14:41:35 +08:00

58 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"github.com/gin-gonic/gin"
"strings"
"wireguard-ui/component"
"wireguard-ui/global/constant"
"wireguard-ui/http/response"
"wireguard-ui/service"
"wireguard-ui/utils"
)
// Authorization
// @description: 授权中间件
// @return gin.HandlerFunc
func Authorization() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" || !strings.HasPrefix(token, "Bearer ") {
response.R(c).AuthorizationFailed("未登陆")
c.Abort()
return
}
userClaims, err := component.JWT().ParseToken(token)
if err != nil {
response.R(c).AuthorizationFailed("未登陆")
c.Abort()
return
}
// 如果token的颁发者与请求的站点不一致则直接给它狗日的丢出去
if userClaims.Issuer != utils.WebSite().GetHost(c.Request.Header.Get("Referer")) {
response.R(c).AuthorizationFailed("未登陆")
c.Abort()
return
}
// 查询用户
user, err := service.User().GetUserById(userClaims.ID)
if err != nil {
response.R(c).FailedWithError("用户不存在")
c.Abort()
return
}
if user.Status != constant.Enabled {
response.R(c).FailedWithError("用户状态异常,请联系管理员处理!")
c.Abort()
return
}
// 将用户信息放入上下文
c.Set("user", &user)
c.Next()
}
}