NDSS CRM Manual / Chapter 4: Authentication & User Management
V3.8 · 2024/2025

Chapter 4: Authentication & User Management

Complete documentation of the NDSS CRM authentication system, login workflows, user registration, password recovery, role-based access control with all 24 roles, session management, demo mode, and security best practices.

4.1 Authentication Overview

NDSS CRM uses Supabase / Oracle Auth as its authentication provider, delivering a secure, standards-compliant identity management layer. Supabase / Oracle Auth is built on top of the GoTrue open-source authentication server and supports multiple authentication methods including email/password credentials and OAuth social login providers.

All authentication operations - login, registration, password reset, email verification, and session management - are handled by the Supabase / Oracle Auth server. The NDSS CRM frontend communicates with this server via the @supabase/supabase-js client library and the @supabase/ssr helper for server-side session management in the Next.js App Router environment.

4.1.1 Supported Authentication Methods

Method Status Description
Email / Password Active Primary authentication method. Users sign in with their registered email address and password. Passwords are hashed using bcrypt with a cost factor of 10.
Google OAuth Active Staff members can sign in using their Google Workspace accounts if the organisation has configured Google OAuth integration in the Admin settings.
Microsoft OAuth Optional Available for organisations using Microsoft 365. Must be configured by a Master Administrator with Azure AD credentials.
Magic Link Optional Passwordless login via a one-time link sent to the user's email. Can be enabled as an alternative to password-based login.
Phone OTP Planned One-time password sent via SMS for two-factor authentication. Planned for V4.0 release.

4.1.2 Authentication Architecture

The authentication system spans three layers of the NDSS CRM architecture:

  • Client Layer (Next.js): The login, registration, and password reset forms are rendered as React components within the (auth) route group. Form submissions call Supabase / Oracle Auth client methods.
  • Middleware Layer (Next.js Middleware): The src/middleware.ts file intercepts every request and verifies the session cookie. Unauthenticated users attempting to access protected routes are redirected to /login.
  • Backend Layer (Supabase / Oracle Auth): The Supabase / Oracle Auth server validates credentials, issues JWT tokens, manages sessions, sends verification emails, and handles password resets.
Technical Note

NDSS CRM uses the @supabase/ssr package (version 0.5.x) for cookie-based session management compatible with the Next.js 16 App Router. This replaces the deprecated @supabase/auth-helpers-nextjs package used in earlier versions of the platform.

4.2 Login Process

The login page is the primary entry point for all NDSS CRM users. It is served at the /login URL and uses a minimal layout without the sidebar or topbar. The page consists of a centred card containing the NDSS CRM logo, a role selector for demo mode, email and password fields, a captcha verification widget, and the login button.

4.2.1 Login Page Wireframe

NDSS CRM - Login Page
N
NDSS CRM
Newdawn Support Services
DEMO MODE - Select Role
Select a role to preview...
OR SIGN IN
Email Address
you@newdawn.org.au
Password
●●●●●●●●●●
CAPTCHA Verification Widget
hCaptcha / Turnstile
Sign In
Or continue with
Google
Microsoft
Don't have an account? Request Access
Fig 4.1 - The NDSS CRM login page with role selector for demo mode, email/password fields, CAPTCHA widget, OAuth options, and registration link.

4.2.2 Login Flow Steps

  1. The user navigates to https://crm.newdawn.org.au/login.
  2. The login page renders with the email and password fields, plus the demo role selector (if demo mode is enabled).
  3. The user enters their email address and password.
  4. The user completes the CAPTCHA verification (hCaptcha or Cloudflare Turnstile, configured per environment).
  5. The user clicks "Sign In" or presses Enter.
  6. The form submission handler calls supabase.auth.signInWithPassword({ email, password }).
  7. Supabase / Oracle Auth validates the credentials. If invalid, an error message is displayed: "Invalid email or password."
  8. If valid, Supabase / Oracle Auth returns an access token (JWT) and a refresh token.
  9. The @supabase/ssr library stores the tokens in an HTTP-only, secure, SameSite cookie.
  10. The application fetches the user profile from the profiles table to determine the assigned role.
  11. The user is redirected to the appropriate landing page based on their role (see table below).

