# NexusCRM User & Access Management — Complete Picture

**Date:** 2026-04-03
**Method:** 3 parallel explore agents
**Scope:** Everything beyond permission enforcement — User lifecycle, Profile/Role admin, Setup UI, Audit, OAuth, Password policies

---

## 1. Comprehensive SF vs NexusCRM Comparison

| Domain | Feature | NexusCRM Status |
|--------|---------|----------------|
| **USER MANAGEMENT** | | |
| | User CRUD (create/update/delete) | **Fully Implemented** |
| | User activation/deactivation (IsActive) | **Fully Implemented** |
| | Profile assignment | **Fully Implemented** |
| | Role assignment | **Fully Implemented** |
| | Manager hierarchy (ManagerID) | **Fully Implemented** |
| | Login history per user | **Not Implemented** |
| | Password reset flow (self-service + admin) | **Not Implemented** |
| | Failed login attempt tracking | **Not Implemented** |
| **PROFILE MANAGEMENT** | | |
| | Profile CRUD | **Fully Implemented** |
| | Profile permissions (Object, Field, System) | **Fully Implemented** |
| | Standard/system profiles | **Fully Implemented** |
| | Clone profile | **Not Implemented** |
| **ROLE & HIERARCHY** | | |
| | Role hierarchy (parent-child tree) | **Fully Implemented** |
| | Role-based sharing | **Fully Implemented** |
| | Role assignment to users | **Fully Implemented** |
| | Role deletion with subordinate reassignment | **Partially Implemented** |
| **PERMISSION SETS & GROUPS** | | |
| | PermissionSet CRUD | **Fully Implemented** |
| | PermissionSet assignment to users | **Fully Implemented** |
| | PermissionSet Groups (PSG) | **Fully Implemented** (backend only, no UI) |
| | Muting Permission Sets | **Fully Implemented** (backend only, no UI) |
| | Custom Permissions | **Fully Implemented** (backend only, no UI) |
| **SHARING MODEL** | | |
| | OWD (Organization-Wide Defaults) | **Not Implemented** |
| | Sharing Rules (criteria-based) | **Fully Implemented** |
| | Manual sharing (record-level) | **Fully Implemented** |
| | Role hierarchy sharing | **Fully Implemented** |
| | Territory management | **Not Implemented** |
| **RECORD/OBJECT/FIELD SECURITY** | | |
| | Object permissions (CRUD + ViewAll + ModifyAll) | **Fully Implemented** |
| | Field-level security (read/edit per field) | **Fully Implemented** |
| | Record-level access (5-layer check) | **Fully Implemented** |
| | SQL RLS (bulk query filtering) | **Partially Implemented** (owner_id only) |
| **SETUP ADMINISTRATION** | | |
| | Setup pages: Users | **Fully Implemented** |
| | Setup pages: Profiles | **Fully Implemented** |
| | Setup pages: Roles | **Fully Implemented** |
| | Setup pages: Permission Sets | **Fully Implemented** |
| | Setup pages: Permission Set Groups | **Not Implemented** (backend ready) |
| | Setup pages: Sharing Rules | **Fully Implemented** |
| | Setup pages: Groups/Queues | **Fully Implemented** |
| | Setup pages: Permission Analyzer | **Fully Implemented** |
| | Setup pages: System Permissions | **Not Implemented** |
| | Setup pages: Custom Permissions | **Not Implemented** |
| | Object/Field permissions matrix view | **Not Implemented** |
| | OWD configuration page | **Not Implemented** |
| **AUDIT & COMPLIANCE** | | |
| | Field history tracking | **Fully Implemented** (_System_AuditLog) |
| | Login history | **Not Implemented** |
| | Setup audit trail | **Not Implemented** |
| | API usage logs | **Not Implemented** |
| | Login IP tracking | **Fully Implemented** (in _System_Session) |
| | Active session management UI | **Not Implemented** |
| **AUTHENTICATION & SSO** | | |
| | Username/password auth | **Fully Implemented** |
| | OAuth 2.0 (auth code + password grant) | **Fully Implemented** |
| | Google OAuth | **Fully Implemented** |
| | SAML 2.0 SSO | **Not Implemented** |
| | Two-factor authentication (MFA) | **Not Implemented** |
| | Session timeout configuration | **Partially Implemented** (hardcoded 24h) |
| | Connected Apps table | **Fully Implemented** (no admin UI) |
| **PASSWORD POLICIES** | | |
| | Password complexity rules | **Partially Implemented** (ValidatePasswordStrength exists) |
| | Password expiration | **Not Implemented** |
| | Password history (reuse prevention) | **Not Implemented** |
| | Lockout after failed attempts | **Not Implemented** |
| | Self-service password reset | **Not Implemented** |
| **DELEGATION** | | |
| | Delegated administration | **Not Implemented** |
| | IP/login hour restrictions | **Not Implemented** |
| | | |
| **TOTALS** | **Fully Implemented** | **28 / 49 (57%)** |
| | **Partially Implemented** | **6 / 49 (12%)** |
| | **Not Implemented** | **15 / 49 (31%)** |

