diff --git a/component/jwt.go b/component/jwt.go index 99e84d6..5629e1e 100644 --- a/component/jwt.go +++ b/component/jwt.go @@ -36,11 +36,19 @@ func JWT() JwtComponent { // @return token // @return expireTime // @return err -func (JwtComponent) GenerateToken(userId, secret string) (token string, expireTime *jwt.NumericDate, err error) { - timeNow := time.Now().Local() - expireTime = jwt.NewNumericDate(timeNow.Add(7 * time.Hour)) - notBefore := jwt.NewNumericDate(timeNow) - issuedAt := jwt.NewNumericDate(timeNow) +func (JwtComponent) GenerateToken(userId, secret string, times ...time.Time) (token string, expireTime *jwt.NumericDate, err error) { + var notBefore, issuedAt *jwt.NumericDate + if len(times) != 0 { + expireTime = jwt.NewNumericDate(times[0]) + notBefore = jwt.NewNumericDate(times[1]) + issuedAt = jwt.NewNumericDate(times[1]) + } else { + timeNow := time.Now().Local() + expireTime = jwt.NewNumericDate(timeNow.Add(7 * time.Hour)) + notBefore = jwt.NewNumericDate(timeNow) + issuedAt = jwt.NewNumericDate(timeNow) + } + claims := JwtComponent{ ID: userId, RegisteredClaims: jwt.RegisteredClaims{ diff --git a/http/middleware/authorization.go b/http/middleware/authorization.go index 46a60d4..a42bdb7 100644 --- a/http/middleware/authorization.go +++ b/http/middleware/authorization.go @@ -1,8 +1,11 @@ package middleware import ( + "fmt" "github.com/gin-gonic/gin" + "github.com/google/uuid" "strings" + "time" "wireguard-ui/component" "wireguard-ui/global/constant" "wireguard-ui/http/response" @@ -59,6 +62,18 @@ func Authorization() gin.HandlerFunc { // 将用户信息放入上下文 c.Set("user", &user) + + // 生成一个新token + secret := component.JWT().GenerateSecret(user.Password, uuid.NewString(), time.Now().Local().String()) + tokenStr, _, err := component.JWT().GenerateToken(user.Id, secret, userClaims.ExpiresAt.Time, userClaims.IssuedAt.Time) + 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) c.Next() } }