4.2.3 Role-Based Landing Pages

Role Category Landing Page Notes
Administration Roles/dashboardFull admin dashboard with all KPI widgets and quick actions
Operations Roles/dashboardOperations-focused dashboard with task lists and pending items
Support Workers/dashboardWorker dashboard showing today's shifts and client list
Clinical Roles/dashboardClinical dashboard with care plan summaries and assessments
Client / Family/portalClient portal with service schedule and plan information

4.2.4 Login Error Handling

Error Condition User Message Technical Detail
Invalid credentials"Invalid email or password. Please try again."Supabase / Oracle returns AuthApiError: Invalid login credentials
Email not verified"Please verify your email address before signing in."The email_confirmed_at field is null
Account disabled"Your account has been deactivated. Contact your administrator."Profile is_active is false
Rate limited"Too many login attempts. Please wait 60 seconds."Supabase / Oracle rate limiting (default: 30 requests per hour per IP)
CAPTCHA failed"CAPTCHA verification failed. Please try again."hCaptcha or Turnstile token validation failed on the server
Network error"Unable to connect. Check your internet connection."Fetch request to Supabase / Oracle Auth server timed out or failed

4.3 User Registration

New user registration in NDSS CRM is a controlled process. Unlike public SaaS applications, NDSS CRM does not allow unrestricted self-registration. Instead, new accounts are created through one of two pathways: administrator-initiated registration (the primary method) or invitation-based self-registration (for client portal users).

4.3.1 Registration Form Wireframe

NDSS CRM - Registration / Signup Page
N
Create Your Account
NDSS CRM by Newdawn Support Services
Full Name *
Enter your full name
Email Address *
you@newdawn.org.au
Phone Number
04XX XXX XXX
Password *
Min 8 chars, uppercase, number, symbol
Confirm Password *
Re-enter your password
Invitation Code *
Enter the code from your invitation email
I agree to the Terms of Service and Privacy Policy
Create Account
Already have an account? Sign In
Fig 4.2 - The registration form requires an invitation code, personal details, and password meeting complexity requirements.

4.3.2 Administrator-Initiated Registration

The primary method for creating new accounts is through the Admin panel (Chapter 17):

  1. An administrator navigates to Admin > User Management > Create User.
  2. The admin fills in the new user's name, email, phone, and assigns a role from the 24 available roles.
  3. The system calls supabase.auth.admin.createUser() with the provided details.
  4. Supabase / Oracle Auth creates the user record and sends a verification/welcome email with a temporary password or a set-password link.
  5. A corresponding record is created in the profiles table with the assigned role.
  6. If the user is a staff member, an additional record is created in the staff_profiles table.
  7. The new user receives the email, sets their password, and can log in.

4.3.3 Invitation-Based Self-Registration

For client portal users (NDIS participants and their families/carers), a simplified invitation flow is used:

  1. A service coordinator generates an invitation code from the client's profile page.
  2. The invitation code is sent to the participant or family member via email or SMS.
  3. The recipient navigates to /register and enters the invitation code along with their personal details.
  4. The system validates the invitation code, creates the user account with the client or family_member role, and links it to the existing client record.
Important

Invitation codes are single-use and expire after 7 days. If an invitation expires, the service coordinator must generate a new one. Invitation codes cannot be reused once redeemed, even if the registration was not completed.

4.4 Password Recovery

NDSS CRM provides a standard password recovery flow using Supabase / Oracle Auth's built-in password reset functionality. The process is initiated from the login page via the "Forgot password?" link.

