wireguard-dashboard/middleware/authorization.go

57 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-03-07 11:03:46 +08:00
package middleware
import (
"github.com/gin-gonic/gin"
"strings"
2024-03-07 17:32:38 +08:00
"wireguard-dashboard/component"
2024-03-07 11:03:46 +08:00
"wireguard-dashboard/constant"
"wireguard-dashboard/repository"
"wireguard-dashboard/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 ") {
utils.GinResponse(c).AuthorizationFailed()
c.Abort()
return
}
2024-03-07 17:32:38 +08:00
userClaims, err := component.JWT().ParseToken(token)
2024-03-07 11:03:46 +08:00
if err != nil {
utils.GinResponse(c).AuthorizationFailed()
c.Abort()
return
}
// 如果token的颁发者与请求的站点不一致则直接给它狗日的丢出去
if userClaims.Issuer != utils.GetHost(c.Request.Header.Get("Referer")) {
utils.GinResponse(c).AuthorizationFailed()
c.Abort()
return
}
2024-03-07 11:03:46 +08:00
// 查询用户
user, err := repository.User().GetUserById(userClaims.ID)
if err != nil {
utils.GinResponse(c).FailedWithMsg("用户不存在")
c.Abort()
return
}
if user.Status != constant.Normal {
utils.GinResponse(c).FailedWithMsg("用户状态异常,请联系管理员处理!")
c.Abort()
return
}
// 将用户信息放入上下文
c.Set("user", user)
c.Next()
}
}