---

## 2. User Lifecycle Implementation

### User Model

**Table:** `_System_User`

Key fields: ID, Username, Email, Password (bcrypt), FirstName, LastName, ProfileID (required), UserRoleID (optional), ManagerID, IsActive, LastLoginDate

### User CRUD

| Operation | Implementation | File |
|-----------|---------------|------|
| Create | `AuthService.CreateUser()` — validates email, hashes password, defaults ProfileID | `auth_user_mgmt.go:28-96` |
| Update | `AuthService.UpdateUser()` — profile/role reassignment, password change | `auth_user_mgmt.go:107-170` |
| Delete | `AuthService.DeleteUser()` — soft delete | `auth_user_mgmt.go:173-189` |
| List | `AuthService.GetUsers()` — returns all with profile/role names resolved | `auth_user_mgmt.go:221+` |
| Bulk import | `SystemManager.BatchUpsertUsers()` — batch SQL with bcrypt caching | `system_manager.go:239` |

### Profile-PermissionSet Relationship

Every Profile has an implicit PermissionSet with `IsOwnedByProfile = 1`:
- `EnsureProfilePermissionSet()` (perm_sets.go:190) — creates/retrieves the backing PermSet
- `INSERT IGNORE` pattern for concurrent safety
- All object/field permissions hang off this PermSet, not the Profile directly

### Known Gap: No Cache Invalidation on Profile/Role Change

When a user's ProfileID or UserRoleID is changed via `UpdateUser()`, the permission cache is **not automatically invalidated**. The user continues operating under old permissions until the 5-min TTL expires or they re-login.

---

## 3. Setup UI Completeness

### Registered Setup Pages (13 pages)

| Page | Component | Permission Guard | Status |
|------|-----------|-----------------|--------|
| /setup/objects | ObjectManager | ViewSetup | Working |
| /setup/users | UserManager | ManageUsers | Working |
| /setup/profiles | ProfileManager | ManageProfilesPermSets | Working |
| /setup/permsets | PermissionSetManager | ManageProfilesPermSets | Working |
| /setup/groups | GroupManager | ManageSharing | Working |
| /setup/roles | RoleManager | ManageRoles | Working |
| /setup/sharing | SharingRuleManager | ManageSharing | Working |
| /setup/permission-analyzer | PermissionAnalyzer | ViewSetup | Working |
| /setup/flows | FlowsPage | ManageFlows | Working |
| /setup/apps | AppManager | CustomizeApplication | Working |
| /setup/import | DataImport | — | Working |
| /setup/export | DataExport | — | Working |
| /setup/schema | SchemaBuilder | — | Working |

### Missing Setup Pages