4.4.1 Password Recovery Flow

  1. Step 1 - Request Reset: The user clicks "Forgot password?" on the login page, which navigates to /forgot-password.
  2. Step 2 - Enter Email: The user enters their registered email address and submits the form.
  3. Step 3 - Email Sent: The system calls supabase.auth.resetPasswordForEmail(email). A success message is displayed regardless of whether the email exists in the system (to prevent user enumeration).
  4. Step 4 - Email Received: If the email exists, Supabase / Oracle sends a password reset email containing a unique, time-limited reset link.
  5. Step 5 - Reset Page: The user clicks the link, which redirects to /reset-password with a token parameter.
  6. Step 6 - New Password: The user enters and confirms their new password, which must meet the complexity requirements (see Section 4.8).
  7. Step 7 - Confirmation: The password is updated via supabase.auth.updateUser({ password }). The user is redirected to the login page with a success message.

4.4.2 Password Reset Email

Parameter Value
From Addressnoreply@newdawn.org.au
Subject Line"NDSS CRM - Reset Your Password"
Link Expiry1 hour from time of request
Max Attempts3 reset requests per email per hour
Token TypeSingle-use, cryptographically random token

4.4.3 Administrator Password Reset

Administrators with the master_admin or administrator role can force-reset a user's password from the Admin panel. This generates a new temporary password and sends it to the user's email, requiring the user to change it on their next login.

4.5 Role-Based Access Control (RBAC)

NDSS CRM implements a comprehensive Role-Based Access Control system with 24 distinct user roles. Each role defines precisely which modules, pages, actions, and data a user can access. Roles are assigned during account creation and can be changed only by users with the master_admin or administrator role.

The RBAC system operates at three levels:

  • Route Level: Next.js middleware checks the user's role before serving a page. Unauthorised roles are redirected to a "403 - Access Denied" page.
  • Component Level: The <RoleGate> component conditionally renders UI elements (buttons, tabs, columns) based on the current user's role.
  • Database Level: PostgreSQL Row Level Security (RLS) policies filter query results based on the authenticated user's role, ensuring data isolation even if application-level checks are bypassed.

4.5.1 Complete Role Directory

The following tables list all 24 roles organised by functional category, with their module access permissions.

Administration Roles (2 roles)

# Role Identifier Display Name Access Level
1master_adminMaster AdministratorFull unrestricted access to all modules, settings, user management, and system configuration. Maximum 2-3 per organisation.
2administratorAdministratorFull access to all operational modules. Cannot modify system-level settings reserved for Master Admins (e.g., Supabase / Oracle configuration, RLS policies).

Operations Roles (6 roles)

# Role Identifier Display Name Access Level
3operations_managerOperations ManagerClients, Staff, Rostering, Finance, Compliance, Intake, Reports. Full read/write on operational data.
4service_coordinatorService CoordinatorClients (assigned), Rostering, Intake, Clinical. Manages participant service plans and coordinates supports.
5team_leaderTeam LeaderStaff (team members), Rostering (team shifts), Compliance (team incidents). Supervisory access for their team.
6rostering_officerRostering OfficerFull Rostering access, read-only Clients and Staff. Manages shift scheduling and allocation.
7intake_officerIntake OfficerFull Intake & Referrals access, read-only Clients. Manages the participant intake pipeline.
8quality_officerQuality & Compliance OfficerFull Compliance access, read-only across all modules for auditing purposes.

Finance Roles (3 roles)

# Role Identifier Display Name Access Level
9finance_managerFinance ManagerFull Finance access including invoicing, claims, budgets, payroll sync, and financial reports.
10finance_officerFinance OfficerFinance read/write for invoicing and claims. Cannot modify budgets or approve payroll.
11accounts_payableAccounts PayableLimited Finance access for processing outgoing payments and expense management only.

Clinical Roles (4 roles)

