feat: 添加用户的role信息
This commit is contained in:
32
web/user.go
32
web/user.go
@@ -14,6 +14,7 @@ type UserInfo struct {
|
||||
FromIP string `json:"from_ip"`
|
||||
Province string `json:"province"`
|
||||
City string `json:"city"`
|
||||
Role int `json:"role"`
|
||||
}
|
||||
|
||||
// contextKey is the type for context keys to prevent collisions
|
||||
@@ -28,6 +29,7 @@ const (
|
||||
FromIPKey contextKey = "fromIP"
|
||||
ProvinceKey contextKey = "province"
|
||||
CityKey contextKey = "city"
|
||||
RoleKey contextKey = "role"
|
||||
)
|
||||
|
||||
// GetUserID returns user ID from context
|
||||
@@ -163,6 +165,25 @@ func SetCity(ctx context.Context, city string) context.Context {
|
||||
return context.WithValue(ctx, CityKey, city)
|
||||
}
|
||||
|
||||
// GetRole returns role from context
|
||||
func GetRole(ctx context.Context) int {
|
||||
if ctx == nil {
|
||||
return 0
|
||||
}
|
||||
if val, ok := ctx.Value(RoleKey).(int); ok {
|
||||
return val
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// SetRole sets role in context and returns new context
|
||||
func SetRole(ctx context.Context, role int) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithValue(ctx, RoleKey, role)
|
||||
}
|
||||
|
||||
// FromContext builds UserInfo from individual context fields
|
||||
// Returns nil if no fields are found
|
||||
func FromContext(ctx context.Context) *UserInfo {
|
||||
@@ -200,6 +221,10 @@ func FromContext(ctx context.Context) *UserInfo {
|
||||
info.City = city
|
||||
hasData = true
|
||||
}
|
||||
if role := GetRole(ctx); role != 0 {
|
||||
info.Role = role
|
||||
hasData = true
|
||||
}
|
||||
|
||||
if !hasData {
|
||||
return nil
|
||||
@@ -223,6 +248,7 @@ func ToContext(ctx context.Context, userInfo *UserInfo) context.Context {
|
||||
ctx = SetFromIP(ctx, userInfo.FromIP)
|
||||
ctx = SetProvince(ctx, userInfo.Province)
|
||||
ctx = SetCity(ctx, userInfo.City)
|
||||
ctx = SetRole(ctx, userInfo.Role)
|
||||
|
||||
return ctx
|
||||
}
|
||||
@@ -275,3 +301,9 @@ func (u *UserInfo) WithCity(city string) *UserInfo {
|
||||
u.City = city
|
||||
return u
|
||||
}
|
||||
|
||||
// WithRole sets the role
|
||||
func (u *UserInfo) WithRole(role int) *UserInfo {
|
||||
u.Role = role
|
||||
return u
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user