Naalya Handbook

Authentication across the platforms

How the schools API issues tokens, how the Hub stores them, and what the public website does instead.

Use this page to see the whole sign-in path. For guards and CASL in more detail, see Auth and permissions in the API section. For how the Hub stores tokens in the browser, see Education Hub authentication.

Status. Read from source on 11 November 2026. The flows were not executed against a running stack.

Schools API

AuthModule in apps/server/src/app/auth/auth.module.ts registers global guards in this order: JwtAuthGuard, UserTypeGuard, SystemRoleGuard, PermissionsGuard, FeatureFlagGuard.

AuthController is mounted at auth, so routes are under /api/v1/auth. JwtStrategy reads ExtractJwt.fromAuthHeaderAsBearerToken(). The server calls cookieParser(), but this strategy does not read a session cookie.

Method and pathAuth on the routeWhat the handler does
POST /api/v1/auth/login@Public(), then AuthGuard('local')LocalStrategy uses the field identifier. AuthService.loginLocal returns AuthTokensResponseDto (access and refresh tokens in the body). operationId login.
POST /api/v1/auth/registerPublicSelf-registration for a guardian or guest, as the operation description states. operationId register.
POST /api/v1/auth/refreshPublicBody field refreshToken. AuthService.refreshTokens returns a new pair.
POST /api/v1/auth/logoutBearer access tokenAuthService.logout. The description says it revokes refresh tokens for the current user.
POST /api/v1/auth/impersonateBearer, and Action.IMPERSONATE on Resource.USERStarts impersonation.
POST /api/v1/auth/impersonate/stopBearerEnds impersonation.
GET /api/v1/auth/microsoftPublicStarts Microsoft OAuth.
GET /api/v1/auth/microsoft/callbackPublicRedirects to the frontend with accessToken and refreshToken on the query string.
GET /api/v1/auth/meBearerCurrent user.
POST /api/v1/auth/otp/lookup, request, verifyPublic, throttledOne-time code. Details below.
POST /api/v1/auth/magic/lookup, request, verifyPublic, throttledMagic link for guardians and guests. Details below.
POST /api/v1/auth/admission-capturePublicUsed by the Hub as startAdmissionCapture.

There is no Google OAuth strategy in the files this audit opened. A handbook page that tells you to sign in with Google is wrong. The Hub’s Microsoft path and the password, OTP, and magic-link paths are the ones in source.

Staging limits