# Role Identifier Display Name Access Level
12clinical_leadClinical LeadFull Clinical Services access, Clients (clinical data), Reports (clinical). Oversees all clinical programs.
13behaviour_practitionerBehaviour Support PractitionerClinical (BSP module), Clients (assigned, clinical data). Creates and manages behaviour support plans.
14occupational_therapistOccupational TherapistClinical (OT module), Clients (assigned, clinical data). Manages OT assessments and interventions.
15nurseRegistered NurseClinical (Nursing module), Clients (medical data). Manages medication, nursing care plans, and health monitoring.

Support Worker Roles (3 roles)

# Role Identifier Display Name Access Level
16support_workerSupport WorkerMy Shifts (view/clock in), Assigned Clients (progress notes, basic profile). Core frontline role.
17senior_support_workerSenior Support WorkerSame as Support Worker plus ability to view team shifts and approve junior worker timesheets.
18casual_workerCasual Support WorkerRestricted version of Support Worker - can only see shifts assigned to them and submit timesheets.

HR & Learning Roles (2 roles)

# Role Identifier Display Name Access Level
19hr_managerHR ManagerFull Staff Management access, Learning & Development, Compliance (staff-related). Manages recruitment and employee records.
20training_coordinatorTraining CoordinatorFull Learning & Development access, read-only Staff profiles for training assignment.

Client-Facing Roles (3 roles)

# Role Identifier Display Name Access Level
21clientNDIS ParticipantClient Portal only - My Services, My Plan, Messages, Documents. Cannot access internal platform.
22family_memberFamily Member / CarerClient Portal (read-only view of linked participant data). Can view schedules and progress but cannot modify.
23plan_managerPlan Manager (External)Limited Finance view for invoices and claims related to their managed participants.

System Roles (1 role)

# Role Identifier Display Name Access Level
24demo_userDemo UserRead-only access to all modules with sample data. Cannot create, edit, or delete any records. Used for platform demonstrations.

4.5.2 Module Access Matrix

The following summarised matrix shows which role categories can access each major module. For individual role permissions, refer to the detailed tables above.

Module Admin Ops Finance Clinical Workers HR Client
DashboardFullFullLimitedLimitedLimitedLimitedPortal
ClientsFullFullReadAssignedAssignedNoneOwn
StaffFullReadNoneNoneOwnFullNone
RosteringFullFullReadReadOwnNoneView
FinanceFullReadFullNoneNoneNoneView
ComplianceFullFullNoneReadReportReadNone
IntakeFullFullNoneReadNoneNoneNone
ClinicalFullReadNoneFullReadNoneView
LearningFullReadNoneOwnOwnFullNone
MessagingFullFullOwnOwnOwnOwnOwn
ReportsFullFullFinanceClinicalNoneHRNone
AdminFullNoneNoneNoneNoneNoneNone
Permission Legend

Full = Read, Create, Edit, Delete. Read = View only. Own = Can only access records related to themselves. Assigned = Can only access records for clients/staff assigned to them. Report = Can submit (e.g., incident reports) but not manage. View = Simplified read-only view (e.g., client portal). None = No access.

4.6 Session Management

NDSS CRM uses cookie-based session management implemented through the @supabase/ssr library. This approach is optimised for the Next.js App Router architecture, where both server-side and client-side rendering need access to the user session.

4.6.1 Session Cookie Configuration

Setting Value Purpose
Cookie Namesb-ndss-auth-tokenUnique cookie name to prevent conflicts with other Supabase / Oracle projects
HttpOnlytruePrevents JavaScript access to the cookie, mitigating XSS attacks
SecuretrueCookie is only sent over HTTPS connections
SameSiteLaxProvides CSRF protection while allowing normal navigation
Path/Cookie is available on all routes
Max-Age604800 (7 days)Maximum session duration before re-authentication is required

4.6.2 Token Refresh Mechanism

The Supabase / Oracle Auth system uses a dual-token approach. The access token (JWT) is short-lived (1 hour) and contains the user's identity and role claims. The refresh token is longer-lived (7 days) and is used to obtain new access tokens without requiring the user to re-enter credentials.

