User
Technical reference for the User model in Care EMR. See the user concept for the plain-language view.
Source: care/users/models.py, care/emr/resources/user/spec.py, care/emr/api/viewsets/user.py, care/facility/models/patient.py, care/emr/resources/mfa/spec.py, care/users/migrations/0028_multiple_changes.py
The Django model is the storage layer. The Pydantic resource specs in care/emr/resources/user/spec.py are the API layer. They define the enums, the validation, the shape of the communication and qualifications JSON fields, and the separate request and response schemas.
Models
| Model | Purpose |
|---|---|
User | Care account: sign-in, profile, languages, qualifications, notification data, MFA data and preferences |
UserFlag | Feature flag for one User |
PlugConfig | Slug-keyed JSON configuration |
MobileOTP | One-time password issued for a phone number. Defined in care/facility/models/patient.py |
The base class sets the audit fields of each model:
Userextends Django'sAbstractUser.MobileOTPextendsBaseModel.UserFlagextendsBaseFlag, aBaseModelsubclass that adds aflagfield and asave()that validates the flag name and clears the flag caches.PlugConfigextends plaindjango.db.models.Model, so it has no audit or soft-delete fields.
Migration 0028_multiple_changes removed qualification, doctor_experience_commenced_on, doctor_medical_council_registration, weekly_working_hours, video_connect_link, verified, home_facility and skills from User.
The same migration added communication, qualifications and role_org_ids to User, and deleted the Skill and UserSkill models.
The API field qualification now reads and writes the new qualifications list.
User fields
User inherits its other fields from AbstractUser. The specs use first_name, last_name, email, password, last_login and is_superuser from it. The fields below are the Care additions.
Queries run through CustomUserManager, which drops rows with deleted=True. get_entire_queryset() returns all rows.
Identity & profile
| Field | Type | Notes |
|---|---|---|
external_id | UUIDField | Unique, indexed. Read specs return it as id |
username | CharField(150) | Unique. The model validator UsernameValidator (4–16 characters, lowercase, dots allowed) does not run on the API path. On create, the API enforces ^[a-zA-Z0-9_-]{3,}$ and uniqueness across all users, deleted users included. The users API looks users up by username |
user_type | CharField(100), nullable | No user spec reads or writes it. create_superuser() sets it to "administrator" |
prefix | CharField(10), nullable | Optional in the specs, max length 10 |
suffix | CharField(50), nullable | Optional in the specs, max length 50 |
gender | CharField(100), nullable | The write specs bind it to GenderChoices and require it. See GenderChoices values |
old_gender | IntegerField, nullable | Legacy integer choices: 1 Male, 2 Female, 3 Non-binary. See GENDER_CHOICES values. No user spec exposes it |
date_of_birth | DateField, nullable | Returned by CurrentUserRetrieveSpec |
profile_picture_url | CharField(500), nullable | Read specs return the value of read_profile_picture_url(). The profile_picture action uploads or deletes the picture, for the user or a superuser only |
created_by | FK → User (self, SET_NULL), nullable | related_name="users_created". Set to the requesting user on create. UserRetrieveSpec returns it as a cached UserSpec dict, or null |
is_service_account | BooleanField | Default False. Settable on create. Returned by UserRetrieveSpec. The list endpoint filters on it, with default false |
deleted | BooleanField | Default False. Soft-delete flag, returned by UserSpec. A delete (superuser only) sets it for a user who has signed in, and removes a user who never signed in |
Contact
| Field | Type | Notes |
|---|---|---|
phone_number | CharField(14) | mobile_or_landline_number_validator. In REQUIRED_FIELDS. Required in the specs, max length 14. On create, it must not belong to another non-deleted user |
alt_phone_number | CharField(14), nullable | mobile_validator. Returned by CurrentUserRetrieveSpec |
Languages & qualifications
| Field | Type | Notes |
|---|---|---|
communication | JSONField | Default []. A list of UserCommunicationSpec entries. The write specs replace it only when the request includes communication |
qualifications | JSONField | Default []. A list of UserQualificationSpec entries. The API field is qualification (singular) on read and write. The write specs replace it only when the request includes qualification |
Organization & roles
| Field | Type | Notes |
|---|---|---|
geo_organization | FK → emr.Organization (SET_NULL), nullable | The write specs take a UUID4 and resolve it to an Organization with org_type="govt", else 404. In UserBaseSpec.__exclude__. UserRetrieveSpec returns it as an OrganizationReadSpec dict |
cached_role_orgs | JSONField, nullable | Default null. No write spec accepts it. Read specs return role_orgs from get_cached_role_orgs() |
role_org_ids | ArrayField(IntegerField) | Default []. The ids of the user's responsibility (org_type="role") organizations, filled by populate_role_orgs_array(). No spec reads or writes it |
Notifications, MFA & preferences
| Field | Type | Notes |
|---|---|---|
pf_endpoint | TextField, nullable | Notification data. Returned by CurrentUserRetrieveSpec |
pf_p256dh | TextField, nullable | Notification data. Returned by CurrentUserRetrieveSpec |
pf_auth | TextField, nullable | Notification data. Returned by CurrentUserRetrieveSpec |
totp_secret | TextField, nullable | TOTP secret. The MFA setup creates it, and disabling MFA clears it. No spec returns it |
mfa_settings | JSONField | Default {}. See mfa_settings shape. No write spec accepts it. UserSpec returns the boolean mfa_enabled from is_mfa_enabled() |
preferences | JSONField | Default {}. Written by POST /api/v1/users/set_preferences/. Returned by CurrentUserRetrieveSpec. See preferences |
REQUIRED_FIELDS = ["email", "phone_number"].
mfa_settings shape
The TOTP endpoints and the MFA login endpoint maintain this field.
| Key | Type | Notes |
|---|---|---|
totp.enabled | bool | True after the user verifies a correct code |
totp.backup_codes | list | 10 codes of 8 digits, created on enable. Regenerate replaces all of them; disable empties the list |
totp.backup_codes[].code | str | Checked with Django check_password at sign-in |
totp.backup_codes[].used | bool | A used code is refused ("Invalid or already used backup code") |
totp.backup_codes[].used_at | ISO datetime string | Set when the code is used |
preferences
preferences maps a preference name to its value. POST /api/v1/users/set_preferences/ stores one named preference on the signed-in user only.
The deployment setting PREFERENCE_SCHEMA validates preference values. By default it defines only facility_quick_links, so other preferences are stored without schema validation.
The Theme tab of the profile saves the appearance preference this way.
Nested JSON shapes
UserCommunicationSpec (communication[])
| Field | Type | Required | Notes |
|---|---|---|---|
language | UserLanguageSpec | yes | See below |
preferred | bool | yes | No limit on the number of preferred entries |
proficiency | CEFRLevel or null | no | Default null. See CEFRLevel values |
UserLanguageSpec (communication[].language)
| Field | Type | Required | Notes |
|---|---|---|---|
code | str | yes | Matches ^[a-z]{3}$ and must be an ISO 639-3 code known to pycountry ("Invalid ISO 639-3 language code") |
system | Literal | yes | Always "urn:iso:std:iso:639:-3" |
UserQualificationSpec (qualifications[])
| Field | Type | Required | Notes |
|---|---|---|---|
degree | UserDegreeSpec | yes | code and system must match an entry of USER_QUALIFICATION_DEGREES ("Degree must be one of the available qualifications") |
issuer | str | yes | Issuing authority |
registration_number | str | yes | Registration number |
meta | dict | no | Default {} |
UserDegreeSpec (qualifications[].degree)
| Field | Type | Required | Notes |
|---|---|---|---|
code | str | yes | Not empty |
system | str | yes | Not empty |
USER_QUALIFICATION_DEGREES is a deployment setting. GET /api/v1/users/degrees/ returns it. By default it lists MBBS, MD, MS, BDS and B.Sc. Nursing.
Enum values
GenderChoices values
Bound to gender on UserUpdateSpec and UserCreateSpec. Defined in care/emr/resources/patient/spec.py and shared with the patient resource.
| Value |
|---|
male |
female |
non_binary |
transgender |
create_superuser() sets gender="non_binary".
GENDER_CHOICES values
Legacy integer choices of old_gender, defined in care/users/models.py. They are separate from GenderChoices, and no user spec exposes old_gender.
| Value | Label |
|---|---|
1 | Male |
2 | Female |
3 | Non-binary |
CEFRLevel values
Bound to UserCommunicationSpec.proficiency.
| Value | Label in the user form |
|---|---|
A1 | A1 · Beginner |
A2 | A2 · Elementary |
B1 | B1 · Intermediate |
B2 | B2 · Upper intermediate |
C1 | C1 · Advanced |
C2 | C2 · Proficient |
LoginMethod values
Bound to MFALoginRequest.method in care/emr/resources/mfa/spec.py.
| Value | Meaning |
|---|---|
totp | One-time TOTP code, verified against totp_secret |
backup | Single-use backup code from mfa_settings |
Resource specs (API schema)
UserBaseSpec extends EMRResource and sets __model__ = User and __exclude__ = ["geo_organization"].
| Spec class | Role | Fields / behaviour |
|---|---|---|
UserBaseSpec | shared base | id, first_name, last_name, phone_number (max 14), prefix (max 10, optional), suffix (max 50, optional) |
UserUpdateSpec | write · update | Base + gender (GenderChoices, required), geo_organization (UUID4, optional), communication (list[UserCommunicationSpec]), qualification (list[UserQualificationSpec]). Writes communication and qualifications only when the request includes them. Resolves geo_organization to a government organization (404 otherwise) |
UserCreateSpec | write · create | Extends UserUpdateSpec + password (optional), username, email, is_service_account (default False), role_orgs (required list[UserRoleOrgCreateSpec]). Validates username, phone_number, email and password (see below). Stores role_orgs on the instance for the view, and calls set_password() |
UserRoleOrgCreateSpec | write · nested | organization: UUID4, role: UUID4. One responsibility and role for the new user |
UserCommunicationSpec, UserLanguageSpec | write/read · nested | See Nested JSON shapes |
UserQualificationSpec, UserDegreeSpec | write/read · nested | See Nested JSON shapes |
UserSpec | read · list | Base + last_login, profile_picture_url, gender, username, mfa_enabled (default False), phone_number, deleted (default False), role_orgs (dict), communication, qualification. @cacheable(use_base_manager=True): cached, and resolves deleted users. Sets id from external_id, and reads qualification from the qualifications column |
UserRetrieveSpec | read · detail | Extends UserSpec + geo_organization (dict), created_by (dict or null), email, flags (list[str]), is_service_account. Fills flags from get_all_flags() |
CurrentUserRetrieveSpec | read · signed-in user | Extends UserRetrieveSpec + is_superuser, alt_phone_number, date_of_birth, pf_endpoint, pf_p256dh, pf_auth, organizations (list[dict]), facilities (list[dict]), permissions (list[str]), preferences (dict). For a non-superuser, organizations lists the organizations that the user is linked to. facilities lists the facilities where the user is in a department, except deleted facilities. It has no qualification, doctor_*, weekly_working_hours or verified field |
PublicUserReadSpec | read · public | Base + last_login, profile_picture_url, gender, username, role_orgs (list[dict]) |
Password-reset DTOs
The email password reset uses plain pydantic BaseModel request and response DTOs, also in user/spec.py. They are not EMRResource classes and have no model binding.
| DTO | Shape | Used by |
|---|---|---|
ResetPasswordRequestTokenRequest | { username: str } | Request of POST /api/v1/password_reset/ |
ResetPasswordCheckRequest | { token: str } | Request of POST /api/v1/password_reset/check/ |
ResetPasswordConfirmRequest | { token: str, password: str } | Request of POST /api/v1/password_reset/confirm/ |
ResetPasswordResponse | { detail: str } | Documented 200, 400, 404 and 429 response of all three endpoints |
MFA DTOs
Plain pydantic BaseModel classes in care/emr/resources/mfa/spec.py, with no model binding. The TOTP endpoints and the MFA login endpoint use them. Those endpoints write totp_secret and mfa_settings.
| DTO | Direction | Shape | Used by |
|---|---|---|---|
TOTPSetupResponse | response | { uri: str, secret_key: str } | POST /api/v1/mfa/totp/setup/ |
TOTPVerifyRequest | request | { code: str } | POST /api/v1/mfa/totp/verify/ |
TOTPVerifyResponse | response | { backup_codes: list[str] } | POST /api/v1/mfa/totp/verify/ |
PasswordVerifyRequest | request | { password: str } | setup/, disable/ and regenerate_backup_codes/ under /api/v1/mfa/totp/ |
MFALoginRequest | request | { method: LoginMethod, code: str, temp_token: str }. See LoginMethod values | POST /api/v1/mfa/login/, which needs no sign-in |
MFALoginResponse | response | { access: str, refresh: str } (JWT pair) | POST /api/v1/mfa/login/ |
Validation rules (write specs)
| Field | Rule | Source |
|---|---|---|
username | Matches ^[a-zA-Z0-9_-]{3,}$ ("Username can only contain alpha numeric values, dashes ( - ) and underscores ( _ )"). Must not exist on any user, deleted users included ("Username already exists") | UserCreateSpec.validate_username |
phone_number | Must not belong to a non-deleted user ("Phone Number already exists"). Create only | UserCreateSpec.validate_phone_number |
email | Must not belong to a non-deleted user ("Email already exists"). Must pass Django validate_email ("Invalid Email") | UserCreateSpec.validate_user_email |
password | If given, must pass the Django password validators: user-attribute similarity, minimum length (8 by default), common passwords, not all numeric. Else "Password is too weak". None is allowed | UserCreateSpec.validate_password |
gender | Must be a GenderChoices member | type annotation |
geo_organization | Must reference an existing Organization with org_type="govt", else 404 | UserUpdateSpec.perform_extra_deserialization |
communication[].language.code | Three lowercase letters and a valid ISO 639-3 code | UserLanguageSpec |
qualification[].degree | Must match an entry of USER_QUALIFICATION_DEGREES | UserQualificationSpec |
Server-maintained behaviour
role_orgson create: the spec copiesrole_orgstoobj._role_orgs, and the view applies each entry after it saves the user.- Each
role_orgsentry must name a responsibility (org_type="role", else "Role organization is not a role organization"). The caller must passcan_manage_organization_users_objfor the requested role, else "Access denied for requested roles". - The user and its responsibility links are created in one transaction.
set_password: create hashes the given password, or sets an unusable password when it isNone.- Email invitation: if the new user is not a service account and has no usable password, the view sends the "Set Up Your Password for Care" email. The link is valid for
PASSWORD_RESET_TOKEN_TTL_HOURS(default 24). - If that email fails, the create fails with "User creation failed due to email error." and no user is created.
created_byis set to the requesting user on create.- Cache:
UserSpecis@cacheable(use_base_manager=True). EveryUsersave clears the cache throughpost_save.UserRetrieveSpecreadscreated_bythroughmodel_from_cache(UserSpec, ...). - Computed read fields:
id,profile_picture_url,mfa_enabledandrole_orgsinUserSpec;created_by,geo_organizationandflagsinUserRetrieveSpec.
Related models
UserFlag
Feature flag for one user, defined in care/users/models.py. Extends BaseFlag, a BaseModel subclass.
| Field | Type | Notes |
|---|---|---|
user | FK → User (CASCADE) | Not null |
flag | CharField(1024) | Inherited from BaseFlag |
flag_type = FlagType.USER. The unique_user_flag constraint blocks duplicate (user, flag) pairs among rows with deleted=False.
UserFlag.check_user_has_flag(user_id, flag_name) and UserFlag.get_all_flags(user_id) read the flags through the cache, with a TTL of one day. UserRetrieveSpec.flags returns the flag names as a list[str].
PlugConfig
Slug-keyed JSON configuration, defined in care/users/models.py. Extends plain models.Model, so it has no audit or soft-delete fields.
| Field | Type | Notes |
|---|---|---|
slug | CharField(255) | Unique |
meta | JSONField | Default {} |
MobileOTP
Defined in care/facility/models/patient.py. A one-time password issued for a phone number. Extends BaseModel.
| Field | Type | Notes |
|---|---|---|
is_used | BooleanField | Default False |
phone_number | CharField(14) | mobile_or_landline_number_validator |
otp | CharField(10) | |
failed_attempts | PositiveSmallIntegerField | Default 0 |
Two partial indexes cover rows with deleted=False: pmo_phone_created_active_idx on (phone_number, -created_date) and pmo_phone_modified_active_idx on (phone_number, -modified_date).
Methods & save behaviour
User overrides neither save() nor delete(). Its helpers:
populate_role_orgs_array(commit=False): setsrole_org_idsto the ids of the user's responsibility organizations. Withcommit=True, it saves only that field.get_cached_role_orgs(): returnscached_role_orgswhen it is notNone. Otherwise it loadsOrganizationUser.get_cached_role_orgs(self.id), stores the result incached_role_orgsand saves only that field. Read specs return the result asrole_orgs.read_profile_picture_url(): returnsNonewhenprofile_picture_urlis empty. Otherwise it prefixes the stored key withFACILITY_CDN, or withFACILITY_S3_BUCKET_EXTERNAL_ENDPOINTandFACILITY_S3_BUCKETwhen no CDN is set. Read specs return the result asprofile_picture_url.is_mfa_enabled():Truewhenmfa_settings["totp"]["enabled"]is truthy.UserSpecreturns it asmfa_enabled.full_name(property): joinsprefix,get_full_name()andsuffixwith spaces, and leaves out an emptyprefixorsuffix.check_username_exists(username)(static): checks the entire queryset, deleted users included.UserCreateSpec.validate_usernameand thecheck_availabilityaction use it.get_all_flags(): returnsUserFlag.get_all_flags(self.id).UserRetrieveSpecreturns it asflags.
CustomUserManager methods:
get_queryset()filtersdeleted=False.get_entire_queryset()returns all rows.create_superuser()sets onlygender="non_binary"anduser_type="administrator". It does not set a phone number.make_random_password(length=10, secure_random=True): picks characters from letters, digits and punctuation. Withsecure_random=True, it retries until the password has a lowercase letter, an uppercase letter and at leastlength // 4digits.
UserFlag.save() (from BaseFlag) validates the flag name against the flag registry, and deletes the per-flag and the all-flags cache keys before it saves.
API integration notes
UserViewSetserves/api/v1/users/and looks users up byusername.- The public identifier is
external_id, returned asid. - Soft-deleted users drop out of normal queries. Cached
UserSpeclookups use the base manager and can still resolve them, for example as acreated_byreference. role_orgsaccepts only responsibilities. Link a user to a government organization throughPOST /api/v1/organization/{id}/users/.- On create, the API validates the request body before it checks permission, so a validation error can come before a permission error.
- The TOTP endpoints
POST /api/v1/mfa/totp/setup/,verify/,regenerate_backup_codes/anddisable/act on the signed-in user and maintaintotp_secretandmfa_settings. Setup, regenerate and disable check the password. PUT /api/v1/password_change/changes the password of the signed-in user. The email and phone-number password reset endpoints need no sign-in.
Endpoints of UserViewSet
Every endpoint needs a signed-in user. UserViewSet defines no permissions_controller, so only the checks in this table apply.
| Method and path | Purpose | Who can call it |
|---|---|---|
GET /api/v1/users/ | List (UserSpec). Filters: email, phone_number, username (partial match), is_service_account (default false). Search on first_name, last_name, username with search_text | Any signed-in user. Deleted users are left out |
GET /api/v1/users/{username}/ | Read one user (UserRetrieveSpec) | Any signed-in user |
POST /api/v1/users/ | Create (UserCreateSpec) | "Can create User in care", or "Can create service account in care" when is_service_account is true, held in any organization or facility department |
PUT /api/v1/users/{username}/ | Update (UserUpdateSpec) | The user or a superuser |
DELETE /api/v1/users/{username}/ | Delete | Superuser only |
GET /api/v1/users/degrees/ | Returns USER_QUALIFICATION_DEGREES | Any signed-in user |
GET /api/v1/users/{username}/check_availability/ | 200 if the username is free, 409 if it exists, deleted users included | Any signed-in user |
POST /api/v1/users/set_preferences/ | Stores one named preference | The signed-in user, on their own account |
Related
- Reference: Role, Permission, Permission association
- Reference: Organization, Facility
- Concept: User, Patient (
GenderChoicesis shared with the patient resource) - Flow: Create a user
- Base: Base model
- Source: users/models.py, facility/models/patient.py, emr/resources/user/spec.py, emr/api/viewsets/user.py, emr/resources/mfa/spec.py