API main d0fbb403 does not have these four limits. They are on API staging 6308a8a1053694b8f123bad29c69aec400b8c1ec (merge of PR #683, 28 November 2026, 08:19 GMT). Not on main. No new environment variable. The route tests were not run. A merge to staging is not a running deploy. A full bucket can answer 429.

RouteGuardLimit
POST /api/v1/auth/loginPersonThrottlerGuard, before the password is checked10 per 60 seconds
POST /api/v1/auth/registerClientIpThrottlerGuard20 per 60 seconds
GET /api/v1/transactions/:referenceClientIpThrottlerGuard120 per 60 seconds
POST /api/v1/transactions/:reference/request-mobile-paymentClientIpThrottlerGuard5 per 60 seconds

Login is counted per person. The other three are counted per client IP. auth.controller.ts and transaction.controller.ts were read at that commit.

On that same staging commit, minting a token refuses a deactivated account or a profile whose isActive is false, with 403 This account is suspended. That includes refresh, except an impersonation mint and a refresh of an impersonation token. An access token already issued is not revoked. Detail is on Auth & Permissions.

One-time codes

OtpAuthController is auth/otp. Every method is @Public() and returns 200 on success.

Method and pathoperationIdThrottleBody
POST /api/v1/auth/otp/lookuplookupLoginOtpClientIpThrottlerGuard, 120 per 60 secondsidentifier (required string). Optional schoolId UUID.
POST /api/v1/auth/otp/requestrequestLoginOtpPersonThrottlerGuard, 5 per 60 secondsSame body.
POST /api/v1/auth/otp/verifyverifyLoginOtpPersonThrottlerGuard, 10 per 60 secondsidentifier, optional schoolId, code (exactly 6 digits).

With schoolId, lookup matches an active account on that school, any user type. Without schoolId, the operation text says only platform operators match. A miss returns found: false. It does not error. A hit returns name and a masked email.

request emails a code. LoginOtpService throws 404 No account found for this identifier when nothing matches, and 403 Account is deactivated when the account exists and isActive is false. That is different from magic link, below. verify returns AuthTokensResponseDto. The controller documents 401 Invalid or expired code.

On API staging 6308a8a1 only, wrong codes are also counted per account. After 30, request and verify both refuse before they send or check a code, with 429 Too many wrong codes. Please try again tomorrow or sign in another way. The Redis key is auth:otp:failures: plus the user id, and it lives for 24 hours from the first count in that window. A correct code deletes it. The per-code cap on main is unchanged. login-otp.service.ts and login-otp.store.ts were read. The OTP test was not run.

PlatformAdminSeedService creates each allowed SUPERADMIN_EMAILS address as a school-less platform_admin. Those operators sign in with the OTP routes above. Magic link does not include platform_admin. No address was copied and the seed was not run. The skip rules are on School operations.

MagicAuthController is auth/magic. Eligible types are guardian and guest only (MAGIC_LINK_USER_TYPES). The only channel is whatsapp. Staff, students, and platform admins do not get a link from this controller.

Method and pathoperationIdThrottleBodySuccess
POST /api/v1/auth/magic/lookuplookupLoginMagicIP guard, 120 per 60 secondsidentifier, schoolId (UUID). Optional channel (defaults to whatsapp).200. found, channels.whatsapp, retryAfterSeconds. A miss is found: false. It does not error.
POST /api/v1/auth/magic/requestrequestLoginMagicperson guard, 5 per 60 secondsSame body.200. message, expiresInMinutes, retryAfterSeconds.
POST /api/v1/auth/magic/verifyverifyLoginMagicperson guard, 10 per 60 secondstoken (required string). POST only.200 AuthTokensResponseDto.

identifier may be an email, an access code, or a phone. schoolId is required. The account must be active, an eligible type, and on that school. An inactive account takes the same path as a miss: lookup returns found: false, and request throws 404 No account found for this identifier. The controller’s Swagger decorator also lists 403 Account is deactivated. MagicLinkService.requestLink does not throw ForbiddenException. Trust the service until that decorator and the service agree.

Other errors from requestLink: 429 while the cooldown remains (the message includes the remaining seconds), 503 when WhatsApp cannot deliver (WhatsApp sign-in is unavailable right now. Ask the school to reconnect WhatsApp.), 502 Could not send the sign-in link. Try again. when sending fails. verify returns 401 Invalid or expired link for a bad, used, or expired token, and for an account that is no longer eligible.

The raw token is 32 random bytes, base64url. Redis stores a SHA-256 hex hash. Defaults in envSchema are MAGIC_LINK_EXPIRY_MINUTES 5 and MAGIC_LINK_RESEND_COOLDOWN_SECONDS 60. The URL built before shortening is {frontend.url}/{schoolReference}/auth/magic?token=..., with an optional redirect query. frontend.url is the shaped config key the service reads. The short link’s expiry in this method is one day. The token’s Redis TTL is the five-minute default. A late tap can hit the page after the token is gone.

Do not put a real token, phone number, or WhatsApp body in a ticket. The service redacts the link in the audit text as [sign-in link, not kept].

Unexecuted. Placeholders only.

curl --silent --show-error \
  --request POST 'https://api.example.com/api/v1/auth/magic/lookup' \
  --header 'content-type: application/json' \
  --data '{"identifier":"amal@example.com","schoolId":"YOUR_SCHOOL_ID"}'

Access tokens default to JWT_ACCESS_TOKEN_EXPIRATION_MS of 900000 (15 minutes) when the variable is unset. Refresh tokens default to JWT_REFRESH_TOKEN_EXPIRATION_MS of 604800000 (7 days). Impersonation refresh defaults to 3600000 (1 hour). REFRESH_TOKEN_RETENTION_DAYS defaults to 30. Those are schema defaults in envSchema, not a measured lifetime from a running server.

The committed Railway settings in .railway/variables.ts (APP.settings) set JWT_ACCESS_TOKEN_EXPIRATION_MS to 86400000 (24 hours) and repeat the 7-day refresh and 30-day retention. That file is what staging and production are configured to apply. It is not a reading of the live variable list. Local boot without the variable still gets the 15-minute schema default.

401, 403, and 404

These are different failures. The API does not hide existence behind a single status.

StatusWhen the audited guards throw itMessage the guard sets
401JwtAuthGuard has no usable tokenAuthentication required. or, when the passport reason is jwt expired, Session has expired. Please sign in again.
401ApiKeyGuardAPI key required. or Invalid API key.
403PermissionsGuard and @RequirePermissions failsInsufficient permissions
403UserTypeGuardYou do not have the required user type to access this resource
403SystemRoleGuardYou do not have the required role to access this resource
403ApiKeyGuardThis key kind is not accepted here. or Origin not allowed for this key.
404FeatureFlagGuard when the feature is disabledFeature not enabled: ... with error: 'FEATURE_DISABLED'. A platform admin skips the check

FeatureFlagGuard returns immediately on @Public() routes, before it reads @RequireFeature. A public method on a controller that also has @RequireFeature does not get that feature check. SchoolPayInboundWebhookController is one case: the webhook method is @Public().

PermissionsGuard allows the request when the route sets no required permissions. That is not the same as “every route is public”. JwtAuthGuard still runs unless the route is @Public().

API keys

ApiKeyController is at api-keys. Clients send x-api-key (API_KEY_HEADER). Kinds are secret and publishable in api-key.types.ts. The default accepted kind is secret. A publishable key must send an Origin that is in allowedOrigins. The stored value is a SHA-256 hash (keyHash). createApiKey says the raw key is returned once. These are school keys, not OAuth scopes. No scope list was found.

Clinic API auth

apps/ehr does not share the Hub JWT. GET /api/v1/auth/microsoft sets an HttpOnly cookie ehr_pkce (path /api/v1/auth/microsoft, 10 minutes). The callback redirects to the clinic web app with tokens in the URL fragment, according to the operation description. POST /api/v1/auth/refresh takes the refresh token in the body. The description says reusing an old refresh token signs the whole session out. GET /api/v1/auth/keys is a public JWKS (operationId authKeys) for PowerSync. GET /api/v1/auth/me is bearer.

Education Hub

The Hub is a browser client of the schools API.

  1. useAuth in src/components/providers/auth.provider.tsx persists token and refreshToken to localStorage. The persist name is tokenKey.
  2. tokenKey in src/services/api/api.instance.ts is the string auth-token.
  3. The Axios request interceptor sets Authorization: Bearer ${token}. withCredentials is true. The base URL is import.meta.env.VITE_API_URL.
  4. On 401, except for URLs containing /auth/refresh or /auth/login, the client posts { refreshToken } to {VITE_API_URL}/api/v1/auth/refresh and stores the new pair. A navigator.locks lock named auth-refresh coordinates tabs. A failed refresh clears the store.
  5. AuthQuery.getMe returns null without a request when both tokens are missing. A 401 or 404 from that call clears the tokens.

/auth/callback reads accessToken and refreshToken from the search params, writes them, clears the query cache, and routes with getUserDestination.

UserType in the generated bus (src/services/api/_generated/bus/user.ts) is 'student' | 'staff' | 'guardian' | 'guest' | 'platform_admin'. There is no user type named operator. The screen at /auth/operator is a route.

getUserDestination sends platform_admin to /platform/hub, a guest to /guest, a student to /student/hub, and a guardian to /guardian/hub. Staff with school-administration read or manage on all go to /staff-hub/school/hub. Other staff go to a campus hub, or to /staff-hub/no-campus when they have no campus.

Route guards are client beforeLoad checks. Several authenticated layouts set ssr: false. The guest layout file that was read does not call requirePermission. The student layout requires Feature.STUDENT_PORTAL and userType: 'student'. Missing profile.campusId redirects to /student/no-campus. A failed permission check redirects to /403. No user redirects to /.

useMeetsRequirement returns true while the user query is still loading, so a control can appear and then disappear. Can hides children. It does not redirect. The route guard’s role compare is case-insensitive. hasRole, which Can uses, compares r.name === roleName and is case-sensitive.

Website

The public site has no end-user session. app/routes.ts has no login route. /settings toggles a local seasonal effect. It is not an account.

Chat and enquiries send x-api-key. They do not send the Hub bearer token. The generated Axios instance can attach auth-token from localStorage, and a search of the website tree found that key only in api.instance.ts. Do not describe the marketing site as signed-in product.

Hub links are built from VITE_EDUCATION_HUB_URL (fallback https://hub.naalyaschools.ac.ug in app/config/site.ts) plus the reference naalya-secondary-school. Apply links append /apply.

Worked request

This example was not executed. It shows the JSON shape the login DTO and the bearer strategy imply. Replace the host and the identifier with values from a development database you are allowed to use.

curl --silent --show-error \
  --request POST 'https://api.example.com/api/v1/auth/login' \
  --header 'content-type: application/json' \
  --data '{"identifier":"ada@example.com","password":"replace-me"}'

A successful body is the token DTO, not a Set-Cookie session. Later calls:

curl --silent --show-error \
  --request GET 'https://api.example.com/api/v1/auth/me' \
  --header 'authorization: Bearer YOUR_ACCESS_TOKEN'

YOUR_ACCESS_TOKEN is the access token from the login response. Do not paste a real token into a doc, a ticket, or a screenshot.

An expired access token yields 401 with Session has expired. Please sign in again. The Hub then tries the refresh route. A caller that is authenticated but not allowed yields 403 with Insufficient permissions, when the route declared permissions.

Sources

  • Naalya-API apps/server/src/app/auth/auth.module.ts, auth.controller.ts AuthController, otp/otp-auth.controller.ts, otp/login-otp.service.ts, magic/magic-auth.controller.ts, magic/magic-link.service.ts, magic/magic-link.channels.ts, platform/platform-admin-seed.service.ts, jwt.strategy.ts JwtStrategy, jwt-auth.guard.ts JwtAuthGuard.handleRequest, permissions.guard.ts, user-type.guard.ts, system-role.guard.ts, feature-flag.guard.ts, api-key.guard.ts ApiKeyGuard, libs/shared/src/config/env.config.ts, .railway/variables.ts APP
  • Naalya-API apps/ehr/src/auth/auth.controller.ts
  • Education-Hub src/components/providers/auth.provider.tsx useAuth, src/services/api/api.instance.ts, src/queries/auth/auth.query.ts AuthQuery, src/routes/auth/callback.tsx, src/lib/auth/get-user-destination.ts getUserDestination, src/lib/permissions/permissions.guard.ts requirePermission
  • Naalya-Website app/routes.ts, app/config/site.ts HUB_URL

On this page