Browse Source

2023-12-28

zoie 1 year ago
parent
commit
0d9efa6a95
7 changed files with 178 additions and 18 deletions
  1. 10 0
      model/dept.go
  2. 5 3
      model/user.go
  3. 115 0
      pkg/jwtauth/beegouser/beegouser.go
  4. 22 10
      pkg/jwtauth/jwtauth.go
  5. 18 0
      pkg/jwtauth/user/user.go
  6. 7 4
      pkg/response/model.go
  7. 1 1
      pkg/response/return.go

+ 10 - 0
model/dept.go

@@ -0,0 +1,10 @@
+package model
+
+
+type Dept struct {
+	ParentId int       `json:"parentId" gorm:""`                               //上级部门
+	DeptPath string    `json:"deptPath" gorm:"size:255;" swaggerignore:"true"` //
+	DeptName string    `json:"deptName"  gorm:"size:128;"`                     //部门名称
+	Sort     int       `json:"sort" gorm:"size:4;"`                            //排序
+	Status   int       `json:"status" gorm:"size:4;"`                          //状态 1-停用 2-正常
+}

+ 5 - 3
model/user.go

@@ -9,7 +9,7 @@ type User struct {
 	RoleId   int    `json:"roleId" gorm:"comment:角色ID"`                   // 角色id
 	Salt     string `json:"-" gorm:"size:255;comment:加盐"`
 	DeptId   int    `json:"deptId" gorm:"comment:部门"`                             // 部门id
-	PostId   int    `json:"PostId" gorm:"comment:岗位"`                             // 岗位id
+	PostId   int    `json:"postId" gorm:"comment:岗位"`                             // 岗位id
 	Remark   string `json:"remark" gorm:"size:255;comment:备注"`                    // 备注
 	Status   string `json:"status" gorm:"size:4;not null;default:'2';comment:状态"` // 1-停用 2-正常
 }
@@ -18,8 +18,10 @@ type UserInfo struct {
 	Uuid      string `json:"uuid"`      // 用户uuid
 	UserId    int    `json:"userId"`    // 用户id
 	RoleId    int    `json:"roleId"`    // 角色id
+	DeptId    int    `json:"deptId"`    // 部门id
 	UserName  string `json:"userName"`  // 用户名称
-	RoleName  string `json:"roleName"`  //  角色名称
-	RoleKey   string `json:"roleKey"`   //  角色编码
+	RoleName  string `json:"roleName"`  // 角色名称
+	DeptName  string `json:"deptName"`  // 部门名称
+	RoleKey   string `json:"roleKey"`   // 角色编码
 	DataScope int    `json:"dataScope"` // 数据访问范围 1-全部数据权限 3-本机构数据权限  4-本机构及以下数据权限 5-仅本人数据权限
 }

+ 115 - 0
pkg/jwtauth/beegouser/beegouser.go

