Security¶
Security utilities for authentication and authorisation.
This module provides cryptographic functions for: - Password hashing and verification (Argon2) - JWT token creation and decoding (HS256) - TOTP two-factor authentication (RFC 6238) - CSRF token generation and validation
All functions use industry-standard algorithms and handle secrets securely.
hash_password ¶
hash_password(p)
Hash Password with Argon2.
Hashes a plain text password using the Argon2id algorithm, which is recommended by OWASP for password storage. Uses argon2-cffi's default parameters (time_cost=3, memory_cost=65536, parallelism=4).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
str
|
Plain text password to hash. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Argon2 hash string in PHC format, suitable for database storage. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If password is empty or None. |
Source code in app/security.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
verify_password ¶
verify_password(p, h)
Verify Password Against Hash.
Verifies a plain text password against an Argon2 hash stored in the database. Uses constant-time comparison to prevent timing attacks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
str
|
Plain text password to verify. |
required |
h
|
str
|
Argon2 hash from database (PHC format). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if password matches hash, False otherwise. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If password or hash is empty. |
Source code in app/security.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
create_access_token ¶
create_access_token(sub, roles, token_version=0)
Create JWT Access Token.
Creates a short-lived JWT access token containing the user's identity and assigned roles. The token is signed with HS256 and expires after ACCESS_TTL_MIN minutes (default: 15). Used for authenticating API requests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sub
|
str
|
Subject (username) for the token. |
required |
roles
|
list[str]
|
List of role names assigned to the user (e.g., ["Clinician"]). |
required |
token_version
|
int
|
User's token version for session invalidation. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Encoded JWT access token valid for ACCESS_TTL_MIN minutes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If subject is empty. |
Source code in app/security.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
create_refresh_token ¶
create_refresh_token(sub, token_version=0)
Create JWT Refresh Token.
Creates a long-lived JWT refresh token used to obtain new access tokens without requiring the user to log in again. Expires after REFRESH_TTL_DAYS (default: 7 days). Stored in HTTP-only cookie with restricted path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sub
|
str
|
Subject (username) for the token. |
required |
token_version
|
int
|
User's token version for session invalidation. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Encoded JWT refresh token valid for REFRESH_TTL_DAYS days. |
Source code in app/security.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
decode_token ¶
decode_token(tok)
Decode and Verify JWT Token.
Decodes a JWT token and verifies its signature using the configured JWT_SECRET. Also validates the token hasn't expired. Used by authentication middleware to extract user identity from access and refresh tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tok
|
str
|
JWT token string to decode. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
Decoded token payload containing 'sub' (username), 'roles', 'exp' (expiration), and other claims. |
Raises:
| Type | Description |
|---|---|
JWTError
|
If token signature is invalid. |
ExpiredSignatureError
|
If token has expired. |
JWTClaimsError
|
If token claims are invalid. |
Source code in app/security.py
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
create_csrf_token ¶
create_csrf_token(username)
Create CSRF Protection Token.
Generates a CSRF token for protecting state-changing operations against cross-site request forgery attacks. The token is signed with the JWT_SECRET and tied to the user's identity. Must be included in X-CSRF-Token header for POST/PUT/PATCH/DELETE requests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
Username to tie the token to. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
URL-safe CSRF token signed with JWT_SECRET. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If username is empty. |
Source code in app/security.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
make_csrf ¶
make_csrf(sub)
Create CSRF Token (Legacy).
Legacy alias for create_csrf_token. Generates a CSRF token signed with the user's identity. Maintained for backward compatibility with existing code that uses this function name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sub
|
str
|
Subject (username) to sign the token with. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
URL-safe CSRF token. |
Source code in app/security.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 | |
verify_csrf ¶
verify_csrf(token, sub)
Verify CSRF Token.
Verifies a CSRF token matches the expected username. Used by the require_csrf dependency to protect state-changing operations. Returns False for any verification failure (invalid signature, wrong subject).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
CSRF token from X-CSRF-Token header. |
required |
sub
|
str
|
Expected subject (username) from JWT. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if token is valid and subject matches, False otherwise. |
Source code in app/security.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
generate_totp_secret ¶
generate_totp_secret()
Generate TOTP Secret.
Generates a new cryptographically random TOTP secret for two-factor authentication. The secret is Base32-encoded for compatibility with authenticator apps like Google Authenticator, Authy, etc.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Base32-encoded secret (32 characters). |
Source code in app/security.py
245 246 247 248 249 250 251 252 253 254 255 | |
generate_totp_provision_uri ¶
generate_totp_provision_uri(username, secret, issuer='Quill')
Generate TOTP Provisioning URI.
Creates an otpauth:// URI for QR code generation, compatible with authenticator apps. The URI contains the secret, username, and issuer information. Users scan this QR code to add the account to their app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
User's username for labeling the TOTP entry. |
required |
secret
|
str
|
Base32-encoded TOTP secret from generate_totp_secret(). |
required |
issuer
|
str
|
Application name displayed in authenticator app (default: "Quill"). |
'Quill'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
otpauth://totp/... URI for QR code generation. |
Source code in app/security.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
verify_totp_code ¶
verify_totp_code(secret, code)
Verify TOTP Code.
Verifies a 6-digit TOTP code against the user's secret. Uses RFC 6238 time-based one-time password algorithm with 30-second time steps. Allows for clock drift of ±1 time step (default pyotp behavior).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
Base32-encoded TOTP secret from database. |
required |
code
|
str
|
6-digit TOTP code from authenticator app. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if code is valid for current time window, False otherwise. |
Source code in app/security.py
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
totp_provisioning_uri ¶
totp_provisioning_uri(secret, username, issuer=None)
Return an otpauth:// URI which can be converted to QR code by the frontend.
Source code in app/security.py
300 301 302 303 304 305 306 307 308 309 | |
create_jwt_with_competencies ¶
create_jwt_with_competencies(sub, roles, competencies, token_version=0)
Create JWT Access Token with CBAC Competencies.
Creates a short-lived JWT access token containing the user's identity, assigned roles, and resolved competencies. This extends create_access_token to include CBAC (Competency-Based Access Control) information in the token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sub
|
str
|
Subject (username) for the token. |
required |
roles
|
list[str]
|
List of role names assigned to the user (e.g., ["Clinician"]). |
required |
competencies
|
list[str]
|
List of competency IDs user has (resolved from base profession). |
required |
token_version
|
int
|
User's token version for session invalidation. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Encoded JWT access token with competencies, valid for ACCESS_TTL_MIN minutes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If subject is empty. |
Source code in app/security.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | |
decode_jwt_with_competencies ¶
decode_jwt_with_competencies(tok)
Decode and Verify JWT Token with Competencies.
Decodes a JWT token and verifies its signature, extracting user identity, roles, and competencies. This is a wrapper around decode_token that documents the expected payload structure for CBAC tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tok
|
str
|
JWT token string to decode. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
Decoded token payload containing 'sub' (username), 'roles', 'competencies', 'exp' (expiration), and other claims. |
Raises:
| Type | Description |
|---|---|
JWTError
|
If token signature is invalid. |
ExpiredSignatureError
|
If token has expired. |
JWTClaimsError
|
If token claims are invalid. |
Source code in app/security.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | |
create_invite_token ¶
create_invite_token(patient_id, email, user_type, *, ttl_days=7)
Create a JWT invite token for external user access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patient_id
|
str
|
FHIR Patient resource ID. |
required |
email
|
str
|
Invitee email address. |
required |
user_type
|
str
|
|
required |
ttl_days
|
int
|
Token validity in days (default 7). |
7
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Signed JWT invite token. |
Source code in app/security.py
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | |
decode_invite_token ¶
decode_invite_token(tok)
Decode and verify an invite JWT.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
Payload with |
Raises:
| Type | Description |
|---|---|
JWTError
|
Invalid or expired token. |
Source code in app/security.py
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
create_password_reset_token ¶
create_password_reset_token(email)
Create a time-limited password reset token.
Generates a signed, time-limited token tied to the user's email. The token expires after PASSWORD_RESET_TTL_MIN minutes (default 30).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
email
|
str
|
User's email address. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
URL-safe signed token. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If email is empty. |
Source code in app/security.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
verify_password_reset_token ¶
verify_password_reset_token(token)
Verify a password reset token and return the email.
Checks the token signature and expiry. Returns the email if valid, None if the token is invalid or expired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
Password reset token from email link. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The email address if valid, None otherwise. |
Source code in app/security.py
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | |