This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
type UserContextInfo struct {
|
||||
UserID uint
|
||||
UserType int
|
||||
Username string
|
||||
ShopID uint
|
||||
EnterpriseID uint
|
||||
CustomerID uint
|
||||
@@ -23,11 +24,15 @@ type UserContextInfo struct {
|
||||
// SetUserContext 将用户信息设置到 context 中
|
||||
// 在 Auth 中间件认证成功后调用
|
||||
func SetUserContext(ctx context.Context, info *UserContextInfo) context.Context {
|
||||
if info == nil {
|
||||
return ctx
|
||||
}
|
||||
ctx = context.WithValue(ctx, constants.ContextKeyUserID, info.UserID)
|
||||
ctx = context.WithValue(ctx, constants.ContextKeyUserType, info.UserType)
|
||||
ctx = context.WithValue(ctx, constants.ContextKeyShopID, info.ShopID)
|
||||
ctx = context.WithValue(ctx, constants.ContextKeyEnterpriseID, info.EnterpriseID)
|
||||
ctx = context.WithValue(ctx, constants.ContextKeyCustomerID, info.CustomerID)
|
||||
ctx = context.WithValue(ctx, constants.ContextKeyUserInfo, info)
|
||||
// SubordinateShopIDs: nil 表示不限制,空切片表示无权限
|
||||
if info.SubordinateShopIDs != nil {
|
||||
ctx = context.WithValue(ctx, constants.ContextKeySubordinateShopIDs, info.SubordinateShopIDs)
|
||||
@@ -59,6 +64,18 @@ func GetUserTypeFromContext(ctx context.Context) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
// GetUsernameFromContext 从 context 中提取用户名。
|
||||
// 如果未设置,返回空字符串。
|
||||
func GetUsernameFromContext(ctx context.Context) string {
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
if info, ok := ctx.Value(constants.ContextKeyUserInfo).(*UserContextInfo); ok && info != nil {
|
||||
return info.Username
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetShopIDFromContext 从 context 中提取店铺 ID
|
||||
// 如果未设置,返回 0
|
||||
func GetShopIDFromContext(ctx context.Context) uint {
|
||||
@@ -157,12 +174,16 @@ func GetRequestMethodFromContext(ctx context.Context) *string {
|
||||
// SetUserToFiberContext 将用户信息设置到 Fiber context 的 Locals 中
|
||||
// 同时也设置到标准 context 中,便于 GORM 查询使用
|
||||
func SetUserToFiberContext(c *fiber.Ctx, info *UserContextInfo) {
|
||||
if info == nil {
|
||||
return
|
||||
}
|
||||
// 设置到 Fiber Locals
|
||||
c.Locals(constants.ContextKeyUserID, info.UserID)
|
||||
c.Locals(constants.ContextKeyUserType, info.UserType)
|
||||
c.Locals(constants.ContextKeyShopID, info.ShopID)
|
||||
c.Locals(constants.ContextKeyEnterpriseID, info.EnterpriseID)
|
||||
c.Locals(constants.ContextKeyCustomerID, info.CustomerID)
|
||||
c.Locals(constants.ContextKeyUserInfo, info)
|
||||
if info.SubordinateShopIDs != nil {
|
||||
c.Locals(constants.ContextKeySubordinateShopIDs, info.SubordinateShopIDs)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user