低空智控平台 后端go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

46 lines
1.0 KiB

package common
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
const (
RoleAdmin = "admin"
RoleUser = "user"
)
// IsAdmin 判断当前用户是否为 admin(全量数据)
func IsAdmin(c *gin.Context) bool {
roles := c.MustGet("roles").([]string)
for _, role := range roles {
if role == RoleAdmin {
return true
}
}
return false
}
// GetUserId 从上下文获取当前用户 ID
func GetUserId(c *gin.Context) int64 {
return c.GetInt64("user_id")
}
// GetAuthFilter admin 返回空 filter(全量),user 返回 user_id 过滤
func GetAuthFilter(c *gin.Context) map[string]interface{} {
filter := make(map[string]interface{})
if IsAdmin(c) {
return filter
}
filter["user_id"] = GetUserId(c)
return filter
}
// WithUserFilter admin 不过滤,user 按 user_id 过滤(GORM scope)
func WithUserFilter(c *gin.Context) func(db *gorm.DB) *gorm.DB {
if IsAdmin(c) {
return func(db *gorm.DB) *gorm.DB { return db }
}
uid := GetUserId(c)
return func(db *gorm.DB) *gorm.DB { return db.Where("user_id = ?", uid) }
}