Browse Source

完成权限领域开发

yjp 1 year ago
parent
commit
adceaeb65e

+ 11 - 11
convenient/domain/auth/auth.go

@@ -2,7 +2,6 @@ package auth
 
 import (
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/jwt_tools"
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/permission"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/permission_group"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/relations"
@@ -34,16 +33,17 @@ type Simple struct {
 
 	// JWT到期时间
 	JWTExpiredSec int64
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *Simple) bind(binder *binding.Binder) {
-	jwt_tools.SetJWTSecretKey(simple.JWTSecretKey)
-
-	(&permission.Simple{Schema: simple.Schema}).Bind(binder)
-	(&permission_group.Simple{Schema: simple.Schema}).Bind(binder)
-	(&role.Simple{Schema: simple.Schema}).Bind(binder)
-	(&user.Simple{Schema: simple.Schema, AESKey: simple.AESKey}).Bind(binder)
-	(&relations.Simple{Schema: simple.Schema}).Bind(binder)
+	(&permission.Simple{Schema: simple.Schema, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
+	(&permission_group.Simple{Schema: simple.Schema, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
+	(&role.Simple{Schema: simple.Schema, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
+	(&user.Simple{Schema: simple.Schema, AESKey: simple.AESKey, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
+	(&relations.Simple{Schema: simple.Schema, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
 
 	// 登录
 	binding.PostBind(binder, &binding.SimpleBindItem[map[string]any]{
@@ -89,7 +89,7 @@ func (simple *Simple) bind(binder *binding.Binder) {
 				return errResponse, err
 			}
 
-			token, err := jwt_tools.NewJWT(existUser.ID, simple.JWTExpiredSec)
+			token, err := jwt_tools.NewJWT(simple.JWTSecretKey, existUser.ID, simple.JWTExpiredSec)
 			if err != nil {
 				return errResponse, errors.New(err.Error())
 			}
@@ -131,7 +131,7 @@ func (simple *Simple) bind(binder *binding.Binder) {
 
 			return nil, nil
 		},
-	}, middlewares.Authentication())
+	}, simple.AuthMiddleware)
 
 	// Challenge
 	binding.PostBind(binder, &binding.SimpleBindItem[UserWithRoleInfo]{
@@ -200,7 +200,7 @@ func (simple *Simple) bind(binder *binding.Binder) {
 				RoleInfos: roleInfos,
 			}, nil
 		},
-	}, middlewares.Authentication())
+	}, simple.AuthMiddleware)
 }
 
 func BindAuth(binder *binding.Binder, simple *Simple) {

+ 2 - 8
convenient/domain/auth/jwt_tools/jwt_tools.go

@@ -6,13 +6,7 @@ import (
 	"time"
 )
 
-var secretKey string
-
-func SetJWTSecretKey(secretKey string) {
-	secretKey = secretKey
-}
-
-func NewJWT(userID string, expSec int64) (string, error) {
+func NewJWT(secretKey string, userID string, expSec int64) (string, error) {
 	token := jwt.New(jwt.SigningMethodHS256)
 	claims := make(jwt.MapClaims)
 
@@ -32,7 +26,7 @@ func NewJWT(userID string, expSec int64) (string, error) {
 	return tokenString, nil
 }
 
-func CheckJWT(tokenStr string) (bool, string, error) {
+func CheckJWT(secretKey string, tokenStr string) (bool, string, error) {
 	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
 		return []byte(secretKey), nil
 	})

+ 31 - 9
convenient/domain/auth/middlewares/middlewares.go

@@ -8,18 +8,14 @@ import (
 	"git.sxidc.com/go-framework/baize/framework/core/api/response"
 	"git.sxidc.com/go-framework/baize/framework/core/domain"
 	"git.sxidc.com/go-framework/baize/framework/core/infrastructure"
+	"git.sxidc.com/go-framework/baize/framework/core/infrastructure/database"
+	"git.sxidc.com/go-framework/baize/framework/core/infrastructure/database/sql"
 	"github.com/dgrijalva/jwt-go/request"
 	"github.com/pkg/errors"
 	"net/http"
 )
 
-var dbSchema string
-
-func SetDBSchema(schema string) {
-	dbSchema = schema
-}
-
-func Authentication() binding.Middleware {
+func Authentication(dbSchema string, jwtSecretKey string) binding.Middleware {
 	return func(c *api.Context, i *infrastructure.Infrastructure) {
 		respFunc := response.SendMapResponse
 
@@ -32,7 +28,7 @@ func Authentication() binding.Middleware {
 		}
 
 		// 校验token
-		valid, _, err := jwt_tools.CheckJWT(token)
+		valid, _, err := jwt_tools.CheckJWT(jwtSecretKey, token)
 		if err != nil {
 			respFunc(c, http.StatusUnauthorized, nil, errors.New(err.Error()))
 			c.Abort()
@@ -46,9 +42,35 @@ func Authentication() binding.Middleware {
 		}
 
 		// 获取用户信息
-		userTableName := domain.TableName(simple.Schema, &user.Entity{})
 		dbExecutor := i.DBExecutor()
 
+		// 查询用户
+		result, err := database.QueryOne(dbExecutor, &sql.QueryOneExecuteParams{
+			TableName:  domain.TableName(dbSchema, &user.Entity{}),
+			Conditions: sql.NewConditions().Equal(user.ColumnToken, token),
+		})
+		if err != nil {
+			if database.IsErrorDBRecordNotExist(err) {
+				respFunc(c, http.StatusUnauthorized, nil, errors.New("token对应的用户不存在"))
+			} else {
+				respFunc(c, http.StatusUnauthorized, nil, errors.New(err.Error()))
+			}
+
+			c.Abort()
+			return
+		}
+
+		userInfo := new(user.Info)
+		err = sql.ParseSqlResult(result, userInfo)
+		if err != nil {
+			respFunc(c, http.StatusUnauthorized, nil, errors.New(err.Error()))
+			c.Abort()
+			return
+		}
+
+		// 设置用户上下文
+		c.SetUserInfo(userInfo)
+
 		c.Next()
 	}
 }

+ 4 - 6
convenient/domain/auth/permission/api.go

@@ -1,7 +1,6 @@
 package permission
 
 import (
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/entity_crud"
 	"git.sxidc.com/go-framework/baize/framework/binding"
 )
@@ -10,6 +9,9 @@ import (
 type Simple struct {
 	// schema
 	Schema string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *Simple) Bind(binder *binding.Binder) {
@@ -21,9 +23,5 @@ func (simple *Simple) Bind(binder *binding.Binder) {
 		UpdateJsonBody:     &UpdatePermissionJsonBody{},
 		QueryQueryParams:   &GetPermissionsQueryParams{},
 		GetByIDQueryParams: &GetPermissionQueryParams{},
-	}, entity_crud.WithCreateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithDeleteMiddlewares(middlewares.Authentication()),
-		entity_crud.WithUpdateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithQueryMiddlewares[Info](middlewares.Authentication()),
-		entity_crud.WithGetByIDMiddlewares[Info](middlewares.Authentication()))
+	}, entity_crud.WithGlobalMiddlewares(simple.AuthMiddleware))
 }

+ 4 - 6
convenient/domain/auth/permission_group/api.go

@@ -1,7 +1,6 @@
 package permission_group
 
 import (
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/entity_crud"
 	"git.sxidc.com/go-framework/baize/framework/binding"
 )
@@ -10,6 +9,9 @@ import (
 type Simple struct {
 	// schema
 	Schema string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *Simple) Bind(binder *binding.Binder) {
@@ -21,9 +23,5 @@ func (simple *Simple) Bind(binder *binding.Binder) {
 		UpdateJsonBody:     &UpdatePermissionGroupJsonBody{},
 		QueryQueryParams:   &GetPermissionGroupsQueryParams{},
 		GetByIDQueryParams: &GetPermissionGroupQueryParams{},
-	}, entity_crud.WithCreateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithDeleteMiddlewares(middlewares.Authentication()),
-		entity_crud.WithUpdateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithQueryMiddlewares[Info](middlewares.Authentication()),
-		entity_crud.WithGetByIDMiddlewares[Info](middlewares.Authentication()))
+	}, entity_crud.WithGlobalMiddlewares(simple.AuthMiddleware))
 }

+ 4 - 5
convenient/domain/auth/relations/permission_group_and_permission.go

@@ -1,7 +1,6 @@
 package relations
 
 import (
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/permission"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/permission_group"
 	"git.sxidc.com/go-framework/baize/convenient/relation/many2many"
@@ -12,6 +11,9 @@ import (
 type SimplePermissionGroupAndPermission struct {
 	// schema
 	Schema string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *SimplePermissionGroupAndPermission) Bind(binder *binding.Binder) {
@@ -23,8 +25,5 @@ func (simple *SimplePermissionGroupAndPermission) Bind(binder *binding.Binder) {
 		LeftQueryQueryParams:  &permission_group.GetPermissionsOfPermissionGroupQueryParams{},
 		RightUpdateJsonBody:   &permission.UpdatePermissionGroupsOfPermissionJsonBody{},
 		RightQueryQueryParams: &permission.GetPermissionGroupsOfPermissionQueryParams{},
-	}, many2many.WithLeftUpdateMiddlewares(middlewares.Authentication()),
-		many2many.WithLeftQueryMiddlewares(middlewares.Authentication()),
-		many2many.WithRightUpdateMiddlewares(middlewares.Authentication()),
-		many2many.WithRightQueryMiddlewares(middlewares.Authentication()))
+	}, many2many.WithGlobalMiddlewares(simple.AuthMiddleware))
 }

+ 6 - 3
convenient/domain/auth/relations/relations.go

@@ -8,10 +8,13 @@ import (
 type Simple struct {
 	// schema
 	Schema string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *Simple) Bind(binder *binding.Binder) {
-	(&SimplePermissionGroupAndPermission{Schema: simple.Schema}).Bind(binder)
-	(&SimpleRoleAndPermission{Schema: simple.Schema}).Bind(binder)
-	(&SimpleUserAndRole{Schema: simple.Schema}).Bind(binder)
+	(&SimplePermissionGroupAndPermission{Schema: simple.Schema, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
+	(&SimpleRoleAndPermission{Schema: simple.Schema, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
+	(&SimpleUserAndRole{Schema: simple.Schema, AuthMiddleware: simple.AuthMiddleware}).Bind(binder)
 }

+ 4 - 5
convenient/domain/auth/relations/role_and_permission.go

@@ -1,7 +1,6 @@
 package relations
 
 import (
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/permission"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/role"
 	"git.sxidc.com/go-framework/baize/convenient/relation/many2many"
@@ -12,6 +11,9 @@ import (
 type SimpleRoleAndPermission struct {
 	// schema
 	Schema string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *SimpleRoleAndPermission) Bind(binder *binding.Binder) {
@@ -23,8 +25,5 @@ func (simple *SimpleRoleAndPermission) Bind(binder *binding.Binder) {
 		LeftQueryQueryParams:  &role.GetPermissionsOfRoleQueryParams{},
 		RightUpdateJsonBody:   &permission.UpdateRolesOfPermissionJsonBody{},
 		RightQueryQueryParams: &permission.GetRolesOfPermissionQueryParams{},
-	}, many2many.WithLeftUpdateMiddlewares(middlewares.Authentication()),
-		many2many.WithLeftQueryMiddlewares(middlewares.Authentication()),
-		many2many.WithRightUpdateMiddlewares(middlewares.Authentication()),
-		many2many.WithRightQueryMiddlewares(middlewares.Authentication()))
+	}, many2many.WithGlobalMiddlewares(simple.AuthMiddleware))
 }

+ 4 - 5
convenient/domain/auth/relations/role_and_user.go

@@ -1,7 +1,6 @@
 package relations
 
 import (
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/role"
 	"git.sxidc.com/go-framework/baize/convenient/domain/auth/user"
 	"git.sxidc.com/go-framework/baize/convenient/relation/many2many"
@@ -12,6 +11,9 @@ import (
 type SimpleUserAndRole struct {
 	// schema
 	Schema string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *SimpleUserAndRole) Bind(binder *binding.Binder) {
@@ -23,8 +25,5 @@ func (simple *SimpleUserAndRole) Bind(binder *binding.Binder) {
 		LeftQueryQueryParams:  &user.GetRolesOfUserQueryParams{},
 		RightUpdateJsonBody:   &role.UpdateUsersOfRoleJsonBody{},
 		RightQueryQueryParams: &role.GetUsersOfRoleQueryParams{},
-	}, many2many.WithLeftUpdateMiddlewares(middlewares.Authentication()),
-		many2many.WithLeftQueryMiddlewares(middlewares.Authentication()),
-		many2many.WithRightUpdateMiddlewares(middlewares.Authentication()),
-		many2many.WithRightQueryMiddlewares(middlewares.Authentication()))
+	}, many2many.WithGlobalMiddlewares(simple.AuthMiddleware))
 }

+ 4 - 6
convenient/domain/auth/role/api.go

@@ -1,7 +1,6 @@
 package role
 
 import (
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/entity_crud"
 	"git.sxidc.com/go-framework/baize/framework/binding"
 )
@@ -10,6 +9,9 @@ import (
 type Simple struct {
 	// schema
 	Schema string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *Simple) Bind(binder *binding.Binder) {
@@ -21,9 +23,5 @@ func (simple *Simple) Bind(binder *binding.Binder) {
 		UpdateJsonBody:     &UpdateRoleJsonBody{},
 		QueryQueryParams:   &GetRolesQueryParams{},
 		GetByIDQueryParams: &GetRoleQueryParams{},
-	}, entity_crud.WithCreateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithDeleteMiddlewares(middlewares.Authentication()),
-		entity_crud.WithUpdateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithQueryMiddlewares[Info](middlewares.Authentication()),
-		entity_crud.WithGetByIDMiddlewares[Info](middlewares.Authentication()))
+	}, entity_crud.WithGlobalMiddlewares(simple.AuthMiddleware))
 }

+ 4 - 6
convenient/domain/auth/user/api.go

@@ -1,7 +1,6 @@
 package user
 
 import (
-	"git.sxidc.com/go-framework/baize/convenient/domain/auth/middlewares"
 	"git.sxidc.com/go-framework/baize/convenient/entity_crud"
 	"git.sxidc.com/go-framework/baize/framework/binding"
 	"git.sxidc.com/go-framework/baize/framework/core/api/response"
@@ -23,6 +22,9 @@ type Simple struct {
 
 	// AES加密用到的Key
 	AESKey string
+
+	// 鉴权中间件
+	AuthMiddleware binding.Middleware
 }
 
 func (simple *Simple) Bind(binder *binding.Binder) {
@@ -34,11 +36,7 @@ func (simple *Simple) Bind(binder *binding.Binder) {
 		UpdateJsonBody:     &UpdateUserJsonBody{},
 		QueryQueryParams:   &GetUsersQueryParams{},
 		GetByIDQueryParams: &GetUserQueryParams{},
-	}, entity_crud.WithCreateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithDeleteMiddlewares(middlewares.Authentication()),
-		entity_crud.WithUpdateMiddlewares(middlewares.Authentication()),
-		entity_crud.WithQueryMiddlewares[Info](middlewares.Authentication()),
-		entity_crud.WithGetByIDMiddlewares[Info](middlewares.Authentication()),
+	}, entity_crud.WithGlobalMiddlewares(simple.AuthMiddleware),
 		entity_crud.WithCreateCallbacks(&entity_crud.CreateCallbacks{
 			Before: func(e entity.Entity, prepared map[string]any, i *infrastructure.Infrastructure, tx database.Executor) error {
 				userEntity, err := domain.ToConcrete[*Entity](e)

+ 11 - 3
framework/core/api/context.go

@@ -45,7 +45,7 @@ func (c *Context) GetFileHeaderBytes(fileHeader *multipart.FileHeader) (string,
 }
 
 func (c *Context) GetHeaders() map[string]string {
-	headers := make(map[string]string, 0)
+	headers := make(map[string]string)
 
 	for key, values := range c.Request.Header {
 		headers[key] = strings.Join(values, ",")
@@ -268,7 +268,7 @@ func (c *Context) GetPathParams() *PathPrams {
 }
 
 func (c *Context) getAllQueryParams() map[string]string {
-	queryParams := make(map[string]string, 0)
+	queryParams := make(map[string]string)
 
 	for key, values := range c.Request.URL.Query() {
 		queryParams[key] = strings.Join(values, ",")
@@ -278,7 +278,7 @@ func (c *Context) getAllQueryParams() map[string]string {
 }
 
 func (c *Context) getAllPathParams() map[string]string {
-	pathParams := make(map[string]string, 0)
+	pathParams := make(map[string]string)
 
 	for _, params := range c.Params {
 		pathParams[params.Key] = params.Value
@@ -328,6 +328,14 @@ type UserInfo interface {
 	GetName() string
 }
 
+func (c *Context) SetTenantInfo(tenantInfo TenantInfo) {
+	c.Set(tenantInfoKey, tenantInfo)
+}
+
+func (c *Context) SetUserInfo(userInfo UserInfo) {
+	c.Set(userInfoKey, userInfo)
+}
+
 func (c *Context) GetTenantInfo() TenantInfo {
 	tenantInfo, exist := c.Get(tenantInfoKey)
 	if !exist {

+ 1 - 1
framework/core/infrastructure/database/sql/sql_template.go

@@ -71,7 +71,7 @@ func (params InsertBatchExecuteParams) Map() (map[string]any, error) {
 			return nil, errors.New("列数不匹配,保证每个TableRow的Add数量一致")
 		}
 
-		columnAndValueMap := make(map[string]any, 0)
+		columnAndValueMap := make(map[string]any)
 
 		for _, cv := range tableRow.columnValues {
 			columnAndValueMap[cv.column] = cv.value