Skip to main content
Version: 3.1

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​

ModelPurpose
UserCare account: sign-in, profile, languages, qualifications, notification data, MFA data and preferences
UserFlagFeature flag for one User
PlugConfigSlug-keyed JSON configuration
MobileOTPOne-time password issued for a phone number. Defined in care/facility/models/patient.py

The base class sets the audit fields of each model:

  • User extends Django's AbstractUser.
  • MobileOTP extends BaseModel.
  • UserFlag extends BaseFlag, a BaseModel subclass that adds a flag field and a save() that validates the flag name and clears the flag caches.
  • PlugConfig extends plain django.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​

FieldTypeNotes
external_idUUIDFieldUnique, indexed. Read specs return it as id
usernameCharField(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_typeCharField(100), nullableNo user spec reads or writes it. create_superuser() sets it to "administrator"
prefixCharField(10), nullableOptional in the specs, max length 10
suffixCharField(50), nullableOptional in the specs, max length 50
genderCharField(100), nullableThe write specs bind it to GenderChoices and require it. See GenderChoices values
old_genderIntegerField, nullableLegacy integer choices: 1 Male, 2 Female, 3 Non-binary. See GENDER_CHOICES values. No user spec exposes it
date_of_birthDateField, nullableReturned by CurrentUserRetrieveSpec
profile_picture_urlCharField(500), nullableRead 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_byFK → User (self, SET_NULL), nullablerelated_name="users_created". Set to the requesting user on create. UserRetrieveSpec returns it as a cached UserSpec dict, or null
is_service_accountBooleanFieldDefault False. Settable on create. Returned by UserRetrieveSpec. The list endpoint filters on it, with default false
deletedBooleanFieldDefault 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​

FieldTypeNotes
phone_numberCharField(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_numberCharField(14), nullablemobile_validator. Returned by CurrentUserRetrieveSpec

Languages & qualifications​

FieldTypeNotes
communicationJSONFieldDefault []. A list of UserCommunicationSpec entries. The write specs replace it only when the request includes communication
qualificationsJSONFieldDefault []. 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​

FieldTypeNotes
geo_organizationFK → emr.Organization (SET_NULL), nullableThe 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_orgsJSONField, nullableDefault null. No write spec accepts it. Read specs return role_orgs from get_cached_role_orgs()
role_org_idsArrayField(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​

FieldTypeNotes
pf_endpointTextField, nullableNotification data. Returned by CurrentUserRetrieveSpec
pf_p256dhTextField, nullableNotification data. Returned by CurrentUserRetrieveSpec
pf_authTextField, nullableNotification data. Returned by CurrentUserRetrieveSpec
totp_secretTextField, nullableTOTP secret. The MFA setup creates it, and disabling MFA clears it. No spec returns it
mfa_settingsJSONFieldDefault {}. See mfa_settings shape. No write spec accepts it. UserSpec returns the boolean mfa_enabled from is_mfa_enabled()
preferencesJSONFieldDefault {}. 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.

KeyTypeNotes
totp.enabledboolTrue after the user verifies a correct code
totp.backup_codeslist10 codes of 8 digits, created on enable. Regenerate replaces all of them; disable empties the list
totp.backup_codes[].codestrChecked with Django check_password at sign-in
totp.backup_codes[].usedboolA used code is refused ("Invalid or already used backup code")
totp.backup_codes[].used_atISO datetime stringSet 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[])​

FieldTypeRequiredNotes
languageUserLanguageSpecyesSee below
preferredboolyesNo limit on the number of preferred entries
proficiencyCEFRLevel or nullnoDefault null. See CEFRLevel values

UserLanguageSpec (communication[].language)​

FieldTypeRequiredNotes
codestryesMatches ^[a-z]{3}$ and must be an ISO 639-3 code known to pycountry ("Invalid ISO 639-3 language code")
systemLiteralyesAlways "urn:iso:std:iso:639:-3"

UserQualificationSpec (qualifications[])​

FieldTypeRequiredNotes
degreeUserDegreeSpecyescode and system must match an entry of USER_QUALIFICATION_DEGREES ("Degree must be one of the available qualifications")
issuerstryesIssuing authority
registration_numberstryesRegistration number
metadictnoDefault {}

UserDegreeSpec (qualifications[].degree)​

FieldTypeRequiredNotes
codestryesNot empty
systemstryesNot 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.

ValueLabel
1Male
2Female
3Non-binary

CEFRLevel values​

Bound to UserCommunicationSpec.proficiency.

ValueLabel in the user form
A1A1 · Beginner
A2A2 · Elementary
B1B1 · Intermediate
B2B2 · Upper intermediate
C1C1 · Advanced
C2C2 · Proficient

LoginMethod values​

Bound to MFALoginRequest.method in care/emr/resources/mfa/spec.py.

ValueMeaning
totpOne-time TOTP code, verified against totp_secret
backupSingle-use backup code from mfa_settings

Resource specs (API schema)​

UserBaseSpec extends EMRResource and sets __model__ = User and __exclude__ = ["geo_organization"].

Spec classRoleFields / behaviour
UserBaseSpecshared baseid, first_name, last_name, phone_number (max 14), prefix (max 10, optional), suffix (max 50, optional)
UserUpdateSpecwrite · updateBase + 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)
UserCreateSpecwrite · createExtends 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()
UserRoleOrgCreateSpecwrite · nestedorganization: UUID4, role: UUID4. One responsibility and role for the new user
UserCommunicationSpec, UserLanguageSpecwrite/read · nestedSee Nested JSON shapes
UserQualificationSpec, UserDegreeSpecwrite/read · nestedSee Nested JSON shapes
UserSpecread · listBase + 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
UserRetrieveSpecread · detailExtends UserSpec + geo_organization (dict), created_by (dict or null), email, flags (list[str]), is_service_account. Fills flags from get_all_flags()
CurrentUserRetrieveSpecread · signed-in userExtends 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
PublicUserReadSpecread · publicBase + 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.

DTOShapeUsed 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.

DTODirectionShapeUsed by
TOTPSetupResponseresponse{ uri: str, secret_key: str }POST /api/v1/mfa/totp/setup/
TOTPVerifyRequestrequest{ code: str }POST /api/v1/mfa/totp/verify/
TOTPVerifyResponseresponse{ backup_codes: list[str] }POST /api/v1/mfa/totp/verify/
PasswordVerifyRequestrequest{ password: str }setup/, disable/ and regenerate_backup_codes/ under /api/v1/mfa/totp/
MFALoginRequestrequest{ method: LoginMethod, code: str, temp_token: str }. See LoginMethod valuesPOST /api/v1/mfa/login/, which needs no sign-in
MFALoginResponseresponse{ access: str, refresh: str } (JWT pair)POST /api/v1/mfa/login/

Validation rules (write specs)​

FieldRuleSource
usernameMatches ^[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_numberMust not belong to a non-deleted user ("Phone Number already exists"). Create onlyUserCreateSpec.validate_phone_number
emailMust not belong to a non-deleted user ("Email already exists"). Must pass Django validate_email ("Invalid Email")UserCreateSpec.validate_user_email
passwordIf 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 allowedUserCreateSpec.validate_password
genderMust be a GenderChoices membertype annotation
geo_organizationMust reference an existing Organization with org_type="govt", else 404UserUpdateSpec.perform_extra_deserialization
communication[].language.codeThree lowercase letters and a valid ISO 639-3 codeUserLanguageSpec
qualification[].degreeMust match an entry of USER_QUALIFICATION_DEGREESUserQualificationSpec

Server-maintained behaviour​

  • role_orgs on create: the spec copies role_orgs to obj._role_orgs, and the view applies each entry after it saves the user.
  • Each role_orgs entry must name a responsibility (org_type="role", else "Role organization is not a role organization"). The caller must pass can_manage_organization_users_obj for 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 is None.
  • 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_by is set to the requesting user on create.
  • Cache: UserSpec is @cacheable(use_base_manager=True). Every User save clears the cache through post_save. UserRetrieveSpec reads created_by through model_from_cache(UserSpec, ...).
  • Computed read fields: id, profile_picture_url, mfa_enabled and role_orgs in UserSpec; created_by, geo_organization and flags in UserRetrieveSpec.

UserFlag​

Feature flag for one user, defined in care/users/models.py. Extends BaseFlag, a BaseModel subclass.

FieldTypeNotes
userFK → User (CASCADE)Not null
flagCharField(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.

FieldTypeNotes
slugCharField(255)Unique
metaJSONFieldDefault {}

MobileOTP​

Defined in care/facility/models/patient.py. A one-time password issued for a phone number. Extends BaseModel.

FieldTypeNotes
is_usedBooleanFieldDefault False
phone_numberCharField(14)mobile_or_landline_number_validator
otpCharField(10)
failed_attemptsPositiveSmallIntegerFieldDefault 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): sets role_org_ids to the ids of the user's responsibility organizations. With commit=True, it saves only that field.
  • get_cached_role_orgs(): returns cached_role_orgs when it is not None. Otherwise it loads OrganizationUser.get_cached_role_orgs(self.id), stores the result in cached_role_orgs and saves only that field. Read specs return the result as role_orgs.
  • read_profile_picture_url(): returns None when profile_picture_url is empty. Otherwise it prefixes the stored key with FACILITY_CDN, or with FACILITY_S3_BUCKET_EXTERNAL_ENDPOINT and FACILITY_S3_BUCKET when no CDN is set. Read specs return the result as profile_picture_url.
  • is_mfa_enabled(): True when mfa_settings["totp"]["enabled"] is truthy. UserSpec returns it as mfa_enabled.
  • full_name (property): joins prefix, get_full_name() and suffix with spaces, and leaves out an empty prefix or suffix.
  • check_username_exists(username) (static): checks the entire queryset, deleted users included. UserCreateSpec.validate_username and the check_availability action use it.
  • get_all_flags(): returns UserFlag.get_all_flags(self.id). UserRetrieveSpec returns it as flags.

CustomUserManager methods:

  • get_queryset() filters deleted=False. get_entire_queryset() returns all rows.
  • create_superuser() sets only gender="non_binary" and user_type="administrator". It does not set a phone number.
  • make_random_password(length=10, secure_random=True): picks characters from letters, digits and punctuation. With secure_random=True, it retries until the password has a lowercase letter, an uppercase letter and at least length // 4 digits.

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​

  • UserViewSet serves /api/v1/users/ and looks users up by username.
  • The public identifier is external_id, returned as id.
  • Soft-deleted users drop out of normal queries. Cached UserSpec lookups use the base manager and can still resolve them, for example as a created_by reference.
  • role_orgs accepts only responsibilities. Link a user to a government organization through POST /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/ and disable/ act on the signed-in user and maintain totp_secret and mfa_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 pathPurposeWho 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_textAny 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}/DeleteSuperuser only
GET /api/v1/users/degrees/Returns USER_QUALIFICATION_DEGREESAny signed-in user
GET /api/v1/users/{username}/check_availability/200 if the username is free, 409 if it exists, deleted users includedAny signed-in user
POST /api/v1/users/set_preferences/Stores one named preferenceThe signed-in user, on their own account