feat: allow custom RBAC roles for team member invites

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-03 04:52:45 -07:00
parent 085a9a3db4
commit dbdea622d4
12 changed files with 279 additions and 13 deletions

View File

@ -332,9 +332,12 @@ func main() {
chapaSvc.SetLearnerNotifier(learnerNotifSvc)
arifpaySvc.SetLearnerNotifier(learnerNotifSvc)
rbacStore := repository.NewRBACStore(store)
// Team management service
teamSvc := team.NewService(
repository.NewTeamStore(store),
rbacStore,
cfg.RefreshExpiry,
emailTemplateSvc,
messengerSvc,
@ -349,7 +352,7 @@ func main() {
ratingSvc := ratingsservice.NewService(repository.NewRatingStore(store))
// RBAC service
rbacSvc := rbacservice.NewService(repository.NewRBACStore(store), logger)
rbacSvc := rbacservice.NewService(rbacStore, logger)
if err := rbacSvc.SeedPermissions(context.Background()); err != nil {
log.Fatalf("failed to seed RBAC permissions: %v", err)
}

View File

@ -0,0 +1,15 @@
-- Restore built-in team role constraint. Fails if any row uses a custom role name.
ALTER TABLE team_members
ADD CONSTRAINT team_members_team_role_check
CHECK (
team_role IN (
'SUPER_ADMIN',
'ADMIN',
'CONTENT_MANAGER',
'SUPPORT_AGENT',
'INSTRUCTOR',
'FINANCE',
'HR',
'ANALYST'
)
);

View File

@ -0,0 +1,3 @@
-- Allow custom RBAC role names on team_members.team_role (not only the built-in eight).
ALTER TABLE team_members
DROP CONSTRAINT IF EXISTS team_members_team_role_check;

View File

@ -2,6 +2,7 @@ package domain
import (
"errors"
"strings"
"time"
)
@ -29,7 +30,8 @@ const (
TeamRoleAnalyst TeamRole = "ANALYST"
)
func (r TeamRole) IsValid() bool {
// IsBuiltinTeamRole reports whether r is one of the original fixed team roles.
func (r TeamRole) IsBuiltinTeamRole() bool {
switch r {
case TeamRoleSuperAdmin, TeamRoleAdmin, TeamRoleContentManager,
TeamRoleSupportAgent, TeamRoleInstructor, TeamRoleFinance,
@ -40,6 +42,37 @@ func (r TeamRole) IsValid() bool {
}
}
// IsValid is true for built-in team roles (custom roles are validated against RBAC separately).
func (r TeamRole) IsValid() bool {
return r.IsBuiltinTeamRole()
}
// NormalizeTeamRoleKey uppercases and trims a team_role / RBAC role identifier.
func NormalizeTeamRoleKey(role string) string {
return strings.ToUpper(strings.TrimSpace(role))
}
// TeamRoleForbiddenForMembers are platform learner roles that must not be assigned to team members.
var TeamRoleForbiddenForMembers = map[string]struct{}{
string(RoleStudent): {},
string(RoleOpenLearner): {},
}
// IsForbiddenTeamMemberRole reports whether a normalized role key cannot be assigned to team staff.
func IsForbiddenTeamMemberRole(roleKey string) bool {
_, forbidden := TeamRoleForbiddenForMembers[NormalizeTeamRoleKey(roleKey)]
return forbidden
}
// RBACRoleForJWT maps a stored team_role to the role name used in JWTs and permission checks.
// Built-in team roles keep their legacy platform mapping; custom RBAC roles use their own name.
func (r TeamRole) RBACRoleForJWT() Role {
if r.IsBuiltinTeamRole() {
return r.PlatformRole()
}
return Role(NormalizeTeamRoleKey(string(r)))
}
func (r TeamRole) String() string {
return string(r)
}

View File

@ -0,0 +1,30 @@
package domain
import "testing"
func TestTeamRole_IsBuiltinTeamRole(t *testing.T) {
if !TeamRoleAdmin.IsBuiltinTeamRole() {
t.Fatal("ADMIN should be builtin")
}
if TeamRole("CONTENT_MANAGER_NEW").IsBuiltinTeamRole() {
t.Fatal("custom role should not be builtin")
}
}
func TestTeamRole_RBACRoleForJWT(t *testing.T) {
if got := TeamRoleContentManager.RBACRoleForJWT(); got != RoleAdmin {
t.Fatalf("CONTENT_MANAGER JWT role = %q, want ADMIN", got)
}
if got := TeamRole("CONTENT_MANAGER_NEW").RBACRoleForJWT(); got != Role("CONTENT_MANAGER_NEW") {
t.Fatalf("custom JWT role = %q", got)
}
}
func TestIsForbiddenTeamMemberRole(t *testing.T) {
if !IsForbiddenTeamMemberRole("STUDENT") {
t.Fatal("STUDENT should be forbidden for team members")
}
if IsForbiddenTeamMemberRole("CONTENT_MANAGER_NEW") {
t.Fatal("custom staff role should be allowed")
}
}

View File

@ -18,8 +18,12 @@ func (s *Service) InviteTeamMember(ctx context.Context, req domain.InviteTeamMem
if s.inviteBaseURL == "" {
return domain.InviteTeamMemberRes{}, domain.ErrTeamInviteBaseURLNotConfigured
}
if !domain.TeamRole(req.TeamRole).IsValid() {
return domain.InviteTeamMemberRes{}, domain.ErrInvalidTeamRole
teamRole, err := s.resolveAndValidateTeamRole(ctx, req.TeamRole)
if err != nil {
if err == domain.ErrInvalidTeamRole {
return domain.InviteTeamMemberRes{}, domain.ErrInvalidTeamRole
}
return domain.InviteTeamMemberRes{}, err
}
email := strings.TrimSpace(strings.ToLower(req.Email))
@ -45,7 +49,7 @@ func (s *Service) InviteTeamMember(ctx context.Context, req domain.InviteTeamMem
LastName: domain.TeamInvitePlaceholderLastName,
Email: email,
Password: hashedPassword,
TeamRole: domain.TeamRole(req.TeamRole),
TeamRole: teamRole,
Status: domain.TeamMemberStatusInactive,
EmailVerified: false,
CreatedBy: invitedBy,

View File

@ -0,0 +1,59 @@
package team
import (
"Yimaru-Backend/internal/domain"
"context"
"errors"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
)
// resolveAndValidateTeamRole accepts a built-in team role key, an RBAC role name, or a decimal RBAC roles.id.
func (s *Service) resolveAndValidateTeamRole(ctx context.Context, raw string) (domain.TeamRole, error) {
key := strings.TrimSpace(raw)
if key == "" {
return "", domain.ErrInvalidTeamRole
}
if id, err := strconv.ParseInt(key, 10, 64); err == nil && id > 0 {
if s.rbacStore == nil {
return "", domain.ErrInvalidTeamRole
}
rec, err := s.rbacStore.GetRoleByID(ctx, id)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return "", domain.ErrInvalidTeamRole
}
return "", err
}
key = rec.Name
}
normalized := domain.NormalizeTeamRoleKey(key)
if normalized == "" || domain.IsForbiddenTeamMemberRole(normalized) {
return "", domain.ErrInvalidTeamRole
}
teamRole := domain.TeamRole(normalized)
if teamRole.IsBuiltinTeamRole() {
return teamRole, nil
}
if s.rbacStore == nil {
return "", domain.ErrInvalidTeamRole
}
if _, err := s.rbacStore.GetRoleByName(ctx, normalized); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return "", domain.ErrInvalidTeamRole
}
return "", err
}
return teamRole, nil
}
func (s *Service) IsAssignableTeamRole(ctx context.Context, raw string) bool {
_, err := s.resolveAndValidateTeamRole(ctx, raw)
return err == nil
}

View File

@ -0,0 +1,112 @@
package team
import (
"Yimaru-Backend/internal/domain"
"context"
"testing"
"github.com/jackc/pgx/v5"
)
type stubRBACStore struct {
roles map[string]domain.RoleRecord
byID map[int64]domain.RoleRecord
}
func (s *stubRBACStore) CreateRole(context.Context, string, string, bool) (domain.RoleRecord, error) {
panic("not implemented")
}
func (s *stubRBACStore) GetRoleByID(_ context.Context, id int64) (domain.RoleRecord, error) {
if r, ok := s.byID[id]; ok {
return r, nil
}
return domain.RoleRecord{}, pgx.ErrNoRows
}
func (s *stubRBACStore) GetRoleByName(_ context.Context, name string) (domain.RoleRecord, error) {
if r, ok := s.roles[name]; ok {
return r, nil
}
return domain.RoleRecord{}, pgx.ErrNoRows
}
func (s *stubRBACStore) ListRoles(context.Context, domain.RoleListFilter) ([]domain.RoleRecord, int64, error) {
panic("not implemented")
}
func (s *stubRBACStore) UpdateRole(context.Context, int64, string, string) error {
panic("not implemented")
}
func (s *stubRBACStore) DeleteRole(context.Context, int64) error { panic("not implemented") }
func (s *stubRBACStore) UpsertPermission(context.Context, domain.PermissionSeed) (domain.Permission, error) {
panic("not implemented")
}
func (s *stubRBACStore) ListPermissions(context.Context) ([]domain.Permission, error) {
panic("not implemented")
}
func (s *stubRBACStore) ListPermissionGroups(context.Context) ([]string, error) {
panic("not implemented")
}
func (s *stubRBACStore) GetPermissionByKey(context.Context, string) (domain.Permission, error) {
panic("not implemented")
}
func (s *stubRBACStore) SetRolePermissions(context.Context, int64, []int64) error {
panic("not implemented")
}
func (s *stubRBACStore) AddRolePermissions(context.Context, int64, []int64) error {
panic("not implemented")
}
func (s *stubRBACStore) GetRolePermissions(context.Context, int64) ([]domain.Permission, error) {
panic("not implemented")
}
func (s *stubRBACStore) GetAllRolesWithPermissions(context.Context) (map[string]map[string]struct{}, error) {
panic("not implemented")
}
func TestResolveAndValidateTeamRole_CustomRBACRole(t *testing.T) {
svc := &Service{
rbacStore: &stubRBACStore{
roles: map[string]domain.RoleRecord{
"CONTENT_MANAGER_NEW": {ID: 9, Name: "CONTENT_MANAGER_NEW"},
},
byID: map[int64]domain.RoleRecord{
9: {ID: 9, Name: "CONTENT_MANAGER_NEW"},
},
},
}
got, err := svc.resolveAndValidateTeamRole(context.Background(), "CONTENT_MANAGER_NEW")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != domain.TeamRole("CONTENT_MANAGER_NEW") {
t.Fatalf("got %q", got)
}
}
func TestResolveAndValidateTeamRole_ByRBACID(t *testing.T) {
svc := &Service{
rbacStore: &stubRBACStore{
roles: map[string]domain.RoleRecord{
"CONTENT_MANAGER_NEW": {ID: 9, Name: "CONTENT_MANAGER_NEW"},
},
byID: map[int64]domain.RoleRecord{
9: {ID: 9, Name: "CONTENT_MANAGER_NEW"},
},
},
}
got, err := svc.resolveAndValidateTeamRole(context.Background(), "9")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != domain.TeamRole("CONTENT_MANAGER_NEW") {
t.Fatalf("got %q", got)
}
}
func TestResolveAndValidateTeamRole_UnknownRole(t *testing.T) {
svc := &Service{rbacStore: &stubRBACStore{roles: map[string]domain.RoleRecord{}}}
_, err := svc.resolveAndValidateTeamRole(context.Background(), "NOT_A_ROLE")
if err != domain.ErrInvalidTeamRole {
t.Fatalf("want ErrInvalidTeamRole, got %v", err)
}
}

View File

@ -9,6 +9,7 @@ import (
type Service struct {
teamStore ports.TeamStore
rbacStore ports.RBACStore
refreshExpirySec int
emailTemplateSvc *emailtemplates.Service
messengerSvc *messenger.Service
@ -18,6 +19,7 @@ type Service struct {
func NewService(
teamStore ports.TeamStore,
rbacStore ports.RBACStore,
refreshExpirySeconds int,
emailTemplateSvc *emailtemplates.Service,
messengerSvc *messenger.Service,
@ -32,6 +34,7 @@ func NewService(
}
return &Service{
teamStore: teamStore,
rbacStore: rbacStore,
refreshExpirySec: refreshExpirySeconds,
emailTemplateSvc: emailTemplateSvc,
messengerSvc: messengerSvc,

View File

@ -12,8 +12,9 @@ import (
const bcryptCost = 10
func (s *Service) CreateTeamMember(ctx context.Context, req domain.CreateTeamMemberReq, createdBy *int64) (domain.TeamMember, error) {
if !domain.TeamRole(req.TeamRole).IsValid() {
return domain.TeamMember{}, domain.ErrInvalidTeamRole
teamRole, err := s.resolveAndValidateTeamRole(ctx, req.TeamRole)
if err != nil {
return domain.TeamMember{}, err
}
if req.EmploymentType != "" && !domain.EmploymentType(req.EmploymentType).IsValid() {
@ -48,7 +49,7 @@ func (s *Service) CreateTeamMember(ctx context.Context, req domain.CreateTeamMem
Email: req.Email,
PhoneNumber: req.PhoneNumber,
Password: hashedPassword,
TeamRole: domain.TeamRole(req.TeamRole),
TeamRole: teamRole,
Department: req.Department,
JobTitle: req.JobTitle,
EmploymentType: domain.EmploymentType(req.EmploymentType),
@ -92,8 +93,11 @@ func (s *Service) SearchTeamMembers(ctx context.Context, search string, teamRole
}
func (s *Service) UpdateTeamMember(ctx context.Context, req domain.UpdateTeamMemberReq) error {
if req.TeamRole != "" && !domain.TeamRole(req.TeamRole).IsValid() {
return domain.ErrInvalidTeamRole
if req.TeamRole != "" {
if _, err := s.resolveAndValidateTeamRole(ctx, req.TeamRole); err != nil {
return err
}
req.TeamRole = domain.NormalizeTeamRoleKey(req.TeamRole)
}
if req.EmploymentType != "" && !domain.EmploymentType(req.EmploymentType).IsValid() {

View File

@ -470,7 +470,7 @@ func (h *Handler) BulkDeactivateAccountsByRole(c *fiber.Ctx) error {
})
}
validUserRole := domain.Role(roleKey).IsValid()
validTeamRole := domain.TeamRole(roleKey).IsValid()
validTeamRole := h.teamSvc.IsAssignableTeamRole(c.Context(), roleKey)
if !validUserRole && !validTeamRole {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid role",
@ -595,7 +595,7 @@ func (h *Handler) BulkReactivateAccountsByRole(c *fiber.Ctx) error {
}
validUserRole := domain.Role(roleKey).IsValid()
validTeamRole := domain.TeamRole(roleKey).IsValid()
validTeamRole := h.teamSvc.IsAssignableTeamRole(c.Context(), roleKey)
if !validUserRole && !validTeamRole {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid role",

View File

@ -33,7 +33,7 @@ type changePasswordReq struct {
}
func mapTeamRoleToRole(teamRole domain.TeamRole) domain.Role {
return teamRole.PlatformRole()
return teamRole.RBACRoleForJWT()
}
// TeamMemberLogin godoc