The refresh process works as follows:

  1. Every Supabase / Oracle client request checks whether the access token has expired or will expire within the next 60 seconds.
  2. If expiring, the client automatically calls supabase.auth.refreshSession() using the refresh token.
  3. Supabase / Oracle Auth validates the refresh token and issues a new access token and refresh token pair.
  4. The new tokens are stored in the session cookie, replacing the old ones.
  5. If the refresh token itself has expired (after 7 days), the user is logged out and redirected to the login page.

4.6.3 Idle Timeout

NDSS CRM implements a client-side idle timeout of 30 minutes. If the user does not interact with the application (mouse movement, keyboard input, or scroll events) for 30 consecutive minutes, a warning dialog appears giving the user 60 seconds to click "Stay Logged In" before they are automatically logged out.

// Idle timeout implementation (simplified)
const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes
const WARNING_DURATION = 60 * 1000;   // 60 seconds

let idleTimer: NodeJS.Timeout;

function resetIdleTimer() {
  clearTimeout(idleTimer);
  idleTimer = setTimeout(showIdleWarning, IDLE_TIMEOUT);
}

// Reset on user activity
['mousemove', 'keydown', 'scroll', 'click'].forEach(event => {
  document.addEventListener(event, resetIdleTimer, { passive: true });
});

4.6.4 Multi-Tab Session Synchronisation

When a user logs out from one browser tab, all other open tabs must also log out to prevent stale session issues. NDSS CRM achieves this using the BroadcastChannel API to synchronise logout events across tabs:

  • When a user clicks "Sign Out", the application broadcasts a LOGOUT message on the ndss-auth-channel BroadcastChannel.
  • All other open tabs listen for this message and immediately call supabase.auth.signOut() and redirect to the login page.
  • This also applies to session expiry events, ensuring all tabs reflect the current authentication state.

4.7 Demo Mode

NDSS CRM includes a built-in demo mode that allows prospective users, stakeholders, and training participants to explore the platform without affecting real data. Demo mode provides read-only access to all modules using pre-populated sample data.

4.7.1 How Demo Mode Works

  1. Role Selector: The login page includes a "Demo Mode - Select Role" dropdown at the top of the form. This dropdown lists all 24 roles.
  2. Instant Access: When a user selects a role from the demo dropdown and clicks "Start Demo", the system creates a temporary session with the demo_user role and a metadata flag indicating the selected demo role.
  3. Sample Data: The demo environment contains realistic but fictional sample data, including 25 sample clients, 15 staff members, 50 shifts, and financial records spanning 3 months.
  4. Read-Only Enforcement: All write operations (create, update, delete) are blocked at both the UI level (disabled buttons, hidden forms) and the database level (RLS policies reject writes from demo_user).
  5. Automatic Expiry: Demo sessions expire after 60 minutes. A countdown timer is displayed in the topbar to remind the user of the remaining time.
  6. No Persistence: Any changes attempted in demo mode are not persisted. The demo database is reset to its baseline state every 24 hours via a scheduled Python script.

4.7.2 Demo Mode Visual Indicators

When a user is in demo mode, several visual indicators make it clear that they are not operating on live data:

  • An orange banner at the top of every page displays: "DEMO MODE - This is a preview environment with sample data. No changes will be saved."
  • The sidebar brand text shows "NDSS CRM [DEMO]" instead of "NDSS CRM".
  • All action buttons (Create, Edit, Delete) are visually dimmed and show a tooltip: "Disabled in demo mode".
  • A countdown timer in the topbar shows the remaining session duration.
NDSS CRM - Demo Mode Banner
DEMO MODE - Preview environment with sample data. No changes will be saved. 47:23 remaining
Dashboard [DEMO]
Demo: Operations Manager
DM
Fig 4.3 - Demo mode displays an orange banner with countdown timer and a role indicator badge in the topbar.