| Page | Backend Ready? | What's Needed |
|------|---------------|---------------|
| /setup/permission-set-groups | Yes (service_psg.go) | Register in SetupRegistry + build UI (~400 LOC) |
| /setup/system-permissions | Yes | Build permission catalog viewer |
| /setup/custom-permissions | Yes (perm_custom.go) | Build CRUD UI |
| /setup/sharing-settings (OWD) | No | Need OWD data model + API + UI |
| /setup/connected-apps | Partial | Need admin management UI |
| /setup/login-history | No | Need LoginHistory table + UI |
| /setup/session-management | Partial (sessions in DB) | Need admin list/revoke endpoint + UI |

### PermissionSet Assignment UI

Fully working flow in UserManager:
1. Admin opens user detail → "Permission Sets" tab
2. `UserPermissionSetsSection` loads assignments via SOQL on PermissionSetAssignment
3. "Add" button → modal → select PermSet → POST PermissionSetAssignment
4. "Remove" button → DELETE PermissionSetAssignment

### Permission Editor

`PermissionEditorModal` provides object + field permission editing:
- Opens from ProfileManager or PermissionSetManager "Permissions" button
- Object permissions: toggle R/C/E/D/ViewAll/ModifyAll per object
- Field permissions: toggle Read/Edit per field
- Missing: bulk matrix view (objects × profiles side-by-side)

---

## 4. Authentication & OAuth

### Login Flow

```
POST /services/oauth2/token
  → FindUserByEmailWithPassword()
  → VerifyPassword (bcrypt)
  → rejectInactiveUser()
  → createAndPersistSession()
    → GenerateToken(UserSession) — JWT HS256, 24h expiry
    → InsertSession(jti, IP, UserAgent) — DB persistence
  → Return {access_token, token_type, expires_in, instance_url}
```

### OAuth 2.0 Support

| Grant Type | Status | Notes |
|-----------|--------|-------|
| Authorization Code | Implemented | Full flow with auth code → token exchange |
| Password | Implemented | SF-compatible with security_token param |
| Client Credentials | Implemented | Service account flow |
| Google OAuth | Implemented | Separate endpoint |
| SAML 2.0 | Not implemented | |
| OIDC | Partial | JWT claims serve as OIDC-like userinfo |

### Session Management

- **Storage:** `_System_Session` table (UserID, Token, ExpiresAt, LastActivity, IpAddress, UserAgent, IsRevoked)
- **Validation:** Every request checks JWT signature + DB revocation status
- **Activity tracking:** `TouchSession()` updates LastActivity async (fire-and-forget, 5s timeout)
- **Revocation:** `Logout()` marks session as revoked by JTI
- **Missing:** Admin session list/revoke UI, configurable timeout, forced logout

---

## 5. Audit Capabilities

| Capability | SF | NexusCRM | Gap |
|-----------|-----|---------|-----|
| Field change history | `FieldHistoryArchive` | `_System_AuditLog` (ObjectApiName, RecordId, FieldName, OldValue, NewValue, ChangedById) | None — equivalent |
| Login history | `LoginHistory` object (success + failures) | Session records only (no failures) | **Major** — no failed login tracking, no login history UI |
| Setup audit trail | `SetupAuditTrail` object | Not implemented | **Major** — no tracking of permission/config changes |
| API usage logs | Per-app API call tracking | Not implemented | Minor for 127 users |
| Session management | Active Sessions page | Sessions in DB but no admin visibility | **Medium** — admin can't see/revoke sessions |

### Key Architectural Gap: Login History vs Session History

NexusCRM conflates these two concepts:
- **Sessions** = active/revoked state (infrastructure concern)
- **Login History** = when/where/how user logged in, including failures (audit concern)

Salesforce separates them. NexusCRM needs a dedicated `LoginHistory` table.

---

## 6. Password & Security Policies

