Files
2026-08-15 17:04:47 +08:00

56 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package commonservice
import "gorm.io/gorm"
// TeamRole 查询用户在团队中的角色;非成员返回空串。
func TeamRole(db *gorm.DB, teamID, userID int64) (string, error) {
if teamID <= 0 || userID <= 0 {
return "", nil
}
var role string
err := db.Table("team_members").Select("role").
Where("team_id = ? AND user_id = ?", teamID, userID).
Scan(&role).Error
if err != nil {
return "", err
}
return role, nil
}
// TeamRoleRank 角色权重owner=3 admin=2 member=1。
func TeamRoleRank(role string) int {
switch role {
case "owner":
return 3
case "admin":
return 2
case "member":
return 1
}
return 0
}
// IsTeamAdmin 该用户是否为团队 owner/admin。
func IsTeamAdmin(db *gorm.DB, teamID, userID int64) bool {
if teamID <= 0 || userID <= 0 {
return false
}
var n int64
db.Table("team_members").
Where("team_id = ? AND user_id = ? AND role IN ('owner','admin')", teamID, userID).
Count(&n)
return n > 0
}
// RequireTeamRole 校验最低角色,返回实际角色。
func RequireTeamRole(db *gorm.DB, teamID, userID int64, min string) (string, error) {
role, err := TeamRole(db, teamID, userID)
if err != nil {
return "", err
}
if TeamRoleRank(role) < TeamRoleRank(min) {
return role, Forbidden("TEAM_FORBIDDEN")
}
return role, nil
}