4.8 Security Best Practices

NDSS CRM enforces multiple layers of security to protect user accounts, participant data, and organisational information. The following best practices are implemented by default and should be maintained by all system administrators.

4.8.1 Password Policies

All user passwords must meet the following complexity requirements:

Requirement Value Notes
Minimum Length8 characters12+ characters recommended for admin roles
Uppercase LetterAt least 1A-Z
Lowercase LetterAt least 1a-z
Numeric DigitAt least 10-9
Special CharacterAt least 1!@#$%^&*()_+-=[]{}|;':",.<>?/
Password HistoryLast 5Cannot reuse any of the last 5 passwords
Maximum Age90 daysUsers are prompted to change their password every 90 days
Common Password CheckEnabledPasswords are checked against a list of 10,000 commonly used passwords

4.8.2 Two-Factor Authentication (2FA)

NDSS CRM supports two-factor authentication using Time-based One-Time Passwords (TOTP). 2FA adds a second verification step after the password, requiring users to enter a 6-digit code from an authenticator app (e.g., Google Authenticator, Microsoft Authenticator, Authy).

2FA Configuration

Setting Default Value Description
2FA AvailabilityAll roles2FA can be enabled by any user from their profile settings
2FA EnforcementAdmin roles onlyMaster Admin and Administrator roles are required to enable 2FA. Other roles are encouraged but not required.
Recovery Codes10 codes generatedSingle-use backup codes provided when 2FA is first enabled, for account recovery if the authenticator device is lost
TOTP AlgorithmSHA-1, 6 digits, 30sStandard TOTP parameters compatible with all major authenticator apps
Grace Period14 daysAfter 2FA enforcement is enabled, users have 14 days to set up 2FA before their account is restricted

4.8.3 Account Lockout

To prevent brute-force password attacks, NDSS CRM implements progressive account lockout:

Failed Attempts Action Recovery
1 - 4Warning message displayedUser can immediately retry
5CAPTCHA requiredUser must complete CAPTCHA before retrying
8Account locked for 15 minutesAutomatic unlock after 15 minutes, or admin can unlock manually
12Account locked for 1 hourAutomatic unlock after 1 hour, or admin can unlock manually
15+Account suspendedOnly a Master Administrator can reactivate the account

4.8.4 Audit Logging

All authentication events are recorded in the auth_audit_log table for security monitoring and compliance:

Event Type Data Recorded
login_successUser ID, email, role, IP address, user agent, timestamp
login_failureEmail attempted, failure reason, IP address, user agent, timestamp
logoutUser ID, session duration, timestamp
password_reset_requestEmail, IP address, timestamp
password_changedUser ID, timestamp
2fa_enabledUser ID, timestamp
2fa_disabledUser ID, disabled by (self or admin), timestamp
account_lockedUser ID, reason, lock duration, timestamp
account_unlockedUser ID, unlocked by (auto or admin), timestamp
role_changedUser ID, old role, new role, changed by, timestamp
session_expiredUser ID, expiry reason (timeout/token expiry), timestamp

4.8.5 Security Recommendations for Administrators

Administrator Checklist
  • Ensure all master_admin and administrator accounts have 2FA enabled.
  • Review the auth audit log weekly for suspicious login attempts or patterns.
  • Deactivate accounts for staff who have left the organisation within 24 hours of their departure.
  • Conduct quarterly access reviews to ensure roles are still appropriate for each user.
  • Keep the number of master_admin accounts to a maximum of 2-3 per organisation.
  • Use unique, strong passwords - never share login credentials between users.
  • Ensure all users access NDSS CRM over HTTPS only. The platform enforces HTTPS redirects by default.
  • Review and revoke any unused invitation codes monthly.
Further Reading

For the complete technical architecture behind the authentication system, see Chapter 3: Architecture & Technical Stack. For advanced security configurations, encryption at rest, and data protection policies, see Chapter 20: Security & Data.