wireguard-dashboard/http/middleware/authorization.go

84 lines
2.0 KiB
Go
Raw Normal View History

2024-07-05 14:41:35 +08:00
package middleware
import (
2024-07-12 16:32:31 +08:00
"fmt"
2024-07-05 14:41:35 +08:00
"github.com/gin-gonic/gin"
2024-07-12 16:32:31 +08:00
"github.com/google/uuid"
2024-07-05 14:41:35 +08:00
"strings"
2024-07-12 16:32:31 +08:00
"time"
2024-07-05 14:41:35 +08:00
"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
}
2024-07-12 10:11:37 +08:00
hashPassword := c.Request.Header.Get("X-TOKEN")
if hashPassword == "" {
response.R(c).AuthorizationFailed("未登陆")
c.Abort()
return
}
userClaims, err := component.JWT().ParseToken(token, hashPassword)
2024-07-05 14:41:35 +08:00
if err != nil {
response.R(c).AuthorizationFailed("未登陆")
c.Abort()
return
}
2024-07-11 16:21:08 +08:00
// 如果token的颁发者与请求的站点不一致那么就给它抬出去
2024-07-05 14:41:35 +08:00
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)
2024-07-12 16:32:31 +08:00
2024-08-06 14:49:05 +08:00
if c.Request.RequestURI == "/api/user/logout" {
c.Next()
}
2024-07-12 16:32:31 +08:00
// 生成一个新token
secret := component.JWT().GenerateSecret(user.Password, uuid.NewString(), time.Now().Local().String())
2024-07-12 17:18:04 +08:00
tokenStr, _, err := component.JWT().GenerateToken(user.Id, secret, userClaims.ExpiresAt.Time, time.Now().Local())
2024-07-12 16:32:31 +08:00
if err != nil {
response.R(c).AuthorizationFailed("校验失败")
c.Abort()
return
}
c.Writer.Header().Set("Authorization", fmt.Sprintf("Bearer %s", tokenStr))
c.Writer.Header().Set("X-TOKEN", secret)
2024-07-05 14:41:35 +08:00
c.Next()
}
}