@@ -0,0 +1,115 @@
+package beegouser
+
+import (
+	"fmt"
+	"github.com/beego/beego/v2/server/web/context"
+	"gogs.baozhida.cn/zoie/OAuth-core/pkg"
+	jwt "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth"
+)
+
+func ExtractClaims(c *context.Context) jwt.MapClaims {
+	claims := c.Input.GetData(jwt.JwtPayloadKey)
+	if claims == nil {
+		return jwt.MapClaims{}
+	}
+	return claims.(jwt.MapClaims)
+}
+
+func Get(c *context.Context, key string) interface{} {
+	data := ExtractClaims(c)
+	if data[key] != nil {
+		return data[key]
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " Get 缺少 " + key)
+	return nil
+}
+func GetUUID(c *context.Context) string {
+	data := ExtractClaims(c)
+	if data["uuid"] != nil {
+		return (data["uuid"]).(string)
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUUID 缺少 uuid")
+	return ""
+}
+
+func GetUserId(c *context.Context) int {
+	data := ExtractClaims(c)
+	if data["identity"] != nil {
+		return int((data["identity"]).(float64))
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserId 缺少 identity")
+	return 0
+}
+
+func GetUserIdStr(c *context.Context) string {
+	data := ExtractClaims(c)
+	if data["identity"] != nil {
+		return pkg.Int64ToString(int64((data["identity"]).(float64)))
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserIdStr 缺少 identity")
+	return ""
+}
+
+func GetUserName(c *context.Context) string {
+	data := ExtractClaims(c)
+	if data["username"] != nil {
+		return (data["username"]).(string)
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserName 缺少 username")
+	return ""
+}
+
+func GetRoleName(c *context.Context) string {
+	data := ExtractClaims(c)
+	if data["roleName"] != nil {
+		return (data["roleName"]).(string)
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetRoleName 缺少 roleName")
+	return ""
+}
+
+func GetRoleKey(c *context.Context) string {
+	data := ExtractClaims(c)
+	if data["roleKey"] != nil {
+		return (data["roleKey"]).(string)
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetRoleKey 缺少 roleKey")
+	return ""
+}
+
+func GetRoleId(c *context.Context) int {
+	data := ExtractClaims(c)
+	if data["roleId"] != nil {
+		i := int((data["roleId"]).(float64))
+		return i
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetRoleId 缺少 roleId")
+	return 0
+}
+
+func GetDataScope(c *context.Context) int {
+	data := ExtractClaims(c)
+	if data["dataScope"] != nil {
+		i := int((data["dataScope"]).(float64))
+		return i
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetDataScope 缺少 dataScope")
+	return 0
+}
+
+func GetDeptId(c *context.Context) int {
+	data := ExtractClaims(c)
+	if data["deptId"] != nil {
+		return int((data["deptId"]).(float64))
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetDeptId 缺少 deptId")
+	return 0
+}
+func GetDeptName(c *context.Context) string {
+	data := ExtractClaims(c)
+	if data["deptName"] != nil {
+		return (data["deptName"]).(string)
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetDeptName 缺少 deptName")
+	return ""
+}

+ 22 - 10
pkg/jwtauth/jwtauth.go

@@ -84,6 +84,9 @@ type GinJWTMiddleware struct {
 
 	// roleId
 	RoleIdKey string
+	//deptId
+	DeptIdKey   string
+	DeptNameKey string
 
 	RoleKey string
 
@@ -166,11 +169,13 @@ var (
 
 	ErrAccountDeactivated = errors.New("账号已停用")
 
+	ErrSingleLogin = errors.New("您的账号已在其他地方登录,请重新登录或退出")
+
 	// ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
 	ErrFailedTokenCreation = errors.New("failed to create JWT Token")
 
 	// ErrExpiredToken indicates JWT token has expired. Can't refresh.
-	ErrExpiredToken = errors.New("token is expired")
+	ErrExpiredToken = errors.New("Token is expired")
 
 	// ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set
 	ErrEmptyAuthHeader = errors.New("auth header is empty")
@@ -227,6 +232,10 @@ var (
 	RoleNameKey = "roleName"
 	// 单一登录标识
 	SingleKey = "single"
+
+	// DeptIdKey 部门  Old
+	DeptIdKey   = "deptId"
+	DeptNameKey = "deptName"
 )
 
 // New for check error with GinJWTMiddleware
@@ -385,8 +394,13 @@ func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
 
 	claims, err := mw.GetClaimsFromJWT(c)
 	if err != nil {
-		mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
-		return
+		if err.Error() == ErrExpiredToken.Error() {
+			mw.unauthorized(c, 6401, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
+			return
+		} else {
+			mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
+			return
+		}
 	}
 
 	if claims["exp"] == nil {
@@ -418,11 +432,12 @@ func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
 	if claims["single"].(bool) {
 		token, err := mw.GetNewestToken(c, int64(claims["identity"].(float64)))
 		if err != nil && errors.Is(err, redis.Nil) {
-			mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
+			// 没有获取到最新的token
+			mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrEmptyQueryToken, c))
 			return
 		}
 		if token != GetToken(c) {
-			mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
+			mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrSingleLogin, c))
 			return
 		}
 	}
@@ -518,9 +533,6 @@ func (mw *GinJWTMiddleware) signedString(token *jwt.Token) (string, error) {
 	return tokenString, err
 }
 
-// RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh.
-// Shall be put under an endpoint that is using the GinJWTMiddleware.
-// Reply will be of the form {"token": "TOKEN"}.
 func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) {
 	tokenString, expire, err := mw.RefreshToken(c)
 	if err != nil {
@@ -570,7 +582,7 @@ func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, err
 	}
 
 	if claims["single"].(bool) {
-		_ = mw.SaveNewestToken(c, int64(claims["identity"].(int)), tokenString, int64(mw.Timeout)/3600)
+		_ = mw.SaveNewestToken(c, int64(claims["identity"].(float64)), tokenString, int64(mw.Timeout)/3600)
 	}
 
 	return tokenString, expire, nil
@@ -731,8 +743,8 @@ func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message strin
 	if !mw.DisabledAbort {
 		c.Abort()
 	}
-
 	mw.Unauthorized(c, code, message)
+
 }
 
 // ExtractClaims help to extract the JWT claims

+ 18 - 0
pkg/jwtauth/user/user.go

@@ -97,3 +97,21 @@ func GetDataScope(c *gin.Context) int {
 	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetDataScope 缺少 dataScope")
 	return 0
 }
+
+func GetDeptId(c *gin.Context) int {
+	data := ExtractClaims(c)
+	if data["deptId"] != nil {
+		return int((data["deptId"]).(float64))
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetDeptId 缺少 deptId")
+	return 0
+}
+
+func GetDeptName(c *gin.Context) string {
+	data := ExtractClaims(c)
+	if data["deptName"] != nil {
+		return (data["deptName"]).(string)
+	}
+	fmt.Println(pkg.GetCurrentTimeStr() + " [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetDeptName 缺少 deptName")
+	return ""
+}

+ 7 - 4
pkg/response/model.go

@@ -1,4 +1,5 @@
 package response
+
 // 数据集
 type Response struct {
 	RequestId string `protobuf:"bytes,1,opt,name=requestId,proto3" json:"requestId,omitempty"`
@@ -13,13 +14,15 @@ type response struct {
 }
 
 type Page struct {
-	Count     int `json:"count"`     //总数
-	PageIndex int `json:"pageIndex"` //页码
-	PageSize  int `json:"pageSize"`  //页条数
+	Count    int `json:"count"`    //总数
+	Page     int `json:"page"`     //页码
+	PageSize int `json:"pageSize"` //页条数
 }
 
 type page struct {
-	Page
+	Count    int `json:"count"`    //总数
+	Page     int `json:"page"`     //页码
+	PageSize int `json:"pageSize"` //页条数
 	List interface{} `json:"list"`
 }
 

+ 1 - 1
pkg/response/return.go

@@ -46,7 +46,7 @@ func PageOK(c *gin.Context, result interface{}, count int, pageIndex int, pageSi
 	var res page
 	res.List = result
 	res.Count = count
-	res.PageIndex = pageIndex
+	res.Page = pageIndex
 	res.PageSize = pageSize
 	OK(c, res, msg)
 }