| Policy | SF | NexusCRM | Gap |
|--------|-----|---------|-----|
| Password complexity | Configurable (min length, require upper/lower/number/special) | `ValidatePasswordStrength()` exists, rules unknown | **Partial** |
| Password expiration | Configurable (days until expiry) | Not implemented | **Missing** |
| Password history | Configurable (prevent reuse of last N) | Not implemented | **Missing** |
| Account lockout | Configurable (N failures → lock for M minutes) | Not implemented | **Missing** |
| Password reset (email) | Self-service + admin-initiated | Not implemented | **Missing** |
| IP restrictions | Per-profile IP ranges | Not implemented | **Missing** |
| Login hour restrictions | Per-profile time windows | Not implemented | **Missing** |
| MFA / 2FA | Configurable | Not implemented | **Missing** |

---

## 7. What's Important for 127 Users (Prioritized)

### Must Have (Security & Compliance)

| # | Item | Why | Effort |
|---|------|-----|--------|
| 1 | **Permission cache invalidation on profile/role change** | Users get stale permissions for up to 5 min after admin changes | 1d |
| 2 | **Login history table** | Compliance requirement; debug login issues | 2d |
| 3 | **Failed login tracking + lockout** | Brute force protection | 2d |
| 4 | **Setup audit trail** | "Who changed this permission?" — compliance and debugging | 3d |
| 5 | **PSG management UI** | Backend 100% ready, users can't manage PSGs without it | 2d |
| 6 | **Admin session management** | Admin needs to force-logout compromised accounts | 1d |

### Should Have (Admin UX)

| # | Item | Effort |
|---|------|--------|
| 7 | Password reset flow (email-based) | 3d |
| 8 | OWD configuration page | 2d (paired with OWD backend) |
| 9 | System permissions catalog page | 1d |
| 10 | Custom permissions management UI | 1d |
| 11 | Connected Apps admin UI | 2d |

### Nice to Have (Enterprise features, not urgent at 127 users)

| # | Item |
|---|------|
| 12 | SAML 2.0 SSO |
| 13 | MFA / 2FA |
| 14 | IP restrictions per profile |
| 15 | Login hour restrictions |
| 16 | Password expiration + history |
| 17 | Delegated administration |
| 18 | Object/field permissions matrix view |
| 19 | Territory Management |

---

## 8. Architecture Diagram — Full User & Access Management

```
┌─────────────────────────────────────────────────────────────────┐
│                     AUTHENTICATION                              │
│                                                                 │
│  Login (password/OAuth/Google)                                  │
│    → Password validation (bcrypt)                               │
│    → [MISSING: IP/login hour check]                             │
│    → [MISSING: lockout check]                                   │
│    → JWT generation (HS256, 24h)                                │
│    → Session persistence (_System_Session)                      │
│    → [MISSING: LoginHistory record]                             │
│    → Permission cache warm                                      │
│                                                                 │
│  Per-request: RequireAuth middleware                             │
│    → JWT signature verify                                       │
│    → DB session revocation check                                │
│    → TouchSession (async activity update)                       │
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                  IDENTITY MANAGEMENT                            │
│                                                                 │
│  User ──┬── ProfileID (required) ── Profile                     │
│         │     └── IsOwnedByProfile PermissionSet                │
│         │         └── ObjectPerms, FieldPerms, SystemPerms      │
│         │                                                       │
│         ├── UserRoleID (optional) ── UserRole                   │
│         │     └── ParentRoleID (hierarchy tree, in-memory cache)│
│         │                                                       │
│         ├── PermissionSetAssignment ── PermissionSet(s)         │
│         │     └── ObjectPerms, FieldPerms, SystemPerms          │
│         │                                                       │
│         └── PSG Assignment ── PermissionSetGroup                │
│               ├── PermissionSetGroupComponent(s) ── PermSet(s)  │
│               └── MutingPermissionSet (subtract)                │
│                                                                 │
│  Resolution: Profile ∪ PermSets ∪ PSG - Muting                 │
│  Cache: 5min TTL + singleflight + bulk warm                    │
│  [MISSING: invalidation on profile/role change]                 │
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                  AUTHORIZATION (3 orthogonal dimensions)        │
│                                                                 │
│  Object Perms ─── Can user do R/C/E/D on this object?          │
│  Field Perms ──── Can user see/edit this field?                 │
│  Record Access ── Can user access this specific record?         │
│    └── [MISSING: OWD] → Owner → Hierarchy → Sharing → Manual   │
│                                                                 │
│  SQL RLS ──── Bulk query filtering (needs upgrade)              │
│  Route Guards ── RequirePermission middleware on routes          │
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                  SETUP ADMINISTRATION                           │
│                                                                 │
│  ✅ Users, Profiles, Roles, PermSets, Groups, Sharing Rules    │
│  ✅ Permission Analyzer, Schema Builder, Flows, Apps           │
│  ❌ PSG Management (backend ready, no UI)                      │
│  ❌ System/Custom Permissions pages                            │
│  ❌ OWD Configuration                                          │
│  ❌ Connected Apps admin                                       │
│  ❌ Session Management                                          │
│  ❌ Login History                                               │
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                  AUDIT & COMPLIANCE                             │
│                                                                 │
│  ✅ Field change history (_System_AuditLog)                    │
│  ✅ Login IP tracking (in _System_Session)                     │
│  ❌ Login History (success + failures)                          │
│  ❌ Setup Audit Trail (who changed permissions?)               │
│  ❌ Admin session view/revoke                                   │
│  ❌ API usage logs                                              │
└─────────────────────────────────────────────────────────────────┘
```

