optimize get user info logic in JWT process

pull/199/head
Michael Li 2 years ago
parent e0d0e254c6
commit 9225485317
No known key found for this signature in database

@ -0,0 +1,24 @@
// Copyright 2023 ROC. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package chain
import (
"sync"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/dao"
)
var (
_ums core.UserManageService
_onceUms sync.Once
)
func userManageService() core.UserManageService {
_onceUms.Do(func() {
_ums = dao.DataService()
})
return _ums
}

@ -10,14 +10,12 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/errcode"
) )
func JWT() gin.HandlerFunc { func JWT() gin.HandlerFunc {
// TODO: optimize get user from a simple service that provide fetch a user info interface. ums := userManageService()
db := conf.MustGormDB()
return func(c *gin.Context) { return func(c *gin.Context) {
var ( var (
token string token string
@ -55,13 +53,12 @@ func JWT() gin.HandlerFunc {
c.Set("USERNAME", claims.Username) c.Set("USERNAME", claims.Username)
// 加载用户信息 // 加载用户信息
user := &core.User{ user, err := ums.GetUserByID(claims.UID)
Model: &core.Model{ if err == nil {
ID: claims.UID, c.Set("USER", user)
}, } else {
ecode = errcode.UnauthorizedAuthNotExist
} }
user, _ = user.Get(db)
c.Set("USER", user)
// 强制下线机制 // 强制下线机制
if (conf.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer { if (conf.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer {
@ -82,8 +79,7 @@ func JWT() gin.HandlerFunc {
} }
func JwtLoose() gin.HandlerFunc { func JwtLoose() gin.HandlerFunc {
// TODO: optimize get user from a simple service that provide fetch a user info interface. ums := userManageService()
db := conf.MustGormDB()
return func(c *gin.Context) { return func(c *gin.Context) {
token, exist := c.GetQuery("token") token, exist := c.GetQuery("token")
if !exist { if !exist {
@ -101,12 +97,7 @@ func JwtLoose() gin.HandlerFunc {
c.Set("UID", claims.UID) c.Set("UID", claims.UID)
c.Set("USERNAME", claims.Username) c.Set("USERNAME", claims.Username)
// 加载用户信息 // 加载用户信息
user := &core.User{ user, err := ums.GetUserByID(claims.UID)
Model: &core.Model{
ID: claims.UID,
},
}
user, err := user.Get(db)
if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer { if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer {
c.Set("USER", user) c.Set("USER", user)
} }

Loading…
Cancel
Save