access.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package agentserver
  2. import "strings"
  3. // RoleAllowed 判断用户是否可以使用新助手:allowedCSV 为空表示所有登录用户
  4. func RoleAllowed(userRoles []string, allowedCSV string) bool {
  5. allowed := splitCSV(allowedCSV)
  6. if len(allowed) == 0 {
  7. return true
  8. }
  9. for _, a := range allowed {
  10. for _, r := range userRoles {
  11. if r == a {
  12. return true
  13. }
  14. }
  15. }
  16. return false
  17. }
  18. // SelectProfile 按角色选择 Profile:byRole 形如 "ops:prf_a,admin:prf_b",
  19. // 按配置顺序取第一个用户拥有的角色;都不命中时返回 def(可为空,表示 API Key 的默认 Profile)
  20. func SelectProfile(userRoles []string, byRole, def string) string {
  21. for _, item := range splitCSV(byRole) {
  22. role, profile, ok := strings.Cut(item, ":")
  23. role, profile = strings.TrimSpace(role), strings.TrimSpace(profile)
  24. if !ok || role == "" || profile == "" {
  25. continue
  26. }
  27. for _, r := range userRoles {
  28. if r == role {
  29. return profile
  30. }
  31. }
  32. }
  33. return strings.TrimSpace(def)
  34. }
  35. func splitCSV(s string) []string {
  36. var out []string
  37. for _, p := range strings.Split(s, ",") {
  38. if p = strings.TrimSpace(p); p != "" {
  39. out = append(out, p)
  40. }
  41. }
  42. return out
  43. }