---

## File Index

Key implementation files referenced in this document:

| Area | File | Purpose |
|------|------|---------|
| User CRUD | `backend/internal/features/auth/auth_user_mgmt.go` | Create/Update/Delete users |
| Login/Session | `backend/internal/features/auth/auth_service.go` | Login, session validation, logout |
| OAuth | `backend/internal/features/auth/oauth_service.go` | OAuth 2.0 flows |
| Session DB | `backend/internal/infrastructure/persistence/session_repository.go` | Session CRUD |
| User DB | `backend/internal/infrastructure/persistence/user_repository.go` | User queries |
| Profile DB | `backend/internal/infrastructure/persistence/perm_system.go` | Profile queries |
| Role DB | `backend/internal/infrastructure/persistence/perm_roles.go` | Role CRUD + hierarchy |
| PermSet DB | `backend/internal/infrastructure/persistence/perm_sets.go` | PermSet queries + EnsureProfilePermissionSet |
| PSG Service | `backend/internal/features/permissions/service_psg.go` | PSG management |
| PSG DB | `backend/internal/infrastructure/persistence/perm_groups.go` | PSG CRUD |
| Routes | `backend/cmd/server/routes.go` | All API endpoints |
| Bootstrap | `backend/internal/bootstrap/system_data.go` | System data initialization |
| Setup Registry | `frontend/src/registries/SetupRegistry.ts` | Setup page definitions |
| Setup Perms | `frontend/src/features/setup/setupPermissions.ts` | Permission gates for setup pages |
| User Manager UI | `frontend/src/pages/UserManager.tsx` | User admin page |
| Profile Manager UI | `frontend/src/pages/ProfileManager.tsx` | Profile admin page |
| Role Manager UI | `frontend/src/pages/RoleManager.tsx` | Role hierarchy page |
| PermSet Manager UI | `frontend/src/pages/PermissionSetManager.tsx` | PermSet admin page |
| PermSet Assignment | `frontend/src/features/users/components/UserPermissionSetsSection.tsx` | Assign/remove PermSets |
| Permission Editor | `frontend/src/features/security/components/PermissionEditorModal.tsx` | Object/field perm editing |
| Sharing Rules UI | `frontend/src/pages/SharingRuleManager.tsx` | Sharing rules admin |
| Permission Analyzer | `frontend/src/pages/PermissionAnalyzer.tsx` | User permission comparison |
