Skip to content

Users API reference

Users

User management router for authenticated operations.

approve_user

approve_user(request, user_id, db)

Approve pending user account.

A user who is not awaiting approval, is deactivated or is queued for deletion, or whose email is not verified while sign-up requires verification, is refused with 409.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_id UuidId

ID of user to approve.

required
db DbSession

Database session dependency.

required
Source code in backend/app/modules/users/users/router.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@router.post(
    "/{user_id}/approve",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def approve_user(
    request: Request,
    user_id: core_dependencies.UuidId,
    db: core_dependencies.DbSession,
) -> None:
    """Approve pending user account.

    A user who is not awaiting approval, is deactivated or is queued for deletion, or whose email is not verified
    while sign-up requires verification, is refused with 409.

    Args:
        request: The incoming request, read by the rate limiter.
        user_id: ID of user to approve.
        db: Database session dependency.
    """
    users_service.approve_user(user_id, db)

create_user

create_user(request, user, token_user_id, token_session_id, step_up_store, db, response)

Create a new user (admin operation).

An administrator account needs the creating administrator's own step-up verification in step_up (their current password or, for an account without one, a fresh identity-provider sign-in, and an MFA code when MFA is enabled). A regular account needs no step_up.

The password is optional when the server has mail configured: without it the account is created active with no password and its owner is emailed a link, valid for 24 hours, to choose one. Without mail, or for an inactive account, a missing password is refused.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user UserAdminCreate

User creation data, and the administrator's step-up.

required
token_user_id CurrentUserId

ID of the administrator creating the user.

required
token_session_id CurrentSessionId

Session ID of the administrator.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
db DbSession

Database session dependency.

required
response Response

The response, whose Location names where the user is read.

required

Returns:

Type Description
UserRead

Created user data.

Source code in backend/app/modules/users/users/router.py
120
121
122
123
124
125
126
127
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@router.post(
    "",
    status_code=status.HTTP_201_CREATED,
    response_model=users_schema.UserRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def create_user(
    request: Request,
    user: users_schema.UserAdminCreate,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
    response: Response,
) -> users_schema.UserRead:
    """Create a new user (admin operation).

    An administrator account needs the creating administrator's own step-up verification in `step_up` (their
    current password or, for an account without one, a fresh identity-provider sign-in, and an MFA code when MFA
    is enabled). A regular account needs no `step_up`.

    The `password` is optional when the server has mail configured: without it the account is created active with
    no password and its owner is emailed a link, valid for 24 hours, to choose one. Without mail, or for an inactive
    account, a missing password is refused.

    Args:
        request: The incoming request, read by the rate limiter.
        user: User creation data, and the administrator's step-up.
        token_user_id: ID of the administrator creating the user.
        token_session_id: Session ID of the administrator.
        step_up_store: Step-up lockout store.
        db: Database session dependency.
        response: The response, whose ``Location`` names where the user is read.

    Returns:
        Created user data.
    """
    created = users_service.create_user(
        user.to_create(), user.step_up, token_user_id, token_session_id, step_up_store, db
    )
    core_location.set_location(response, request, "read_user", user_id=created.id)
    core_etag.set_etag(response, created.version)
    return created

delete_user

delete_user(request, response, user_id, body, token_user_id, token_session_id, step_up_store, states, storage, mail, if_match, db)

Queue the deletion of another user's account.

Requires the administrator's own step-up verification: their current password (or, for an account without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. The user is signed out and deactivated at once and a background job erases their data. Poll GET /jobs/{job_id} for the outcome; a failed deletion is requested again.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
response Response

The response, which names the job and when to poll it.

required
user_id UuidId

ID of user to delete.

required
body StepUpRequest

The administrator's step-up verification.

required
token_user_id CurrentUserId

ID of the administrator making the request.

required
token_session_id CurrentSessionId

Session ID of the administrator.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
states UserDeletionStateStoreDep

Shared store of the deletion's state.

required
storage Storage

The platform storage provider.

required
mail Mail

The platform mail provider.

required
if_match IfMatch

The If-Match precondition.

required
db DbSession

Database session dependency.

required

Returns:

Type Description
UserDeletionStatus

The deletion's initial status, with the id of the job that reads it.

Raises:

Type Description
PermissionDeniedError

If the administrator targets their own account.

NotFoundError

If the user does not exist.

PreconditionFailedError

If the user changed since the client read it.

LastAdministratorError

If the user is the only administrator.

JobAlreadyRunningError

If a deletion is already pending.

Source code in backend/app/modules/users/users/router.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
@router.post(
    "/{user_id}/delete",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=users_schema.UserDeletionStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def delete_user(
    request: Request,
    response: Response,
    user_id: core_dependencies.UuidId,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    states: users_dependencies.UserDeletionStateStoreDep,
    storage: core_dependencies.Storage,
    mail: core_dependencies.Mail,
    if_match: core_dependencies.IfMatch,
    db: core_dependencies.DbSession,
) -> users_schema.UserDeletionStatus:
    """Queue the deletion of another user's account.

    Requires the administrator's own step-up verification: their current password (or, for an account
    without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. The user is signed
    out and deactivated at once and a background job erases their data. Poll ``GET /jobs/{job_id}`` for the
    outcome; a failed deletion is requested again.

    Args:
        request: The incoming request, read by the rate limiter.
        response: The response, which names the job and when to poll it.
        user_id: ID of user to delete.
        body: The administrator's step-up verification.
        token_user_id: ID of the administrator making the request.
        token_session_id: Session ID of the administrator.
        step_up_store: Step-up lockout store.
        states: Shared store of the deletion's state.
        storage: The platform storage provider.
        mail: The platform mail provider.
        if_match: The ``If-Match`` precondition.
        db: Database session dependency.

    Returns:
        The deletion's initial status, with the id of the job that reads it.

    Raises:
        PermissionDeniedError: If the administrator targets their own account.
        NotFoundError: If the user does not exist.
        PreconditionFailedError: If the user changed since the client read it.
        LastAdministratorError: If the user is the only administrator.
        JobAlreadyRunningError: If a deletion is already pending.
    """
    deletion = users_deletion_job_service.request_deletion_by_administrator(
        user_id,
        token_user_id,
        token_session_id,
        body.step_up,
        step_up_store,
        states,
        storage,
        mail,
        db,
        if_match=if_match,
    )
    core_location.set_job_location(response, request, deletion.id, users_constants.DELETION_POLL_SECONDS)
    return deletion

delete_user_identity_provider

delete_user_identity_provider(request, user_id, idp_id, body, token_user_id, token_session_id, step_up_store, db)

Unlink an identity provider from another user (admin).

Requires the administrator's own step-up verification: their current password (or, for an account without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_id UuidId

ID of the user to unlink the identity provider from.

required
idp_id UuidId

ID of the identity provider to unlink.

required
body StepUpRequest

The administrator's step-up verification.

required
token_user_id CurrentUserId

ID of the administrator making the change.

required
token_session_id CurrentSessionId

Session ID of the administrator.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
db DbSession

Database session.

required

Returns:

Type Description
None

None

Source code in backend/app/modules/users/users/router.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
@router.post(
    "/{user_id}/identity-providers/{idp_id}/unlink",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_user_identity_provider(
    request: Request,
    user_id: core_dependencies.UuidId,
    idp_id: core_dependencies.UuidId,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
) -> None:
    """Unlink an identity provider from another user (admin).

    Requires the administrator's own step-up verification: their current password (or, for an account
    without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled.

    Args:
        request: The incoming request, read by the rate limiter.
        user_id: ID of the user to unlink the identity provider from.
        idp_id: ID of the identity provider to unlink.
        body: The administrator's step-up verification.
        token_user_id: ID of the administrator making the change.
        token_session_id: Session ID of the administrator.
        step_up_store: Step-up lockout store.
        db: Database session.

    Returns:
        None
    """
    users_service.unlink_identity_provider(
        user_id, idp_id, token_user_id, token_session_id, body.step_up, step_up_store, db
    )

delete_user_photo

delete_user_photo(request, user_id, storage, db)

Delete user profile photo.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_id UuidId

ID of user whose photo to delete.

required
storage Storage

The platform storage provider.

required
db DbSession

Database session dependency.

required

Returns:

Type Description
None

None

Source code in backend/app/modules/users/users/router.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
@router.delete(
    "/{user_id}/photo",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_user_photo(
    request: Request,
    user_id: core_dependencies.UuidId,
    storage: core_dependencies.Storage,
    db: core_dependencies.DbSession,
) -> None:
    """Delete user profile photo.

    Args:
        request: The incoming request, read by the rate limiter.
        user_id: ID of user whose photo to delete.
        storage: The platform storage provider.
        db: Database session dependency.

    Returns:
        None
    """
    users_photo_service.delete_photo(user_id, storage, db, audit=True)

edit_user

edit_user(request, user_id, user_attributtes, token_user_id, token_session_id, step_up_store, db, response, if_match)

Update user information.

A change of email, access type, active flag, username or email-verified flag needs the administrator's own step-up verification in step_up (their current password or, for an account without one, a fresh identity-provider sign-in, and an MFA code when MFA is enabled). A change of email, access type or active flag also signs the edited user out everywhere; a new username does not, and the user is sent a security notice of it. An edit that changes none of the five needs no step_up.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_id UuidId

ID of user to update.

required
user_attributtes UserAdminEdit

User data to update, and the administrator's step-up.

required
token_user_id CurrentUserId

ID of the administrator making the edit.

required
token_session_id CurrentSessionId

Session ID of the administrator.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
db DbSession

Database session dependency.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
UserRead

Updated user data.

Source code in backend/app/modules/users/users/router.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
@router.patch(
    "/{user_id}",
    response_model=users_schema.UserRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_user(
    request: Request,
    user_id: core_dependencies.UuidId,
    user_attributtes: users_schema.UserAdminEdit,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> users_schema.UserRead:
    """Update user information.

    A change of email, access type, active flag, username or email-verified flag needs the administrator's own
    step-up verification in `step_up` (their current password or, for an account without one, a fresh
    identity-provider sign-in, and an MFA code when MFA is enabled). A change of email, access type or active
    flag also signs the edited user out everywhere; a new username does not, and the user is sent a security
    notice of it. An edit that changes none of the five needs no `step_up`.

    Args:
        request: The incoming request, read by the rate limiter.
        user_id: ID of user to update.
        user_attributtes: User data to update, and the administrator's step-up.
        token_user_id: ID of the administrator making the edit.
        token_session_id: Session ID of the administrator.
        step_up_store: Step-up lockout store.
        db: Database session dependency.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        Updated user data.
    """
    updated = users_service.edit_user(
        user_id,
        user_attributtes.to_edit(),
        user_attributtes.step_up,
        token_user_id,
        token_session_id,
        step_up_store,
        db,
        if_match=if_match,
    )
    core_etag.set_etag(response, updated.version)
    return updated

edit_user_password

edit_user_password(request, user_id, user_attributes, token_user_id, token_session_id, step_up_store, db)

Update another user's password.

Requires the administrator's own step-up verification: their current password (or, for an account without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_id UuidId

ID of user to update password for.

required
user_attributes UserAdminEditPassword

New password data and the administrator's step-up.

required
token_user_id CurrentUserId

ID of the administrator making the change.

required
token_session_id CurrentSessionId

Session ID of the administrator.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
db DbSession

Database session dependency.

required

Raises:

Type Description
HTTPException

422 if the password is too short, too common or matches the account's details.

Source code in backend/app/modules/users/users/router.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
@router.post(
    "/{user_id}/password/change",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def edit_user_password(
    request: Request,
    user_id: core_dependencies.UuidId,
    user_attributes: users_schema.UserAdminEditPassword,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
) -> None:
    """Update another user's password.

    Requires the administrator's own step-up verification: their current password (or, for an account
    without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled.

    Args:
        request: The incoming request, read by the rate limiter.
        user_id: ID of user to update password for.
        user_attributes: New password data and the administrator's step-up.
        token_user_id: ID of the administrator making the change.
        token_session_id: Session ID of the administrator.
        step_up_store: Step-up lockout store.
        db: Database session dependency.

    Raises:
        HTTPException: 422 if the password is too short, too common or matches the account's details.
    """
    users_service.change_user_password(user_id, user_attributes, token_user_id, token_session_id, step_up_store, db)

get_user_identity_providers

get_user_identity_providers(user_id, page, db)

List one page of a specific user's identity provider links (admin).

Parameters:

Name Type Description Default
user_id UuidId

ID of the user whose identity provider links to retrieve.

required
page ListPage

The requested window.

required
db DbSession

Database session.

required

Returns:

Type Description
IdentityProviderLinkPage

The page of the user's enriched identity provider links, oldest first.

Source code in backend/app/modules/users/users/router.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
@router.get(
    "/{user_id}/identity-providers",
    response_model=auth_identity_links_schema.IdentityProviderLinkPage,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:read-all"])],
)
def get_user_identity_providers(
    user_id: core_dependencies.UuidId,
    page: core_pagination.ListPage,
    db: core_dependencies.DbSession,
) -> auth_identity_links_schema.IdentityProviderLinkPage:
    """List one page of a specific user's identity provider links (admin).

    Args:
        user_id: ID of the user whose identity provider links to retrieve.
        page: The requested window.
        db: Database session.

    Returns:
        The page of the user's enriched identity provider links, oldest first.
    """
    return users_service.list_identity_provider_links(user_id, page, db)

put_user_image

put_user_image(request, user_id, file, storage, db, response)

Set a user's profile image.

Answers 201 when the user had no photo and 200 when it replaced one.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_id UuidId

ID of user to upload image for.

required
file UploadFile

Uploaded image file.

required
storage Storage

The platform storage provider.

required
db DbSession

Database session dependency.

required
response Response

The response, whose status is 200 when a photo was replaced.

required

Returns:

Type Description
UserPhotoRead

The servable URL of the new photo.

Source code in backend/app/modules/users/users/router.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
@router.put(
    "/{user_id}/photo",
    status_code=status.HTTP_201_CREATED,
    response_model=users_schema.UserPhotoRead,
    responses=core_openapi_contract.replaced_response(users_schema.UserPhotoRead),
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
    openapi_extra=core_middleware_body_limit.upload_limit(
        core_file_uploads.max_bytes_for(core_file_uploads.UploadKind.IMAGE)
    ),
)
@core_rate_limit.limiter.limit(core_rate_limit.UPLOAD)
def put_user_image(
    request: Request,
    user_id: core_dependencies.UuidId,
    file: UploadFile,
    storage: core_dependencies.Storage,
    db: core_dependencies.DbSession,
    response: Response,
) -> users_schema.UserPhotoRead:
    """Set a user's profile image.

    Answers 201 when the user had no photo and 200 when it replaced one.

    Args:
        request: The incoming request, read by the rate limiter.
        user_id: ID of user to upload image for.
        file: Uploaded image file.
        storage: The platform storage provider.
        db: Database session dependency.
        response: The response, whose status is 200 when a photo was replaced.

    Returns:
        The servable URL of the new photo.
    """
    replaced = users_photo_service.upload_photo(user_id, file, storage, db, audit=True)
    if replaced:
        response.status_code = status.HTTP_200_OK
    return users_schema.UserPhotoRead(photo_path=users_service.require_user(user_id, db).photo_path)

read_user

read_user(user_id, db, scopes, response)

Get a user by ID.

With users:read-all the answer is the full record, with its ETag. With only users:read it is the public projection, and a user who is inactive or awaits approval is 404.

Source code in backend/app/modules/users/users/router.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
@router.get(
    "/{user_id}",
    response_model=users_schema.UserRead | users_schema.UserPublicRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:read"])],
)
def read_user(
    user_id: core_dependencies.UuidId,
    db: core_dependencies.DbSession,
    scopes: auth_dependencies.CurrentScopes,
    response: Response,
) -> users_schema.UserRead | users_schema.UserPublicRead:
    """Get a user by ID.

    With `users:read-all` the answer is the full record, with its `ETag`. With only `users:read` it is the
    public projection, and a user who is inactive or awaits approval is 404.
    """
    if "users:read-all" in scopes:
        user = users_service.require_user_with_pending_email(user_id, db)
        core_etag.set_etag(response, user.version)
        return user
    return users_service.get_public_profile(user_id, db)

read_users

read_users(db, scopes, page, active=None, email_verified=None, pending_approval=None, external_auth=None, username=None, username_contains=None)

List users, one page at a time.

With users:read-all the page holds full records and every filter is available. With only users:read it holds public projections of active users who are discoverable (those who switched off "Let others find me in search" are left out; their profile stays reachable by id), a state filter is refused with 403, and a request with neither username nor username_contains (at least 3 characters) is refused with 422. num_records defaults to the server's page size and may not exceed it; a larger value is refused with 422.

Source code in backend/app/modules/users/users/router.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
90
91
92
93
94
@router.get(
    "",
    response_model=core_pagination.Page[users_schema.UserRead] | users_schema.UserPublicPage,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:read"])],
)
def read_users(
    db: core_dependencies.DbSession,
    scopes: auth_dependencies.CurrentScopes,
    page: users_dependencies.DirectoryPage,
    active: Annotated[
        bool | None,
        Query(description="Keep only active (true) or inactive (false) users; needs `users:read-all`"),
    ] = None,
    email_verified: Annotated[
        bool | None,
        Query(description="Keep only users whose email is verified (true) or not (false); needs `users:read-all`"),
    ] = None,
    pending_approval: Annotated[
        bool | None,
        Query(description="Keep only users awaiting admin approval (true) or not (false); needs `users:read-all`"),
    ] = None,
    external_auth: Annotated[
        bool | None,
        Query(
            description=(
                "Keep only users with (true) or without (false) a linked identity provider; needs `users:read-all`"
            )
        ),
    ] = None,
    username: Annotated[
        str | None,
        Query(min_length=1, max_length=250, description="Keep only the user with this exact username"),
    ] = None,
    username_contains: Annotated[
        str | None,
        Query(
            min_length=users_dependencies.MIN_SEARCH_TERM_LENGTH,
            max_length=250,
            description="Keep only users whose username contains this text (at least 3 characters)",
        ),
    ] = None,
) -> core_pagination.Page[users_schema.UserRead] | users_schema.UserPublicPage:
    """List users, one page at a time.

    With `users:read-all` the page holds full records and every filter is available. With only `users:read` it
    holds public projections of active users who are discoverable (those who switched off "Let others find me
    in search" are left out; their profile stays reachable by id), a state filter is refused with 403, and a request
    with neither `username` nor `username_contains` (at least 3 characters) is refused with 422.
    `num_records` defaults to the server's page size and may not exceed it; a larger value is refused with 422.
    """
    if "users:read-all" in scopes:
        return users_service.list_users(
            db,
            page_number=page.page_number,
            num_records=page.num_records,
            active=active,
            email_verified=email_verified,
            pending_approval=pending_approval,
            external_auth=external_auth,
            username=username,
            username_contains=username_contains,
        )
    if any(state is not None for state in (active, email_verified, pending_approval, external_auth)):
        auth_dependencies.require_scopes(scopes, "users:read-all")
    users_dependencies.require_search_term(username, username_contains)
    return users_service.list_public_users(page, db, username=username, username_contains=username_contains)

require_user_password_change

require_user_password_change(request, user_id, body, token_user_id, token_session_id, step_up_store, db)

Require another user to choose a new password at their next sign-in.

Requires the administrator's own step-up verification: their current password (or, for an account without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. The user keeps their current password until then, all of their sessions end and they are notified. A user without a local password is refused with 409; single sign-on sign-ins are unaffected.

Source code in backend/app/modules/users/users/router.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
@router.post(
    "/{user_id}/password/require-change",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def require_user_password_change(
    request: Request,
    user_id: core_dependencies.UuidId,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
) -> None:
    """Require another user to choose a new password at their next sign-in.

    Requires the administrator's own step-up verification: their current password (or, for an account
    without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. The user keeps their
    current password until then, all of their sessions end and they are notified. A user without a local
    password is refused with 409; single sign-on sign-ins are unaffected.
    """
    users_service.require_user_password_change(user_id, body, token_user_id, token_session_id, step_up_store, db)

reset_user_mfa

reset_user_mfa(request, user_id, body, token_user_id, token_session_id, step_up_store, db)

Reset another user's two-factor authentication.

Requires the administrator's own step-up verification: their current password (or, for an account without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. The user's MFA secret and backup codes are removed, all of their sessions end and they are notified. A user without MFA is refused with 409.

Source code in backend/app/modules/users/users/router.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
@router.post(
    "/{user_id}/mfa/reset",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["users:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def reset_user_mfa(
    request: Request,
    user_id: core_dependencies.UuidId,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
) -> None:
    """Reset another user's two-factor authentication.

    Requires the administrator's own step-up verification: their current password (or, for an account
    without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. The user's MFA
    secret and backup codes are removed, all of their sessions end and they are notified. A user without MFA is
    refused with 409.
    """
    users_service.reset_user_mfa(user_id, body, token_user_id, token_session_id, step_up_store, db)

User schema definitions for request and response models.

EmailChange

Bases: BaseModel

Self-service email change, authorised by step-up verification.

Attributes:

Name Type Description
email EmailStr

The new email address.

revoke_other_sessions StrictBool

Whether to sign out the user's other sessions after the change.

step_up StepUpVerification

The caller's step-up verification.

Source code in backend/app/modules/users/users/schema.py
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
class EmailChange(BaseModel):
    """Self-service email change, authorised by step-up verification.

    Attributes:
        email: The new email address.
        revoke_other_sessions: Whether to sign out the user's other sessions after the change.
        step_up: The caller's step-up verification.
    """

    email: EmailStr = Field(..., max_length=250, description="The new email address")
    revoke_other_sessions: StrictBool = Field(
        default=True,
        description=(
            "After the email change, all of the user's other sessions "
            "(keeping the current one) are revoked unless the client sends false."
        ),
    )
    step_up: auth_schema.StepUpVerification = Field(
        ..., description="Step-up verification, required to change the email address"
    )

    model_config = ConfigDict(extra="forbid")

FirstAdminCreate

Bases: BaseModel

The only fields a caller supplies when the first administrator is created.

The access level and account state are not here: the users service sets them.

Attributes:

Name Type Description
name UserRequestName

User's full name.

username UserUsername

Unique username.

email UserEmail

User's email address.

password UserPassword

User's password (the administrator password policy applies).

Source code in backend/app/modules/users/users/schema.py
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
class FirstAdminCreate(BaseModel):
    """The only fields a caller supplies when the first administrator is created.

    The access level and account state are not here: the users service sets them.

    Attributes:
        name: User's full name.
        username: Unique username.
        email: User's email address.
        password: User's password (the administrator password policy applies).
    """

    name: UserRequestName
    username: UserUsername
    email: UserEmail
    password: UserPassword

    model_config = ConfigDict(extra="forbid")

Gender

Bases: Enum

User gender enumeration.

Attributes:

Name Type Description
MALE

Male gender.

FEMALE

Female gender.

UNSPECIFIED

Unspecified or undisclosed gender.

Source code in backend/app/modules/users/users/schema.py
32
33
34
35
36
37
38
39
40
41
42
43
class Gender(Enum):
    """User gender enumeration.

    Attributes:
        MALE: Male gender.
        FEMALE: Female gender.
        UNSPECIFIED: Unspecified or undisclosed gender.
    """

    MALE = "male"
    FEMALE = "female"
    UNSPECIFIED = "unspecified"

IdentityProviderLinkStart

Bases: BaseModel

Start linking an identity provider to the signed-in user's account, authorised by step-up verification.

Attributes:

Name Type Description
redirect StrictStr | None

Frontend return path after linking (a relative path or a configured native-app address).

revoke_other_sessions StrictBool

Whether to sign out the user's other sessions once the link completes.

step_up StepUpVerification

The caller's step-up verification.

Source code in backend/app/modules/users/users/schema.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
class IdentityProviderLinkStart(BaseModel):
    """Start linking an identity provider to the signed-in user's account, authorised by step-up verification.

    Attributes:
        redirect: Frontend return path after linking (a relative path or a configured native-app address).
        revoke_other_sessions: Whether to sign out the user's other sessions once the link completes.
        step_up: The caller's step-up verification.
    """

    redirect: StrictStr | None = Field(
        default=None,
        min_length=1,
        max_length=oauth_state_constants.REDIRECT_MAX_LENGTH,
        description="Frontend return path after linking (relative path or a configured native-app address)",
    )
    revoke_other_sessions: StrictBool = Field(
        default=True,
        description=(
            "When the link completes, all of the user's other sessions "
            "(keeping the current one) are revoked unless the client sends false."
        ),
    )
    step_up: auth_schema.StepUpVerification = Field(
        ..., description="Step-up verification, required to link an identity provider"
    )

    model_config = ConfigDict(extra="forbid")

Language

Bases: StrEnum

Supported application languages.

Attributes:

Name Type Description
CATALAN

Catalan (ca).

CHINESE_SIMPLIFIED

Simplified Chinese (zh-Hans).

CHINESE_TRADITIONAL

Traditional Chinese (zh-Hant).

GERMAN

German (de).

FRENCH

French (fr).

GALICIAN

Galician (gl).

ITALIAN

Italian (it).

DUTCH

Dutch (nl).

PORTUGUESE

Portuguese (pt-PT).

SLOVENIAN

Slovenian (sl).

SWEDISH

Swedish (sv).

SPANISH

Spanish (es).

ENGLISH

English (en).

POLISH

Polish (pl).

TURKISH

Turkish (tr).

UKRAINIAN

Ukrainian (uk).

ROMANIAN

Romanian (ro).

NORWEGIAN

Norwegian Bokmål (nb).

DANISH

Danish (da).

FINNISH

Finnish (fi).

CZECH

Czech (cs).

GREEK

Greek (el).

HUNGARIAN

Hungarian (hu).

BULGARIAN

Bulgarian (bg).

CROATIAN

Croatian (hr).

SERBIAN

Serbian (sr).

SLOVAK

Slovak (sk).

LITHUANIAN

Lithuanian (lt).

LATVIAN

Latvian (lv).

ESTONIAN

Estonian (et).

Source code in backend/app/modules/users/users/schema.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class Language(StrEnum):
    """Supported application languages.

    Attributes:
        CATALAN: Catalan (ca).
        CHINESE_SIMPLIFIED: Simplified Chinese (zh-Hans).
        CHINESE_TRADITIONAL: Traditional Chinese (zh-Hant).
        GERMAN: German (de).
        FRENCH: French (fr).
        GALICIAN: Galician (gl).
        ITALIAN: Italian (it).
        DUTCH: Dutch (nl).
        PORTUGUESE: Portuguese (pt-PT).
        SLOVENIAN: Slovenian (sl).
        SWEDISH: Swedish (sv).
        SPANISH: Spanish (es).
        ENGLISH: English (en).
        POLISH: Polish (pl).
        TURKISH: Turkish (tr).
        UKRAINIAN: Ukrainian (uk).
        ROMANIAN: Romanian (ro).
        NORWEGIAN: Norwegian Bokmål (nb).
        DANISH: Danish (da).
        FINNISH: Finnish (fi).
        CZECH: Czech (cs).
        GREEK: Greek (el).
        HUNGARIAN: Hungarian (hu).
        BULGARIAN: Bulgarian (bg).
        CROATIAN: Croatian (hr).
        SERBIAN: Serbian (sr).
        SLOVAK: Slovak (sk).
        LITHUANIAN: Lithuanian (lt).
        LATVIAN: Latvian (lv).
        ESTONIAN: Estonian (et).
    """

    CATALAN = "ca"
    CHINESE_SIMPLIFIED = "zh-Hans"
    CHINESE_TRADITIONAL = "zh-Hant"
    GERMAN = "de"
    FRENCH = "fr"
    GALICIAN = "gl"
    ITALIAN = "it"
    DUTCH = "nl"
    PORTUGUESE = "pt-PT"
    SLOVENIAN = "sl"
    SWEDISH = "sv"
    SPANISH = "es"
    ENGLISH = "en"
    POLISH = "pl"
    TURKISH = "tr"
    UKRAINIAN = "uk"
    ROMANIAN = "ro"
    NORWEGIAN = "nb"
    DANISH = "da"
    FINNISH = "fi"
    CZECH = "cs"
    GREEK = "el"
    HUNGARIAN = "hu"
    BULGARIAN = "bg"
    CROATIAN = "hr"
    SERBIAN = "sr"
    SLOVAK = "sk"
    LITHUANIAN = "lt"
    LATVIAN = "lv"
    ESTONIAN = "et"

ProfileUpdate

Bases: NotClearable, BaseModel

Schema for self-service profile updates.

Strict allow-list of fields the authenticated user is permitted to change on their own account. Administrative fields (access_type, active, mfa_enabled, mfa_secret, email_verified, pending_admin_approval) are intentionally excluded — accepting them here would allow self-service privilege escalation through mass assignment.

Attributes:

Name Type Description
name DisplayName | None

User's full name.

city StrictStr | None

User's city.

birthdate RecordDate | None

User's birthdate.

preferred_language Language | None

Preferred application language.

gender Gender | None

User's gender.

units Units | None

Preferred unit system.

weight_units Units | None

Preferred weight units, independent of units; null follows units.

height UserRequestHeight | None

User's height in centimeters.

max_heart_rate StrictInt | None

Maximum heart rate in bpm.

first_day_of_week WeekDay | None

First day of the week.

currency Currency | None

Preferred currency.

timezone IanaTimezone | None

IANA timezone the athlete lives in.

Note

email is deliberately absent. It is the address password resets go to, so changing it needs fresh proof of identity and is :class:EmailChange. username is deliberately absent for the same reason: it is the sign-in name, so changing it is :class:UsernameChange.

photo_path is deliberately absent. The photo is a server-issued storage key written only by the upload and delete endpoints, so accepting it here would let a caller repoint their avatar at another user's blob.

Source code in backend/app/modules/users/users/schema.py
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
class ProfileUpdate(core_partial_update.NotClearable, BaseModel):
    """Schema for self-service profile updates.

    Strict allow-list of fields the authenticated user is
    permitted to change on their own account. Administrative
    fields (``access_type``, ``active``, ``mfa_enabled``,
    ``mfa_secret``, ``email_verified``,
    ``pending_admin_approval``) are intentionally excluded —
    accepting them here would allow self-service privilege
    escalation through mass assignment.

    Attributes:
        name: User's full name.
        city: User's city.
        birthdate: User's birthdate.
        preferred_language: Preferred application language.
        gender: User's gender.
        units: Preferred unit system.
        weight_units: Preferred weight units, independent of units; null follows units.
        height: User's height in centimeters.
        max_heart_rate: Maximum heart rate in bpm.
        first_day_of_week: First day of the week.
        currency: Preferred currency.
        timezone: IANA timezone the athlete lives in.

    Note:
        ``email`` is deliberately absent. It is the address password resets go to, so changing
        it needs fresh proof of identity and is :class:`EmailChange`. ``username`` is deliberately absent
        for the same reason: it is the sign-in name, so changing it is :class:`UsernameChange`.

        ``photo_path`` is deliberately absent. The photo is a
        server-issued storage key written only by the upload and
        delete endpoints, so accepting it here would let a caller
        repoint their avatar at another user's blob.
    """

    not_clearable: ClassVar[tuple[str, ...]] = (
        "name",
        "preferred_language",
        "gender",
        "units",
        "first_day_of_week",
        "currency",
    )

    name: core_types.DisplayName | None = None
    city: StrictStr | None = Field(default=None, max_length=250)
    birthdate: core_types.RecordDate | None = None
    preferred_language: Language | None = None
    gender: Gender | None = None
    units: server_settings_schema.Units | None = None
    weight_units: server_settings_schema.Units | None = None
    height: UserRequestHeight | None = None
    max_heart_rate: StrictInt | None = Field(default=None, ge=30, le=250)
    first_day_of_week: WeekDay | None = None
    currency: server_settings_schema.Currency | None = None
    timezone: core_types.IanaTimezone | None = Field(default=None, max_length=250)

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

User

Bases: UserBase

Complete users schema with administrative fields.

Note

mfa_secret is intentionally NOT part of any API-facing schema. It lives only on the SQLAlchemy model and is accessed directly by MFA verification utilities. Including it in a Pydantic schema would risk leaking the encrypted seed through responses, exports, logs, or future model_dump callers.

Attributes:

Name Type Description
access_type UserAccessType

User access level.

active StrictBool

Whether the user is active.

email_verified StrictBool

Whether email is verified.

Source code in backend/app/modules/users/users/schema.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
class User(UserBase):
    """Complete users schema with administrative fields.

    Note:
        ``mfa_secret`` is intentionally NOT part of any API-facing
        schema. It lives only on the SQLAlchemy model and is
        accessed directly by MFA verification utilities. Including
        it in a Pydantic schema would risk leaking the encrypted
        seed through responses, exports, logs, or future
        ``model_dump`` callers.

    Attributes:
        access_type: User access level.
        active: Whether the user is active.
        email_verified: Whether email is verified.
    """

    access_type: UserAccessType = Field(
        ...,
        description="User access level",
    )
    active: StrictBool = Field(
        ...,
        description="Whether the user is active",
    )
    email_verified: StrictBool = Field(
        default=False,
        description="Whether email is verified",
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

UserAccessType

Bases: StrEnum

User access level enumeration.

Attributes:

Name Type Description
REGULAR

Standard user access.

ADMIN

Administrative access.

Source code in backend/app/modules/users/users/schema.py
136
137
138
139
140
141
142
143
144
145
class UserAccessType(StrEnum):
    """User access level enumeration.

    Attributes:
        REGULAR: Standard user access.
        ADMIN: Administrative access.
    """

    REGULAR = "regular"
    ADMIN = "admin"

UserAdminCreate

Bases: UserCreate

An administrator's creation of a user, the body of POST /users.

Attributes:

Name Type Description
step_up StepUpVerification | None

The administrator's own step-up verification. Required when the new account is an administrator's; it is never a user field.

Source code in backend/app/modules/users/users/schema.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
class UserAdminCreate(UserCreate):
    """An administrator's creation of a user, the body of ``POST /users``.

    Attributes:
        step_up: The administrator's own step-up verification. Required when the new account is an
            administrator's; it is never a user field.
    """

    step_up: auth_schema.StepUpVerification | None = Field(
        default=None,
        description="The administrator's step-up verification, required to create an administrator account",
    )

    def to_create(self) -> UserCreate:
        """Return the user fields of the request, without the step-up.

        Returns:
            The user as a :class:`UserCreate`.
        """
        return UserCreate.model_validate(self.model_dump(exclude={"step_up"}))

to_create

to_create()

Return the user fields of the request, without the step-up.

Returns:

Type Description
UserCreate

The user as a :class:UserCreate.

Source code in backend/app/modules/users/users/schema.py
561
562
563
564
565
566
567
def to_create(self) -> UserCreate:
    """Return the user fields of the request, without the step-up.

    Returns:
        The user as a :class:`UserCreate`.
    """
    return UserCreate.model_validate(self.model_dump(exclude={"step_up"}))

UserAdminEdit

Bases: UserEdit

An administrator's edit of another user, the body of PATCH /users/{user_id}.

Attributes:

Name Type Description
step_up StepUpVerification | None

The administrator's own step-up verification. Required when the edit changes the email, the access type, the active flag, the username or the email-verified flag; it is never a user field.

Source code in backend/app/modules/users/users/schema.py
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
class UserAdminEdit(UserEdit):
    """An administrator's edit of another user, the body of ``PATCH /users/{user_id}``.

    Attributes:
        step_up: The administrator's own step-up verification. Required when the edit changes the email,
            the access type, the active flag, the username or the email-verified flag; it is never a user field.
    """

    step_up: auth_schema.StepUpVerification | None = Field(
        default=None,
        description=(
            "The administrator's step-up verification, required to change the email, access type, active flag, "
            "username or email-verified flag"
        ),
    )

    def to_edit(self) -> UserEdit:
        """Return the user fields of the request, without the step-up.

        Returns:
            The edit as a :class:`UserEdit`, with the same fields set.
        """
        return UserEdit.model_validate(self.model_dump(exclude={"step_up"}, exclude_unset=True))

to_edit

to_edit()

Return the user fields of the request, without the step-up.

Returns:

Type Description
UserEdit

The edit as a :class:UserEdit, with the same fields set.

Source code in backend/app/modules/users/users/schema.py
879
880
881
882
883
884
885
def to_edit(self) -> UserEdit:
    """Return the user fields of the request, without the step-up.

    Returns:
        The edit as a :class:`UserEdit`, with the same fields set.
    """
    return UserEdit.model_validate(self.model_dump(exclude={"step_up"}, exclude_unset=True))

UserAdminEditPassword

Bases: BaseModel

Schema for admin password reset operations.

Setting another user's password needs the users:write scope and the administrator's own step-up verification, not the target user's current password. Self-service password changes must use :class:UserEditPassword instead.

Attributes:

Name Type Description
password StrictStr

New password (the account's password policy applies).

step_up StepUpVerification

The administrator's own step-up verification.

Source code in backend/app/modules/users/users/schema.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
class UserAdminEditPassword(BaseModel):
    """Schema for admin password reset operations.

    Setting another user's password needs the ``users:write`` scope and the administrator's own step-up
    verification, not the target user's current password. Self-service password changes must use
    :class:`UserEditPassword` instead.

    Attributes:
        password: New password (the account's password policy applies).
        step_up: The administrator's own step-up verification.
    """

    password: StrictStr = Field(
        ...,
        max_length=credentials_contracts.PASSWORD_MAX_LENGTH,
        description="New password",
    )
    step_up: auth_schema.StepUpVerification = Field(
        ..., description="The administrator's step-up verification, required to set another user's password"
    )

    model_config = ConfigDict(extra="forbid")

UserBase

Bases: BaseModel

Base users schema with common fields.

Attributes:

Name Type Description
name UserName

User's full name (1-250 chars).

username UserUsername

Unique username (1-250 chars, alphanumeric and dots).

email UserEmail

User's email address (max 250 chars).

city StrictStr | None

User's city (max 250 chars).

birthdate RecordDate | None

User's birthdate.

preferred_language Language

Preferred language.

gender Gender

User's gender.

units Units

User units (metric, imperial).

weight_units Units | None

Weight units override (metric - kg, imperial - lb); null follows units.

height StrictInt | None

User's height in centimeters (1-300).

max_heart_rate StrictInt | None

Maximum heart rate in bpm (30-250).

first_day_of_week WeekDay

First day of the week.

currency Currency

User currency (euro, dollar, pound).

timezone IanaTimezone | None

IANA timezone the athlete lives in.

Source code in backend/app/modules/users/users/schema.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
class UserBase(BaseModel):
    """Base users schema with common fields.

    Attributes:
        name: User's full name (1-250 chars).
        username: Unique username (1-250 chars, alphanumeric
            and dots).
        email: User's email address (max 250 chars).
        city: User's city (max 250 chars).
        birthdate: User's birthdate.
        preferred_language: Preferred language.
        gender: User's gender.
        units: User units (metric, imperial).
        weight_units: Weight units override (metric - kg, imperial - lb);
            null follows units.
        height: User's height in centimeters (1-300).
        max_heart_rate: Maximum heart rate in bpm (30-250).
        first_day_of_week: First day of the week.
        currency: User currency (euro, dollar, pound).
        timezone: IANA timezone the athlete lives in.
    """

    name: UserName
    username: UserUsername
    email: UserEmail
    city: StrictStr | None = Field(
        default=None,
        max_length=250,
        description="User's city",
    )
    birthdate: core_types.RecordDate | None = Field(
        default=None,
        description="User's birthdate",
    )
    preferred_language: Language = Field(
        default=Language.ENGLISH,
        description="Preferred language",
    )
    gender: Gender = Field(
        default=Gender.UNSPECIFIED,
        description="User's gender",
    )
    units: server_settings_schema.Units = Field(
        default=server_settings_schema.Units.METRIC,
        description="User units (metric, imperial)",
    )
    weight_units: server_settings_schema.Units | None = Field(
        default=None,
        description="Weight units override (metric - kg, imperial - lb), follows 'units' when null",
    )
    height: StrictInt | None = Field(
        default=None,
        ge=1,
        le=300,
        description="Height in centimeters",
    )
    max_heart_rate: StrictInt | None = Field(
        default=None,
        ge=30,
        le=250,
        description="Maximum heart rate in bpm",
    )
    first_day_of_week: WeekDay = Field(
        default=WeekDay.MONDAY,
        description="First day of the week",
    )
    currency: server_settings_schema.Currency = Field(
        default=server_settings_schema.Currency.EURO,
        description="User currency (euro, dollar, pound)",
    )
    timezone: core_types.IanaTimezone | None = Field(
        default=None,
        max_length=250,
        description=(
            "IANA timezone the athlete lives in. Used as the fallback for activities "
            "imported without a GPS track, which would otherwise inherit the server's "
            "timezone. Null means not set."
        ),
    )

    # A default is validated too, so an enum default is stored as its value ("en"), not as the member a driver
    # would write by name ("ENGLISH").
    model_config = ConfigDict(use_enum_values=True, validate_default=True)

UserCreate

Bases: User

Users schema for admin user creation.

Attributes:

Name Type Description
password UserPassword | None

User's password (the account's password policy applies). Absent when the account is invited to choose its own, which needs mail and an active account.

Source code in backend/app/modules/users/users/schema.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
class UserCreate(User):
    """Users schema for admin user creation.

    Attributes:
        password: User's password (the account's password policy applies). Absent when the account is invited to
            choose its own, which needs mail and an active account.
    """

    name: UserRequestName
    height: UserRequestHeight | None = None
    password: UserPassword | None = None

    @field_validator("password")
    @classmethod
    def _inactive_account_needs_password(cls, value: str | None, info: ValidationInfo) -> str | None:
        """Refuse an account with neither a password nor an active state, which an invitation cannot activate.

        Args:
            value: The submitted password.
            info: Pydantic's validation info, holding the fields validated before the password.

        Returns:
            The password, unchanged.

        Raises:
            ValueError: When there is no password and the account is inactive.
        """
        if value is None and info.data.get("active") is False:
            raise ValueError("An inactive account needs a password, because an invitation cannot activate it")
        return value

UserDeletionStatus

Bases: JobStatusOpenFailure

Where a queued account deletion is.

Source code in backend/app/modules/users/users/schema.py
888
889
890
891
class UserDeletionStatus(core_job_status.JobStatusOpenFailure):
    """Where a queued account deletion is."""

    kind: Literal["user_deletion"]

UserEdit

Bases: ProfileUpdate

Users schema for an administrative edit, a partial one: a field left out is kept.

The profile fields a user may edit, plus the ones only an administrator sets. The stored columns of a user and nothing a read adds: id is the path, and external_auth_count, the photo URL and the pending email change are derived. mfa_enabled and pending_admin_approval are read-only projections and are not fields. A name already stored is re-applied as it is, even if it would not pass as new input. A writer that re-applies a whole user sends every field, as :meth:from_read does.

Attributes:

Name Type Description
username UserUsername | None

Unique username.

email UserEmail | None

User's email address.

access_type UserAccessType | None

User access level.

active StrictBool | None

Whether the user is active.

email_verified StrictBool | None

Whether email is verified.

Source code in backend/app/modules/users/users/schema.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
class UserEdit(ProfileUpdate):
    """Users schema for an administrative edit, a partial one: a field left out is kept.

    The profile fields a user may edit, plus the ones only an administrator sets. The stored columns of a user and
    nothing a read adds: ``id`` is the path, and ``external_auth_count``, the photo URL and the pending email
    change are derived. ``mfa_enabled`` and ``pending_admin_approval`` are read-only projections and are not
    fields. A name already stored is re-applied as it is, even if it would not pass as new input. A writer that
    re-applies a whole user sends every field, as :meth:`from_read` does.

    Attributes:
        username: Unique username.
        email: User's email address.
        access_type: User access level.
        active: Whether the user is active.
        email_verified: Whether email is verified.
    """

    not_clearable: ClassVar[tuple[str, ...]] = (
        *ProfileUpdate.not_clearable,
        "username",
        "email",
        "access_type",
        "active",
        "email_verified",
    )

    username: UserUsername | None = Field(
        default=None, description="Unique username (alphanumeric, dots, hyphen, underscore)"
    )
    email: UserEmail | None = Field(default=None, description="User's email address")
    access_type: UserAccessType | None = Field(default=None, description="User access level")
    active: StrictBool | None = Field(default=None, description="Whether the user is active")
    email_verified: StrictBool | None = Field(default=None, description="Whether email is verified")

    @classmethod
    def from_read(cls, user: "UserRead") -> "UserEdit":
        """Build the edit that re-applies a user as stored, for a caller that changes a few fields.

        Args:
            user: The user as read, usually with the changes already applied.

        Returns:
            The same user as an edit.
        """
        return cls.model_validate(
            user.model_dump(
                exclude={
                    "id",
                    "mfa_enabled",
                    "pending_admin_approval",
                    "photo_path",
                    "external_auth_count",
                    "version",
                    "pending_email",
                    "pending_email_expires_at",
                    "deletion_requested_at",
                }
            ),
            context={core_types.STORED_CONTEXT: True},
        )

from_read classmethod

from_read(user)

Build the edit that re-applies a user as stored, for a caller that changes a few fields.

Parameters:

Name Type Description Default
user UserRead

The user as read, usually with the changes already applied.

required

Returns:

Type Description
UserEdit

The same user as an edit.

Source code in backend/app/modules/users/users/schema.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
@classmethod
def from_read(cls, user: "UserRead") -> "UserEdit":
    """Build the edit that re-applies a user as stored, for a caller that changes a few fields.

    Args:
        user: The user as read, usually with the changes already applied.

    Returns:
        The same user as an edit.
    """
    return cls.model_validate(
        user.model_dump(
            exclude={
                "id",
                "mfa_enabled",
                "pending_admin_approval",
                "photo_path",
                "external_auth_count",
                "version",
                "pending_email",
                "pending_email_expires_at",
                "deletion_requested_at",
            }
        ),
        context={core_types.STORED_CONTEXT: True},
    )

UserEditPassword

Bases: BaseModel

Schema for password update operations (self-service).

Requires the caller's step-up verification, in step_up, before the new password is accepted. This prevents a stolen in-memory access token from being parlayed into permanent account takeover.

Attributes:

Name Type Description
password StrictStr

New password (the account's password policy applies).

revoke_other_sessions StrictBool

Whether to sign out the user's other sessions after the change.

step_up StepUpVerification

The caller's step-up verification: the current password and, when MFA is enabled, an MFA code.

Source code in backend/app/modules/users/users/schema.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
class UserEditPassword(BaseModel):
    """Schema for password update operations (self-service).

    Requires the caller's step-up verification, in ``step_up``, before the new password is accepted. This
    prevents a stolen in-memory access token from being parlayed into permanent account takeover.

    Attributes:
        password: New password (the account's password policy applies).
        revoke_other_sessions: Whether to sign out the user's other sessions after the change.
        step_up: The caller's step-up verification: the current password and, when MFA is enabled, an MFA code.
    """

    password: StrictStr = Field(
        ...,
        max_length=credentials_contracts.PASSWORD_MAX_LENGTH,
        description="New password",
    )
    revoke_other_sessions: StrictBool = Field(
        default=True,
        description=(
            "After the password change, all of the user's other sessions "
            "(keeping the current one) are revoked unless the client sends false."
        ),
    )
    step_up: auth_schema.StepUpVerification = Field(
        ..., description="Step-up verification, required to change the password"
    )

    model_config = ConfigDict(
        extra="forbid",
        validate_assignment=True,
    )

UserMe

Bases: UserRead

Extended users schema for current user profile.

Includes privacy settings and integration status.

Attributes:

Name Type Description
privacy_settings_version StrictInt | None

Version of the privacy settings, for If-Match.

integrations_version StrictInt | None

Version of the integrations, for If-Match when the Strava client is set.

is_strava_linked StrictBool | None

Strava integration status.

strava_revoked_at datetime | None

When Strava refused the refresh token, None while access is intact.

strava_data_deletion_at datetime | None

When the user's Strava data is deleted unless they relink, None while access is intact.

is_garminconnect_linked StrictBool | None

Garmin Connect status.

default_activity_visibility ActivityVisibility | None

Default visibility level.

hide_activity_start_time StrictBool | None

Hide start time setting.

hide_activity_location StrictBool | None

Hide location setting.

hide_activity_map StrictBool | None

Hide map setting.

hide_activity_hr StrictBool | None

Hide heart rate setting.

hide_activity_power StrictBool | None

Hide power setting.

hide_activity_cadence StrictBool | None

Hide cadence setting.

hide_activity_elevation StrictBool | None

Hide elevation setting.

hide_activity_speed StrictBool | None

Hide speed setting.

hide_activity_pace StrictBool | None

Hide pace setting.

hide_activity_laps StrictBool | None

Hide laps setting.

hide_activity_workout_sets_steps StrictBool | None

Hide workout sets/steps.

hide_activity_gear StrictBool | None

Hide gear setting.

discoverable StrictBool | None

Whether other users can find the user in username search.

has_local_password StrictBool

Whether the account has a local password (False for an account with no password).

Source code in backend/app/modules/users/users/schema.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
class UserMe(UserRead):
    """Extended users schema for current user profile.

    Includes privacy settings and integration status.

    Attributes:
        privacy_settings_version: Version of the privacy settings, for ``If-Match``.
        integrations_version: Version of the integrations, for ``If-Match`` when the Strava client is set.
        is_strava_linked: Strava integration status.
        strava_revoked_at: When Strava refused the refresh token, ``None`` while access is intact.
        strava_data_deletion_at: When the user's Strava data is deleted unless they relink, ``None`` while
            access is intact.
        is_garminconnect_linked: Garmin Connect status.
        default_activity_visibility: Default visibility level.
        hide_activity_start_time: Hide start time setting.
        hide_activity_location: Hide location setting.
        hide_activity_map: Hide map setting.
        hide_activity_hr: Hide heart rate setting.
        hide_activity_power: Hide power setting.
        hide_activity_cadence: Hide cadence setting.
        hide_activity_elevation: Hide elevation setting.
        hide_activity_speed: Hide speed setting.
        hide_activity_pace: Hide pace setting.
        hide_activity_laps: Hide laps setting.
        hide_activity_workout_sets_steps: Hide workout
            sets/steps.
        hide_activity_gear: Hide gear setting.
        discoverable: Whether other users can find the user in username search.
        has_local_password: Whether the account has a local
            password (False for an account with no password).
    """

    privacy_settings_version: StrictInt | None = Field(
        default=None, description="Version of the privacy settings, sent back in If-Match when they are edited"
    )
    integrations_version: StrictInt | None = Field(
        default=None,
        description="Version of the integrations, sent back in If-Match when the Strava client is set",
    )
    is_strava_linked: StrictBool | None = Field(default=None, description="Whether Strava is linked")
    strava_revoked_at: datetime | None = Field(
        default=None, description="When Strava access ended because the user revoked it on Strava"
    )
    strava_data_deletion_at: datetime | None = Field(
        default=None, description="When Strava-synced activities and gear are deleted unless Strava is relinked"
    )
    is_garminconnect_linked: StrictBool | None = Field(default=None, description="Whether Garmin Connect is linked")
    default_activity_visibility: activity_constants.ActivityVisibility | None = Field(
        default=None, description="Default activity visibility"
    )
    hide_activity_start_time: StrictBool | None = Field(default=None, description="Hide activity start time")
    hide_activity_location: StrictBool | None = Field(default=None, description="Hide activity location")
    hide_activity_map: StrictBool | None = Field(default=None, description="Hide activity map")
    hide_activity_hr: StrictBool | None = Field(default=None, description="Hide activity heart rate")
    hide_activity_power: StrictBool | None = Field(default=None, description="Hide activity power")
    hide_activity_cadence: StrictBool | None = Field(default=None, description="Hide activity cadence")
    hide_activity_elevation: StrictBool | None = Field(default=None, description="Hide activity elevation")
    hide_activity_speed: StrictBool | None = Field(default=None, description="Hide activity speed")
    hide_activity_pace: StrictBool | None = Field(default=None, description="Hide activity pace")
    hide_activity_laps: StrictBool | None = Field(default=None, description="Hide activity laps")
    hide_activity_workout_sets_steps: StrictBool | None = Field(
        default=None, description="Hide activity workout sets and steps"
    )
    hide_activity_gear: StrictBool | None = Field(default=None, description="Hide activity gear")
    discoverable: StrictBool | None = Field(default=None, description="Appear in other users' username search")
    has_local_password: StrictBool = Field(
        ...,
        description=(
            "Whether the account has a local password set. False"
            " means the account has no password; its step-up proves a"
            " fresh sign-in with an identity provider instead of a"
            " password. The raw password hash is never exposed; only"
            " this derived boolean is returned."
        ),
    )

UserPhotoRead

Bases: BaseModel

The photo a user has after an upload.

Attributes:

Name Type Description
photo_path StrictStr | None

Servable URL of the user's photo, or None when none is stored.

Source code in backend/app/modules/users/users/schema.py
648
649
650
651
652
653
654
655
class UserPhotoRead(BaseModel):
    """The photo a user has after an upload.

    Attributes:
        photo_path: Servable URL of the user's photo, or None when none is stored.
    """

    photo_path: StrictStr | None = Field(default=None, description="Servable URL of the user's photo")

UserPublicRead

Bases: BaseModel

What any signed-in viewer, or an anonymous one on a shared link, may learn about a user.

A deliberate subset of :class:UserRead: no email, birthdate, access level or account state, so a lookup cannot be used to harvest personal data or to probe who is an admin.

Attributes:

Name Type Description
id UUID

User ID.

name StrictStr

User's full name.

username StrictStr

Unique username.

city StrictStr | None

User's city.

photo_path StrictStr | None

Servable URL of the user's photo.

Source code in backend/app/modules/users/users/schema.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
class UserPublicRead(BaseModel):
    """What any signed-in viewer, or an anonymous one on a shared link, may learn about a user.

    A deliberate subset of :class:`UserRead`: no email, birthdate, access level or account
    state, so a lookup cannot be used to harvest personal data or to probe who is an admin.

    Attributes:
        id: User ID.
        name: User's full name.
        username: Unique username.
        city: User's city.
        photo_path: Servable URL of the user's photo.
    """

    id: uuid.UUID = Field(..., description="User ID")
    name: StrictStr = Field(..., description="User's full name")
    username: StrictStr = Field(..., description="Unique username")
    city: StrictStr | None = Field(default=None, description="User's city")
    photo_path: StrictStr | None = Field(default=None, description="Servable URL of the user's photo")

    model_config = ConfigDict(from_attributes=True, extra="forbid")

UserRead

Bases: User

Users schema for read operations.

Attributes:

Name Type Description
mfa_enabled StrictBool

Whether MFA is enabled.

pending_admin_approval StrictBool

Whether pending admin approval.

id UUID

User ID.

photo_path StrictStr | None

Servable URL of the user's photo, resolved from the stored storage key.

external_auth_count StrictInt

Number of external auth providers.

pending_email EmailStr | None

Address awaiting confirmation, which replaces email once confirmed.

pending_email_expires_at datetime | None

When the confirmation link for pending_email expires.

deletion_requested_at datetime | None

When the account was queued for deletion, None when no deletion is queued.

Source code in backend/app/modules/users/users/schema.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
class UserRead(User):
    """Users schema for read operations.

    Attributes:
        mfa_enabled: Whether MFA is enabled.
        pending_admin_approval: Whether pending admin approval.
        id: User ID.
        photo_path: Servable URL of the user's photo, resolved from the stored storage key.
        external_auth_count: Number of external auth providers.
        pending_email: Address awaiting confirmation, which replaces ``email`` once confirmed.
        pending_email_expires_at: When the confirmation link for ``pending_email`` expires.
        deletion_requested_at: When the account was queued for deletion, ``None`` when no deletion is queued.
    """

    mfa_enabled: StrictBool = Field(
        default=False,
        description="Whether MFA is enabled",
    )
    pending_admin_approval: StrictBool = Field(
        default=False,
        description="Whether pending admin approval",
    )
    id: uuid.UUID = Field(
        ...,
        description="User ID",
    )
    photo_path: StrictStr | None = Field(
        default=None,
        max_length=500,
        description="Servable URL of the user's photo",
    )
    external_auth_count: StrictInt = Field(
        default=0,
        ge=0,
        description="Number of external auth providers linked",
    )
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    pending_email: EmailStr | None = Field(
        default=None, description="Email address awaiting confirmation, which replaces the current one once confirmed"
    )
    pending_email_expires_at: datetime | None = Field(
        default=None, description="When the confirmation link for the pending email address expires"
    )
    deletion_requested_at: datetime | None = Field(
        default=None, description="When the account was queued for deletion; null when no deletion is queued"
    )

UserSignup

Bases: BaseModel

Users schema for a public sign-up request: only what an account needs.

The rest of the profile starts from the UserBase defaults and is edited after signing in.

Attributes:

Name Type Description
name UserRequestName

User's full name (1-250 chars).

username UserUsername

Unique username (1-250 chars, alphanumeric and dots).

email UserEmail

User's email address (max 250 chars).

password UserPassword | None

User's password; the account's password policy applies. Absent when the password is chosen at email verification.

preferred_language Language

Language of the account's emails and interface.

Source code in backend/app/modules/users/users/schema.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
class UserSignup(BaseModel):
    """Users schema for a public sign-up request: only what an account needs.

    The rest of the profile starts from the ``UserBase`` defaults and is edited after signing in.

    Attributes:
        name: User's full name (1-250 chars).
        username: Unique username (1-250 chars, alphanumeric and dots).
        email: User's email address (max 250 chars).
        password: User's password; the account's password policy applies. Absent when the password is chosen at
            email verification.
        preferred_language: Language of the account's emails and interface.
    """

    name: UserRequestName
    username: UserUsername
    email: UserEmail
    password: UserPassword | None = None
    preferred_language: Language = Field(
        default=Language.ENGLISH,
        description="Preferred language",
    )

    model_config = ConfigDict(use_enum_values=True, validate_default=True, extra="forbid")

UsernameChange

Bases: BaseModel

Self-service username change, authorised by step-up verification.

Attributes:

Name Type Description
username UserUsername

The new username.

revoke_other_sessions StrictBool

Whether to sign out the user's other sessions after the change.

step_up StepUpVerification

The caller's step-up verification.

Source code in backend/app/modules/users/users/schema.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
class UsernameChange(BaseModel):
    """Self-service username change, authorised by step-up verification.

    Attributes:
        username: The new username.
        revoke_other_sessions: Whether to sign out the user's other sessions after the change.
        step_up: The caller's step-up verification.
    """

    username: UserUsername
    revoke_other_sessions: StrictBool = Field(
        default=True,
        description=(
            "After the username change, all of the user's other sessions "
            "(keeping the current one) are revoked unless the client sends false."
        ),
    )
    step_up: auth_schema.StepUpVerification = Field(
        ..., description="Step-up verification, required to change the username"
    )

    model_config = ConfigDict(extra="forbid")

WeekDay

Bases: Enum

Days of the week enumeration.

Attributes:

Name Type Description
SUNDAY

Sunday.

MONDAY

Monday.

TUESDAY

Tuesday.

WEDNESDAY

Wednesday.

THURSDAY

Thursday.

FRIDAY

Friday.

SATURDAY

Saturday.

Source code in backend/app/modules/users/users/schema.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class WeekDay(Enum):
    """Days of the week enumeration.

    Attributes:
        SUNDAY: Sunday.
        MONDAY: Monday.
        TUESDAY: Tuesday.
        WEDNESDAY: Wednesday.
        THURSDAY: Thursday.
        FRIDAY: Friday.
        SATURDAY: Saturday.
    """

    SUNDAY = "sunday"
    MONDAY = "monday"
    TUESDAY = "tuesday"
    WEDNESDAY = "wednesday"
    THURSDAY = "thursday"
    FRIDAY = "friday"
    SATURDAY = "saturday"

normalize_access_type

normalize_access_type(access_type)

Return the string value of an access type.

Accepts either a :class:UserAccessType enum member or its raw string value and always returns the plain string form (e.g. "admin" or "regular").

Parameters:

Name Type Description Default
access_type UserAccessType | str

A UserAccessType member or its string value.

required

Returns:

Type Description
str

The access type as a plain string.

Source code in backend/app/modules/users/users/schema.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def normalize_access_type(access_type: "UserAccessType | str") -> str:
    """Return the string value of an access type.

    Accepts either a :class:`UserAccessType` enum member or its raw
    string value and always returns the plain string form (e.g.
    ``"admin"`` or ``"regular"``).

    Args:
        access_type: A ``UserAccessType`` member or its string value.

    Returns:
        The access type as a plain string.
    """
    return access_type.value if isinstance(access_type, UserAccessType) else access_type

Users profile

The profile router also serves the privacy settings routes (/profile/privacy). The profile's sessions, two-step verification and identity provider links (/profile/sessions, /profile/mfa and /profile/identity-providers) are served by the auth module; see Authentication.

Profile API endpoints for user management and operations.

This module provides FastAPI endpoints for: - User profile retrieval and updates - Password and privacy settings management - Profile photo upload and deletion - Profile data export and import

The signed-in user's own sessions, two-step verification and identity provider links are served under the same /profile prefix by the auth module (modules.auth.sessions, modules.auth.mfa and modules.auth.identity_providers, each in a profile_router).

cancel_profile_email_change

cancel_profile_email_change(request, token_user_id, db)

Cancel the pending email change, so its confirmation link stops working.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session.

required
Source code in backend/app/modules/users/users_profile/router.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@router.delete(
    "/email/change",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:security"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def cancel_profile_email_change(
    request: Request,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
) -> None:
    """Cancel the pending email change, so its confirmation link stops working.

    Args:
        request: The incoming request, read by the rate limiter.
        token_user_id: User ID from access token.
        db: Database session.
    """
    profile_service.cancel_email_change(token_user_id, db)

delete_my_account

delete_my_account(request, response, body, token_user_id, token_session_id, step_up_store, state, storage, mail, db)

Queue the deletion of the authenticated user's account and all of their data.

Requires step-up verification: the current password (or, for an account without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. The account is signed out and deactivated at once and a background job erases the data, which is permanent and cannot be undone. Export the profile first to keep a copy. The browser's refresh-token cookie is cleared on the response.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
response Response

The response, which receives the cookie-deletion headers.

required
body StepUpRequest

The step-up verification.

required
token_user_id CurrentUserId

User ID from access token.

required
token_session_id CurrentSessionId

Session ID from access token.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
state PlatformState

The platform state provider.

required
storage Storage

The platform storage provider.

required
mail Mail

The platform mail provider.

required
db DbSession

Database session.

required

Returns:

Type Description
UserDeletionStatus

The deletion's initial status.

Source code in backend/app/modules/users/users_profile/router.py
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
@router.post(
    "/delete-account",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=users_schema.UserDeletionStatus,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:security"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def delete_my_account(
    request: Request,
    response: Response,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    state: core_dependencies.PlatformState,
    storage: core_dependencies.Storage,
    mail: core_dependencies.Mail,
    db: core_dependencies.DbSession,
) -> users_schema.UserDeletionStatus:
    """Queue the deletion of the authenticated user's account and all of their data.

    Requires step-up verification: the current password (or, for an account without one, a fresh
    identity-provider sign-in), and an MFA code when MFA is enabled. The
    account is signed out and deactivated at once and a background job erases the data, which is
    permanent and cannot be undone. Export the profile first to keep a copy. The browser's
    refresh-token cookie is cleared on the response.

    Args:
        request: The incoming request, read by the rate limiter.
        response: The response, which receives the cookie-deletion headers.
        body: The step-up verification.
        token_user_id: User ID from access token.
        token_session_id: Session ID from access token.
        step_up_store: Step-up lockout store.
        state: The platform state provider.
        storage: The platform storage provider.
        mail: The platform mail provider.
        db: Database session.

    Returns:
        The deletion's initial status.
    """
    deletion = profile_service.delete_account(
        token_user_id, token_session_id, body.step_up, step_up_store, state, storage, mail, db
    )
    authentication_dependencies.clear_refresh_token_cookies(response, environment=core_config.settings.ENVIRONMENT)
    return deletion

delete_profile_photo

delete_profile_photo(request, token_user_id, storage, db)

Delete authenticated user's profile photo.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
token_user_id CurrentUserId

User ID from access token.

required
storage Storage

The platform storage provider.

required
db DbSession

Database session.

required
Source code in backend/app/modules/users/users_profile/router.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
@router.delete(
    "/photo",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_profile_photo(
    request: Request,
    token_user_id: auth_dependencies.CurrentUserId,
    storage: core_dependencies.Storage,
    db: core_dependencies.DbSession,
) -> None:
    """Delete authenticated user's profile photo.

    Args:
        request: The incoming request, read by the rate limiter.
        token_user_id: User ID from access token.
        storage: The platform storage provider.
        db: Database session.
    """
    profile_photo_service.delete_photo(token_user_id, storage, db)

download_profile_export

download_profile_export(request, token_user_id, token_session_id, export_states, storage)

Download the authenticated user's finished profile export.

Only the session that requested the export, and passed step-up for it, can download it; any other session gets 404, as when no finished export exists.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
token_user_id CurrentUserId

User ID from access token.

required
token_session_id CurrentSessionId

Session ID from access token.

required
export_states ProfileExportStateStoreDep

Shared store of the export's state.

required
storage Storage

The platform storage provider.

required

Returns:

Type Description
StreamingResponse

Streaming response with the ZIP archive.

Source code in backend/app/modules/users/users_profile/router.py
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
@router.get(
    "/export/download",
    response_class=StreamingResponse,
    responses=core_openapi_contract.binary_response(
        "application/zip",
        description="The ZIP archive of the export.",
        headers=core_openapi_contract.NO_STORE_RESPONSE_HEADERS,
    ),
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:export"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def download_profile_export(
    request: Request,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    export_states: profile_dependencies.ProfileExportStateStoreDep,
    storage: core_dependencies.Storage,
) -> StreamingResponse:
    """Download the authenticated user's finished profile export.

    Only the session that requested the export, and passed step-up for it, can download it; any other session
    gets 404, as when no finished export exists.

    Args:
        request: The incoming request, read by the rate limiter.
        token_user_id: User ID from access token.
        token_session_id: Session ID from access token.
        export_states: Shared store of the export's state.
        storage: The platform storage provider.

    Returns:
        Streaming response with the ZIP archive.
    """
    chunks, size = profile_export_job_service.open_export(token_user_id, token_session_id, export_states, storage)
    return StreamingResponse(
        chunks,
        media_type="application/zip",
        headers={
            "Content-Disposition": f"attachment; filename=user_{token_user_id}_export.zip",
            "Content-Length": str(size),
            **core_cache_control.NO_STORE_HEADERS,
        },
    )

edit_profile

edit_profile(request, response, user_attributtes, token_user_id, db, if_match)

Edit self-service profile fields for the authenticated user.

Uses an explicit allow-list (:class:users_schema.ProfileUpdate) so administrative attributes such as access_type, active, mfa_enabled, mfa_secret, email_verified, and pending_admin_approval cannot be modified through this endpoint, even if a malicious client submits them.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
response Response

The response, which carries the user's new ETag.

required
user_attributtes ProfileUpdate

Allow-listed profile updates.

required
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session.

required
if_match IfMatch

The If-Match precondition, the version the client read.

required

Returns:

Type Description
UserMe

The edited profile; its version is also sent as the ETag.

Source code in backend/app/modules/users/users_profile/router.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@router.patch(
    "",
    response_model=users_schema.UserMe,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_profile(
    request: Request,
    response: Response,
    user_attributtes: users_schema.ProfileUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    if_match: core_dependencies.IfMatch,
) -> users_schema.UserMe:
    """Edit self-service profile fields for the authenticated user.

    Uses an explicit allow-list (:class:`users_schema.ProfileUpdate`)
    so administrative attributes such as ``access_type``,
    ``active``, ``mfa_enabled``, ``mfa_secret``, ``email_verified``,
    and ``pending_admin_approval`` cannot be modified through this
    endpoint, even if a malicious client submits them.

    Args:
        request: The incoming request, read by the rate limiter.
        response: The response, which carries the user's new ETag.
        user_attributtes: Allow-listed profile updates.
        token_user_id: User ID from access token.
        db: Database session.
        if_match: The ``If-Match`` precondition, the ``version`` the client read.

    Returns:
        The edited profile; its ``version`` is also sent as the ETag.
    """
    profile = profile_service.edit_profile(token_user_id, user_attributtes, db, if_match=if_match)
    core_etag.set_etag(response, profile.version)
    return profile

edit_profile_email

edit_profile_email(request, response, email_change, token_user_id, token_session_id, step_up_store, state, db)

Request a change of the authenticated user's email after step-up verification.

The address is where password resets go, so the caller must re-prove identity with the current password (and an MFA code when MFA is enabled). The current address stays in place until the link emailed to the new one is followed, and the new address is shown as pending_email meanwhile. A later request replaces an earlier one, and the current address cancels a pending change. When the server cannot send mail the address changes at once, unverified. The user's other sessions are revoked when the request asks for it. The answer is the profile as it stands afterwards, so the client can tell a pending change (pending_email) from an applied one. An address another account holds is answered exactly like a free one, so the request does not reveal which addresses are registered; that account's holder is emailed a notice instead of a confirmation link.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
response Response

The response, which carries the user's current ETag.

required
email_change EmailChange

The new address with the step-up verification.

required
token_user_id CurrentUserId

User ID from access token.

required
token_session_id Annotated[UUID, Depends(get_sid_from_access_token)]

Session ID of the caller, preserved when other sessions are revoked.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
state PlatformState

The platform state provider, for the notice cooldown.

required
db DbSession

Database session.

required

Returns:

Type Description
UserMe

The profile after the request; its version is also sent as the ETag.

Raises:

Type Description
HTTPException

403 if step-up verification fails; 409 if another account uses the address and the server cannot send mail.

Source code in backend/app/modules/users/users_profile/router.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
@router.post(
    "/email/change",
    response_model=users_schema.UserMe,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:security"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def edit_profile_email(
    request: Request,
    response: Response,
    email_change: users_schema.EmailChange,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: Annotated[
        uuid.UUID,
        Depends(auth_dependencies.get_sid_from_access_token),
    ],
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    state: core_dependencies.PlatformState,
    db: core_dependencies.DbSession,
) -> users_schema.UserMe:
    """Request a change of the authenticated user's email after step-up verification.

    The address is where password resets go, so the caller must re-prove identity with the
    current password (and an MFA code when MFA is enabled). The current address stays in place
    until the link emailed to the new one is followed, and the new address is shown as
    ``pending_email`` meanwhile. A later request replaces an earlier one, and the current address
    cancels a pending change. When the server cannot send mail the address changes at once, unverified.
    The user's other sessions are revoked when the request asks for it. The answer is the profile as it
    stands afterwards, so the client can tell a pending change (``pending_email``) from an applied one.
    An address another account holds is answered exactly like a free one, so the request does not reveal
    which addresses are registered; that account's holder is emailed a notice instead of a confirmation link.

    Args:
        request: The incoming request, read by the rate limiter.
        response: The response, which carries the user's current ETag.
        email_change: The new address with the step-up verification.
        token_user_id: User ID from access token.
        token_session_id: Session ID of the caller, preserved when other sessions are revoked.
        step_up_store: Step-up lockout store.
        state: The platform state provider, for the notice cooldown.
        db: Database session.

    Returns:
        The profile after the request; its ``version`` is also sent as the ETag.

    Raises:
        HTTPException: 403 if step-up verification fails; 409 if another account uses the address and the server
            cannot send mail.
    """
    profile = profile_service.change_email(token_user_id, email_change, token_session_id, step_up_store, state, db)
    core_etag.set_etag(response, profile.version)
    return profile

edit_profile_password

edit_profile_password(request, user_attributtes, token_user_id, token_session_id, step_up_store, db)

Update user password after step-up verification.

Requires the caller to re-prove identity in step_up with the current password — and an MFA code when MFA is enabled — before the new password is accepted. This prevents a stolen access token alone from being parlayed into permanent account takeover.

All of the user's other sessions are revoked after the change while the current session is preserved, unless the request sets revoke_other_sessions to false, so a password change evicts a suspected attacker without logging the caller out.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_attributtes UserEditPassword

Schema with the new password, the step-up verification, and the optional revoke_other_sessions flag.

required
token_user_id CurrentUserId

ID of the user extracted from the access token.

required
token_session_id Annotated[UUID, Depends(get_sid_from_access_token)]

Session ID of the caller, preserved when other sessions are revoked.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
db DbSession

Database session.

required

Raises:

Type Description
StepUpFailedError

403 step-up-failed if step-up verification fails.

PasswordPolicyError

422 if the new password is too short, too common or matches the account's details.

Source code in backend/app/modules/users/users_profile/router.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
@router.post(
    "/password/change",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:security"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def edit_profile_password(
    request: Request,
    user_attributtes: users_schema.UserEditPassword,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: Annotated[
        uuid.UUID,
        Depends(auth_dependencies.get_sid_from_access_token),
    ],
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
) -> None:
    """Update user password after step-up verification.

    Requires the caller to re-prove identity in ``step_up`` with the current
    password — and an MFA code when MFA is enabled — before the
    new password is accepted. This prevents a stolen access
    token alone from being parlayed into permanent account
    takeover.

    All of the user's other sessions are revoked after the change
    while the current session is preserved, unless the request sets
    ``revoke_other_sessions`` to false, so a password change evicts
    a suspected attacker without logging the caller out.

    Args:
        request: The incoming request, read by the rate limiter.
        user_attributtes: Schema with the new password, the step-up
            verification, and the optional ``revoke_other_sessions`` flag.
        token_user_id: ID of the user extracted from the access
            token.
        token_session_id: Session ID of the caller, preserved when
            other sessions are revoked.
        step_up_store: Step-up lockout store.
        db: Database session.

    Raises:
        StepUpFailedError: 403 ``step-up-failed`` if step-up verification fails.
        PasswordPolicyError: 422 if the new password is too short, too common or matches the account's details.
    """
    profile_service.change_password(token_user_id, user_attributtes, token_session_id, step_up_store, db)

edit_profile_privacy_settings

edit_profile_privacy_settings(request, response, user_privacy_settings, token_user_id, db, if_match)

Edit privacy settings for authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
response Response

The response, which carries the settings' new ETag.

required
user_privacy_settings UserPrivacySettingsUpdate

New privacy settings.

required
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session.

required
if_match IfMatch

The If-Match precondition, the privacy_settings_version the client read.

required

Returns:

Type Description
UserPrivacySettingsRead

The edited settings; their version is also sent as the ETag.

Source code in backend/app/modules/users/users_profile/router.py
310
311
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
@router.patch(
    "/privacy",
    response_model=users_privacy_settings_schema.UserPrivacySettingsRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_profile_privacy_settings(
    request: Request,
    response: Response,
    user_privacy_settings: users_privacy_settings_schema.UserPrivacySettingsUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    if_match: core_dependencies.IfMatch,
) -> users_privacy_settings_schema.UserPrivacySettingsRead:
    """Edit privacy settings for authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        response: The response, which carries the settings' new ETag.
        user_privacy_settings: New privacy settings.
        token_user_id: User ID from access token.
        db: Database session.
        if_match: The ``If-Match`` precondition, the ``privacy_settings_version`` the client read.

    Returns:
        The edited settings; their ``version`` is also sent as the ETag.
    """
    updated = profile_service.edit_privacy_settings(token_user_id, user_privacy_settings, db, if_match=if_match)
    core_etag.set_etag(response, updated.version)
    return updated

edit_profile_username

edit_profile_username(request, response, username_change, token_user_id, token_session_id, step_up_store, db)

Change the authenticated user's username after step-up verification.

The username is the sign-in name, so the caller must re-prove identity with the current password (and an MFA code when MFA is enabled). It is stored in lower case, and re-submitting the current username changes nothing. The user's other sessions are revoked when the request asks for it, and the account's email address is told of the change. The answer is the updated profile.

Source code in backend/app/modules/users/users_profile/router.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
@router.post(
    "/username/change",
    response_model=users_schema.UserMe,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:security"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def edit_profile_username(
    request: Request,
    response: Response,
    username_change: users_schema.UsernameChange,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: Annotated[
        uuid.UUID,
        Depends(auth_dependencies.get_sid_from_access_token),
    ],
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    db: core_dependencies.DbSession,
) -> users_schema.UserMe:
    """Change the authenticated user's username after step-up verification.

    The username is the sign-in name, so the caller must re-prove identity with the current password (and an
    MFA code when MFA is enabled). It is stored in lower case, and re-submitting the current username changes
    nothing. The user's other sessions are revoked when the request asks for it, and the account's email address
    is told of the change. The answer is the updated profile.
    """
    profile = profile_service.change_username(token_user_id, username_change, token_session_id, step_up_store, db)
    core_etag.set_etag(response, profile.version)
    return profile

export_profile_data

export_profile_data(request, response, body, token_user_id, token_session_id, step_up_store, export_states, db)

Queue an export of all profile data as a ZIP archive.

Requires step-up verification: the current password (or, for an account without one, a fresh identity-provider sign-in), and an MFA code when MFA is enabled. A worker builds the archive; poll GET /jobs/{job_id} for the outcome and fetch it from GET /profile/export/download.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
response Response

The response, which names the job and when to poll it.

required
body StepUpRequest

The step-up verification.

required
token_user_id CurrentUserId

User ID from access token.

required
token_session_id CurrentSessionId

Session ID from access token.

required
step_up_store Annotated[StepUpStore, Depends(get_step_up_attempts)]

Step-up lockout store.

required
export_states ProfileExportStateStoreDep

Shared store of the export's state.

required
db DbSession

Database session.

required

Returns:

Type Description
ProfileExportStatus

The queued export's status.

Source code in backend/app/modules/users/users_profile/router.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
@router.post(
    "/export",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=profile_schema.ProfileExportStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:export"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def export_profile_data(
    request: Request,
    response: Response,
    body: auth_schema.StepUpRequest,
    token_user_id: auth_dependencies.CurrentUserId,
    token_session_id: auth_dependencies.CurrentSessionId,
    step_up_store: Annotated[
        auth_dependencies.StepUpStore,
        Depends(auth_dependencies.get_step_up_attempts),
    ],
    export_states: profile_dependencies.ProfileExportStateStoreDep,
    db: core_dependencies.DbSession,
) -> profile_schema.ProfileExportStatus:
    """Queue an export of all profile data as a ZIP archive.

    Requires step-up verification: the current password (or, for an account without one, a fresh
    identity-provider sign-in), and an MFA code when MFA is enabled. A worker builds the archive;
    poll ``GET /jobs/{job_id}`` for the outcome and fetch it from ``GET /profile/export/download``.

    Args:
        request: The incoming request, read by the rate limiter.
        response: The response, which names the job and when to poll it.
        body: The step-up verification.
        token_user_id: User ID from access token.
        token_session_id: Session ID from access token.
        step_up_store: Step-up lockout store.
        export_states: Shared store of the export's state.
        db: Database session.

    Returns:
        The queued export's status.
    """
    queued = profile_export_job_service.request_export(
        token_user_id, token_session_id, body.step_up, step_up_store, export_states, db
    )
    core_location.set_job_location(response, request, queued.id, profile_constants.EXPORT_POLL_SECONDS)
    return queued

import_profile_data

import_profile_data(request, response, file, token_user_id, import_states, storage, db)

Queue a profile import from a ZIP archive.

The archive is validated and staged, and a worker imports it; poll GET /jobs/{job_id} for the outcome. The database part is all-or-nothing, so a failed import leaves nothing behind.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
response Response

The response, which names the job and when to poll it.

required
file UploadFile

ZIP file containing profile data.

required
token_user_id CurrentUserId

User ID from access token.

required
import_states ProfileImportStateStoreDep

Shared store of the import's state.

required
storage Storage

The platform storage provider.

required
db DbSession

Database session.

required

Returns:

Type Description
ProfileImportStatus

The queued import's status.

Source code in backend/app/modules/users/users_profile/router.py
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@router.post(
    "/import",
    status_code=status.HTTP_202_ACCEPTED,
    response_model=profile_schema.ProfileImportStatus,
    responses=core_location.ACCEPTED_RESPONSE,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:export"])],
    openapi_extra=core_middleware_body_limit.upload_limit(
        core_file_uploads.max_bytes_for(core_file_uploads.UploadKind.PROFILE_ARCHIVE)
    ),
)
@core_rate_limit.limiter.limit(core_rate_limit.UPLOAD)
def import_profile_data(
    request: Request,
    response: Response,
    file: UploadFile,
    token_user_id: auth_dependencies.CurrentUserId,
    import_states: profile_dependencies.ProfileImportStateStoreDep,
    storage: core_dependencies.Storage,
    db: core_dependencies.DbSession,
) -> profile_schema.ProfileImportStatus:
    """Queue a profile import from a ZIP archive.

    The archive is validated and staged, and a worker imports it; poll ``GET /jobs/{job_id}`` for
    the outcome. The database part is all-or-nothing, so a failed import leaves nothing behind.

    Args:
        request: The incoming request, read by the rate limiter.
        response: The response, which names the job and when to poll it.
        file: ZIP file containing profile data.
        token_user_id: User ID from access token.
        import_states: Shared store of the import's state.
        storage: The platform storage provider.
        db: Database session.

    Returns:
        The queued import's status.
    """
    queued = profile_import_job_service.request_import(
        token_user_id,
        partial(core_file_uploads.save_validated_upload_sync, file),
        import_states,
        storage,
        db,
    )
    core_location.set_job_location(response, request, queued.id, profile_constants.IMPORT_POLL_SECONDS)
    return queued

put_profile_image

put_profile_image(request, file, token_user_id, storage, db, response)

Set the authenticated user's profile image, with security validation.

Answers 201 when the user had no photo and 200 when it replaced one.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
file UploadFile

Image file to upload.

required
token_user_id CurrentUserId

User ID from access token.

required
storage Storage

The platform storage provider.

required
db DbSession

Database session.

required
response Response

The response, whose status is 200 when a photo was replaced.

required

Returns:

Type Description
UserPhotoRead

The servable URL of the new photo.

Source code in backend/app/modules/users/users_profile/router.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
@router.put(
    "/photo",
    status_code=status.HTTP_201_CREATED,
    response_model=users_schema.UserPhotoRead,
    responses=core_openapi_contract.replaced_response(users_schema.UserPhotoRead),
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
    openapi_extra=core_middleware_body_limit.upload_limit(
        core_file_uploads.max_bytes_for(core_file_uploads.UploadKind.IMAGE)
    ),
)
@core_rate_limit.limiter.limit(core_rate_limit.UPLOAD)
def put_profile_image(
    request: Request,
    file: UploadFile,
    token_user_id: auth_dependencies.CurrentUserId,
    storage: core_dependencies.Storage,
    db: core_dependencies.DbSession,
    response: Response,
) -> users_schema.UserPhotoRead:
    """Set the authenticated user's profile image, with security validation.

    Answers 201 when the user had no photo and 200 when it replaced one.

    Args:
        request: The incoming request, read by the rate limiter.
        file: Image file to upload.
        token_user_id: User ID from access token.
        storage: The platform storage provider.
        db: Database session.
        response: The response, whose status is 200 when a photo was replaced.

    Returns:
        The servable URL of the new photo.
    """
    photo, replaced = profile_photo_service.set_photo(token_user_id, file, storage, db)
    if replaced:
        response.status_code = status.HTTP_200_OK
    return photo

read_profile_privacy_settings

read_profile_privacy_settings(token_user_id, db, response)

Retrieve the authenticated user's privacy settings.

The ETag is the settings' version, which a later PATCH /profile/privacy echoes in If-Match.

Source code in backend/app/modules/users/users_profile/router.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
@router.get(
    "/privacy",
    response_model=users_privacy_settings_schema.UserPrivacySettingsRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
def read_profile_privacy_settings(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> users_privacy_settings_schema.UserPrivacySettingsRead:
    """Retrieve the authenticated user's privacy settings.

    The ETag is the settings' version, which a later ``PATCH /profile/privacy`` echoes in ``If-Match``.
    """
    privacy_settings = profile_service.get_privacy_settings(token_user_id, db)
    core_etag.set_etag(response, privacy_settings.version)
    return privacy_settings

read_users_me

read_users_me(token_user_id, db, response)

Retrieve authenticated user profile with integrations.

The ETag is the user's version, which a later PATCH /profile echoes in If-Match. The privacy settings have their own version, privacy_settings_version.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session.

required
response Response

The response, which carries the user's ETag.

required

Returns:

Type Description
UserMe

User object with integration and privacy settings.

Source code in backend/app/modules/users/users_profile/router.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@router.get(
    "",
    response_model=users_schema.UserMe,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
def read_users_me(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> users_schema.UserMe:
    """Retrieve authenticated user profile with integrations.

    The ETag is the user's version, which a later ``PATCH /profile`` echoes in ``If-Match``. The
    privacy settings have their own version, ``privacy_settings_version``.

    Args:
        token_user_id: User ID from access token.
        db: Database session.
        response: The response, which carries the user's ETag.

    Returns:
        User object with integration and privacy settings.
    """
    profile = profile_service.get_profile(token_user_id, db)
    core_etag.set_etag(response, profile.version)
    return profile

resend_profile_email_change

resend_profile_email_change(request, token_user_id, state, db)

Send the confirmation email of the pending email change again.

The answer is the same whether or not an email was queued: there may be no pending change, the server may not send mail, or an email may already have gone out within the cooldown.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
token_user_id CurrentUserId

User ID from access token.

required
state PlatformState

The platform state provider, for the resend cooldown.

required
db DbSession

Database session.

required
Source code in backend/app/modules/users/users_profile/router.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
@router.post(
    "/email/change/resend",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account:security"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def resend_profile_email_change(
    request: Request,
    token_user_id: auth_dependencies.CurrentUserId,
    state: core_dependencies.PlatformState,
    db: core_dependencies.DbSession,
) -> None:
    """Send the confirmation email of the pending email change again.

    The answer is the same whether or not an email was queued: there may be no pending change,
    the server may not send mail, or an email may already have gone out within the cooldown.

    Args:
        request: The incoming request, read by the rate limiter.
        token_user_id: User ID from access token.
        state: The platform state provider, for the resend cooldown.
        db: Database session.
    """
    profile_service.resend_email_change(token_user_id, state, db)

Pydantic response shapes for the profile import and export.

ProfileExportStatus

Bases: JobStatus

Where the authenticated user's profile export is.

Attributes:

Name Type Description
error_code ExportFailure | None

Why the export failed; set only when it failed.

size_bytes int | None

Size of the archive; set only when it succeeded and can be downloaded.

expires_at datetime | None

When the download stops working; set only when it succeeded and can be downloaded.

Source code in backend/app/modules/users/users_profile/schema.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class ProfileExportStatus(core_job_status.JobStatus):
    """Where the authenticated user's profile export is.

    Attributes:
        error_code: Why the export failed; set only when it failed.
        size_bytes: Size of the archive; set only when it succeeded and can be downloaded.
        expires_at: When the download stops working; set only when it succeeded and can be downloaded.
    """

    model_config = ConfigDict(extra="forbid")

    kind: Literal["profile_export"]
    error_code: profile_constants.ExportFailure | None = Field(default=None, description="Reason the export failed")
    size_bytes: int | None = Field(default=None, description="Archive size in bytes, once it succeeded")
    expires_at: datetime | None = Field(
        default=None, description="Instant after which the download stops working, once it succeeded"
    )

ProfileImportStatus

Bases: JobStatus

Where the authenticated user's profile import is.

Attributes:

Name Type Description
error_code ImportFailure | None

Why the import failed; set only when it failed.

imported dict[str, int] | None

How many items of each kind were imported; set only when it succeeded.

Source code in backend/app/modules/users/users_profile/schema.py
36
37
38
39
40
41
42
43
44
45
46
class ProfileImportStatus(core_job_status.JobStatus):
    """Where the authenticated user's profile import is.

    Attributes:
        error_code: Why the import failed; set only when it failed.
        imported: How many items of each kind were imported; set only when it succeeded.
    """

    kind: Literal["profile_import"]
    error_code: profile_constants.ImportFailure | None = Field(default=None, description="Reason the import failed")
    imported: dict[str, int] | None = Field(default=None, description="Items imported per kind, once it succeeded")

UserProfileOverviewRead

Bases: BaseModel

Public profile and summary metrics displayed on a user's profile page.

Attributes:

Name Type Description
user UserPublicRead

The profile's public user projection.

week_stats ActivityStatsRead

Visible per-sport activity totals for the current week.

month_stats ActivityStatsRead

Visible per-sport activity totals for the current month.

month_activity_count int

Visible activity count for the current month.

followers_count int | None

Accepted followers, or None when the viewer cannot see the network.

following_count int | None

Accepted followees, or None when the viewer cannot see the network.

Source code in backend/app/modules/users/users_profile/schema.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class UserProfileOverviewRead(BaseModel):
    """Public profile and summary metrics displayed on a user's profile page.

    Attributes:
        user: The profile's public user projection.
        week_stats: Visible per-sport activity totals for the current week.
        month_stats: Visible per-sport activity totals for the current month.
        month_activity_count: Visible activity count for the current month.
        followers_count: Accepted followers, or None when the viewer cannot see the network.
        following_count: Accepted followees, or None when the viewer cannot see the network.
    """

    user: users_schema.UserPublicRead
    week_stats: activity_schema.ActivityStatsRead
    month_stats: activity_schema.ActivityStatsRead
    month_activity_count: int = Field(..., ge=0)
    followers_count: int | None = Field(default=None, ge=0)
    following_count: int | None = Field(default=None, ge=0)

    model_config = ConfigDict(from_attributes=True, extra="forbid")

Users goals

User goals API endpoints.

create_user_goal

create_user_goal(request, user_goal, token_user_id, db, response)

Create a new goal for the authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_goal UserGoalCreate

Goal data to create.

required
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session dependency.

required
response Response

The response, whose Location names where the goal is read.

required

Returns:

Type Description
UserGoalRead

The created goal object.

Source code in backend/app/modules/users/users_goals/router.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
@router.post(
    "",
    response_model=user_goals_schema.UserGoalRead,
    status_code=status.HTTP_201_CREATED,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def create_user_goal(
    request: Request,
    user_goal: user_goals_schema.UserGoalCreate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> user_goals_schema.UserGoalRead:
    """Create a new goal for the authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        user_goal: Goal data to create.
        token_user_id: User ID from access token.
        db: Database session dependency.
        response: The response, whose ``Location`` names where the goal is read.

    Returns:
        The created goal object.
    """
    created = user_goals_service.create_goal(token_user_id, user_goal, db)
    core_location.set_location(response, request, "get_user_goal", goal_id=created.id)
    core_etag.set_etag(response, created.version)
    return created

delete_user_goal

delete_user_goal(request, goal_id, token_user_id, if_match, db)

Delete a goal for the authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
goal_id UuidId

ID of the goal to delete.

required
token_user_id CurrentUserId

User ID from access token.

required
if_match IfMatch

The If-Match precondition.

required
db DbSession

Database session dependency.

required

Raises:

Type Description
PreconditionFailedError

If the goal changed since the client read it.

Source code in backend/app/modules/users/users_goals/router.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
@router.delete(
    "/{goal_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    response_model=None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_user_goal(
    request: Request,
    goal_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    if_match: core_dependencies.IfMatch,
    db: core_dependencies.DbSession,
) -> None:
    """Delete a goal for the authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        goal_id: ID of the goal to delete.
        token_user_id: User ID from access token.
        if_match: The ``If-Match`` precondition.
        db: Database session dependency.

    Raises:
        PreconditionFailedError: If the goal changed since the client read it.
    """
    user_goals_service.delete_goal(token_user_id, goal_id, db, if_match=if_match)

get_user_goal

get_user_goal(goal_id, token_user_id, db, response)

Retrieve one of the authenticated user's goals; its ETag is the version for If-Match.

Source code in backend/app/modules/users/users_goals/router.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
@router.get(
    "/{goal_id}",
    response_model=user_goals_schema.UserGoalRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
def get_user_goal(
    goal_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> user_goals_schema.UserGoalRead:
    """Retrieve one of the authenticated user's goals; its ``ETag`` is the version for ``If-Match``."""
    goal = user_goals_service.get_goal(token_user_id, goal_id, db)
    core_etag.set_etag(response, goal.version)
    return goal

get_user_goals

get_user_goals(token_user_id, page, db, interval=None, activity_type=None, goal_type=None)

Retrieve one page of goals for the authenticated user with optional filters.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

User ID from access token.

required
page ListPage

The requested window.

required
db DbSession

Database session dependency.

required
interval Annotated[Interval | None, Query(description='Filter by goal interval')]

Optional filter by goal interval.

None
activity_type Annotated[GoalActivityType | None, Query(description='Filter by activity type')]

Optional filter by activity type.

None
goal_type Annotated[GoalType | None, Query(description='Filter by goal type')]

Optional filter by goal type.

None

Returns:

Type Description
UserGoalPage

The page of user goals matching the filters.

Source code in backend/app/modules/users/users_goals/router.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@router.get(
    "",
    response_model=user_goals_schema.UserGoalPage,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
def get_user_goals(
    token_user_id: auth_dependencies.CurrentUserId,
    page: core_pagination.ListPage,
    db: core_dependencies.DbSession,
    interval: Annotated[
        user_goals_schema.Interval | None,
        Query(description="Filter by goal interval"),
    ] = None,
    activity_type: Annotated[
        user_goals_schema.GoalActivityType | None,
        Query(description="Filter by activity type"),
    ] = None,
    goal_type: Annotated[
        user_goals_schema.GoalType | None,
        Query(description="Filter by goal type"),
    ] = None,
) -> user_goals_schema.UserGoalPage:
    """Retrieve one page of goals for the authenticated user with optional filters.

    Args:
        token_user_id: User ID from access token.
        page: The requested window.
        db: Database session dependency.
        interval: Optional filter by goal interval.
        activity_type: Optional filter by activity type.
        goal_type: Optional filter by goal type.

    Returns:
        The page of user goals matching the filters.
    """
    return user_goals_service.list_goals(
        user_id=token_user_id,
        db=db,
        page=page,
        interval=interval,
        activity_type=activity_type,
        goal_type=goal_type,
    )

get_user_goals_results

get_user_goals_results(request, token_user_id, page, db)

Calculate and retrieve one page of goal progress for the authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
token_user_id CurrentUserId

User ID from access token.

required
page ListPage

The requested window.

required
db DbSession

Database session dependency.

required

Returns:

Type Description
UserGoalProgressPage

The page of goal progress objects, empty if no goals.

Source code in backend/app/modules/users/users_goals/router.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@router.get(
    "/results",
    response_model=user_goals_schema.UserGoalProgressPage,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.EXPENSIVE_READ)
def get_user_goals_results(
    request: Request,
    token_user_id: auth_dependencies.CurrentUserId,
    page: core_pagination.ListPage,
    db: core_dependencies.DbSession,
) -> user_goals_schema.UserGoalProgressPage:
    """Calculate and retrieve one page of goal progress for the authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        token_user_id: User ID from access token.
        page: The requested window.
        db: Database session dependency.

    Returns:
        The page of goal progress objects, empty if no goals.
    """
    return user_goals_progress_service.get_goals_progress(token_user_id, page, db)

update_user_goal

update_user_goal(request, goal_id, user_goal, token_user_id, db, response, if_match)

Replace an existing goal for the authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
goal_id UuidId

ID of the goal to replace.

required
user_goal UserGoalUpdate

The goal's new values.

required
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session dependency.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
UserGoalRead

The updated goal object.

Source code in backend/app/modules/users/users_goals/router.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
@router.put(
    "/{goal_id}",
    response_model=user_goals_schema.UserGoalRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def update_user_goal(
    request: Request,
    goal_id: core_dependencies.UuidId,
    user_goal: user_goals_schema.UserGoalUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> user_goals_schema.UserGoalRead:
    """Replace an existing goal for the authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        goal_id: ID of the goal to replace.
        user_goal: The goal's new values.
        token_user_id: User ID from access token.
        db: Database session dependency.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        The updated goal object.
    """
    updated = user_goals_service.update_goal(token_user_id, goal_id, user_goal, db, if_match=if_match)
    core_etag.set_etag(response, updated.version)
    return updated

User goals Pydantic schemas and validators.

GoalActivityType

Bases: StrEnum

Supported activity types for user goals.

Attributes:

Name Type Description
RUN

Running activities.

BIKE

Cycling activities.

SWIM

Swimming activities.

WALK

Walking or hiking activities.

STRENGTH

Strength or resistance training.

CARDIO

Cardiovascular training.

Source code in backend/app/modules/users/users_goals/schema.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class GoalActivityType(StrEnum):
    """Supported activity types for user goals.

    Attributes:
        RUN: Running activities.
        BIKE: Cycling activities.
        SWIM: Swimming activities.
        WALK: Walking or hiking activities.
        STRENGTH: Strength or resistance training.
        CARDIO: Cardiovascular training.
    """

    RUN = "run"
    BIKE = "bike"
    SWIM = "swim"
    WALK = "walk"
    STRENGTH = "strength"
    CARDIO = "cardio"

GoalType

Bases: StrEnum

Types of measurable user goals.

Attributes:

Name Type Description
CALORIES

Target calories burned.

ACTIVITIES

Target count of completed activities.

DISTANCE

Target distance traveled.

ELEVATION

Target elevation gain.

DURATION

Target total duration.

Source code in backend/app/modules/users/users_goals/schema.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class GoalType(StrEnum):
    """Types of measurable user goals.

    Attributes:
        CALORIES: Target calories burned.
        ACTIVITIES: Target count of completed activities.
        DISTANCE: Target distance traveled.
        ELEVATION: Target elevation gain.
        DURATION: Target total duration.
    """

    CALORIES = "calories"
    ACTIVITIES = "activities"
    DISTANCE = "distance"
    ELEVATION = "elevation"
    DURATION = "duration"

Interval

Bases: StrEnum

Recurrence intervals for user goals.

Attributes:

Name Type Description
DAILY

Daily recurrence interval.

WEEKLY

Weekly recurrence interval.

MONTHLY

Monthly recurrence interval.

YEARLY

Yearly recurrence interval.

Source code in backend/app/modules/users/users_goals/schema.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Interval(StrEnum):
    """Recurrence intervals for user goals.

    Attributes:
        DAILY: Daily recurrence interval.
        WEEKLY: Weekly recurrence interval.
        MONTHLY: Monthly recurrence interval.
        YEARLY: Yearly recurrence interval.
    """

    DAILY = "daily"
    WEEKLY = "weekly"
    MONTHLY = "monthly"
    YEARLY = "yearly"

UserGoalBase

Bases: BaseModel

Base schema for users fitness goals.

Attributes:

Name Type Description
interval Interval

Goal time interval (daily, weekly, monthly, yearly).

activity_type GoalActivityType

Type of activity for the goal.

goal_type GoalType

Type of goal metric being tracked.

goal_calories StrictInt | None

Target calories in kcal.

goal_activities_number StrictInt | None

Target number of activities.

goal_distance StrictInt | None

Target distance in meters.

goal_elevation StrictInt | None

Target elevation gain in meters.

goal_duration StrictInt | None

Target duration in seconds.

Source code in backend/app/modules/users/users_goals/schema.py
 84
 85
 86
 87
 88
 89
 90
 91
 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
126
127
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
153
154
155
156
157
158
159
160
161
162
class UserGoalBase(BaseModel):
    """Base schema for users fitness goals.

    Attributes:
        interval: Goal time interval (daily, weekly, monthly,
            yearly).
        activity_type: Type of activity for the goal.
        goal_type: Type of goal metric being tracked.
        goal_calories: Target calories in kcal.
        goal_activities_number: Target number of activities.
        goal_distance: Target distance in meters.
        goal_elevation: Target elevation gain in meters.
        goal_duration: Target duration in seconds.
    """

    interval: Interval = Field(..., description="Goal time interval")
    activity_type: GoalActivityType = Field(..., description="Type of activity for the goal")
    goal_type: GoalType = Field(..., description="Type of goal metric being tracked")
    goal_calories: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Target calories in kcal"
    )
    goal_activities_number: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Target number of activities"
    )
    goal_distance: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Target distance in meters"
    )
    goal_elevation: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Target elevation gain in meters"
    )
    goal_duration: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Target duration in seconds"
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

    @model_validator(mode="after")
    def ensure_correct_goal_field(self) -> "UserGoalBase":
        """Validate exactly one goal field matches goal_type.

        Returns:
            Self with validated goal field.

        Raises:
            PydanticCustomError: If required field missing or
                extra fields set.
        """
        goal_type_value = self.goal_type if isinstance(self.goal_type, str) else self.goal_type.value

        required_field = TYPE_TO_FIELD.get(goal_type_value)
        if required_field is None:
            return self

        if getattr(self, required_field) is None:
            raise PydanticCustomError(
                "missing_goal_value",
                "{field} is required when goal_type={goal_type}",
                {
                    "field": required_field,
                    "goal_type": goal_type_value,
                },
            )

        for name in TYPE_TO_FIELD.values():
            if name != required_field and getattr(self, name) is not None:
                raise PydanticCustomError(
                    "exclusive_goal_value",
                    "Only {field} may be set when goal_type={goal_type}",
                    {
                        "field": required_field,
                        "goal_type": goal_type_value,
                    },
                )
        return self

ensure_correct_goal_field

ensure_correct_goal_field()

Validate exactly one goal field matches goal_type.

Returns:

Type Description
UserGoalBase

Self with validated goal field.

Raises:

Type Description
PydanticCustomError

If required field missing or extra fields set.

Source code in backend/app/modules/users/users_goals/schema.py
125
126
127
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
153
154
155
156
157
158
159
160
161
162
@model_validator(mode="after")
def ensure_correct_goal_field(self) -> "UserGoalBase":
    """Validate exactly one goal field matches goal_type.

    Returns:
        Self with validated goal field.

    Raises:
        PydanticCustomError: If required field missing or
            extra fields set.
    """
    goal_type_value = self.goal_type if isinstance(self.goal_type, str) else self.goal_type.value

    required_field = TYPE_TO_FIELD.get(goal_type_value)
    if required_field is None:
        return self

    if getattr(self, required_field) is None:
        raise PydanticCustomError(
            "missing_goal_value",
            "{field} is required when goal_type={goal_type}",
            {
                "field": required_field,
                "goal_type": goal_type_value,
            },
        )

    for name in TYPE_TO_FIELD.values():
        if name != required_field and getattr(self, name) is not None:
            raise PydanticCustomError(
                "exclusive_goal_value",
                "Only {field} may be set when goal_type={goal_type}",
                {
                    "field": required_field,
                    "goal_type": goal_type_value,
                },
            )
    return self

UserGoalCreate

Bases: _UserGoalWrite

Schema for creating a new users goal.

Inherits all validation from UserGoalBase.

Source code in backend/app/modules/users/users_goals/schema.py
185
186
187
188
189
class UserGoalCreate(_UserGoalWrite):
    """Schema for creating a new users goal.

    Inherits all validation from UserGoalBase.
    """

UserGoalProgress

Bases: BaseModel

Schema for user goal progress tracking.

Attributes:

Name Type Description
goal_id UUID

Goal identifier.

interval Interval

Goal time interval.

activity_type GoalActivityType

Activity type for this goal.

goal_type GoalType

Type of goal metric.

start_date date

Period start date.

end_date date

Period end date.

percentage_completed StrictInt | None

Completion percentage.

total_calories StrictInt | None

Total calories achieved.

total_activities_number StrictInt | None

Total activities completed.

total_distance StrictInt | None

Total distance achieved.

total_elevation StrictInt | None

Total elevation gained.

total_duration StrictInt | None

Total duration achieved.

goal_calories StrictInt | None

Target calories.

goal_activities_number StrictInt | None

Target activities count.

goal_distance StrictInt | None

Target distance.

goal_elevation StrictInt | None

Target elevation.

goal_duration StrictInt | None

Target duration.

Source code in backend/app/modules/users/users_goals/schema.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
class UserGoalProgress(BaseModel):
    """Schema for user goal progress tracking.

    Attributes:
        goal_id: Goal identifier.
        interval: Goal time interval.
        activity_type: Activity type for this goal.
        goal_type: Type of goal metric.
        start_date: Period start date.
        end_date: Period end date.
        percentage_completed: Completion percentage.
        total_calories: Total calories achieved.
        total_activities_number: Total activities completed.
        total_distance: Total distance achieved.
        total_elevation: Total elevation gained.
        total_duration: Total duration achieved.
        goal_calories: Target calories.
        goal_activities_number: Target activities count.
        goal_distance: Target distance.
        goal_elevation: Target elevation.
        goal_duration: Target duration.
    """

    goal_id: uuid.UUID = Field(..., description="Goal identifier")
    interval: Interval = Field(..., description="Goal time interval")
    activity_type: GoalActivityType = Field(..., description="Activity type for this goal")
    goal_type: GoalType
    start_date: date = Field(..., description="First day of the goal period")
    end_date: date = Field(..., description="Last day of the goal period")
    percentage_completed: StrictInt | None = Field(default=None, ge=0, le=100, description="Completion percentage")
    # total
    total_calories: StrictInt | None = Field(default=None, ge=0, description="Total calories burned in kcal")
    total_activities_number: StrictInt | None = Field(default=None, ge=0, description="Total activities completed")
    total_distance: StrictInt | None = Field(default=None, ge=0, description="Total distance in meters")
    total_elevation: StrictInt | None = Field(default=None, ge=0, description="Total elevation gain in meters")
    total_duration: StrictInt | None = Field(default=None, ge=0, description="Total duration in seconds")
    # goal
    goal_calories: StrictInt | None = Field(default=None, ge=0, description="Target calories in kcal")
    goal_activities_number: StrictInt | None = Field(default=None, ge=0, description="Target number of activities")
    goal_distance: StrictInt | None = Field(default=None, ge=0, description="Target distance in meters")
    goal_elevation: StrictInt | None = Field(default=None, ge=0, description="Target elevation gain in meters")
    goal_duration: StrictInt | None = Field(default=None, ge=0, description="Target duration in seconds")

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

UserGoalRead

Bases: UserGoalBase

Schema for reading a user goal.

Attributes:

Name Type Description
id UUID

Unique identifier for the goal.

user_id UUID

User who owns this goal.

Source code in backend/app/modules/users/users_goals/schema.py
192
193
194
195
196
197
198
199
200
201
202
class UserGoalRead(UserGoalBase):
    """Schema for reading a user goal.

    Attributes:
        id: Unique identifier for the goal.
        user_id: User who owns this goal.
    """

    id: uuid.UUID = Field(..., description="Unique identifier for the goal")
    user_id: uuid.UUID = Field(..., description="User who owns this goal")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")

UserGoalUpdate

Bases: _UserGoalWrite

Schema for replacing an existing users goal.

The goal is named by the path, so the body carries neither an id nor an owner. It is the whole goal, because the goal type decides which target field is required.

Source code in backend/app/modules/users/users_goals/schema.py
209
210
211
212
213
214
class UserGoalUpdate(_UserGoalWrite):
    """Schema for replacing an existing users goal.

    The goal is named by the path, so the body carries neither an id nor an owner. It is the whole
    goal, because the goal type decides which target field is required.
    """

Users default gear

User default gear API endpoints.

edit_user_default_gear

edit_user_default_gear(request, user_default_gear, token_user_id, db, response, if_match)

Update default gear settings for authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
user_default_gear UserDefaultGearUpdate

Updated gear settings.

required
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session dependency.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
UserDefaultGearRead

Updated user default gear settings.

Source code in backend/app/modules/users/users_default_gear/router.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@router.patch(
    "",
    response_model=user_default_gear_schema.UserDefaultGearRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_user_default_gear(
    request: Request,
    user_default_gear: user_default_gear_schema.UserDefaultGearUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> user_default_gear_schema.UserDefaultGearRead:
    """Update default gear settings for authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        user_default_gear: Updated gear settings.
        token_user_id: User ID from access token.
        db: Database session dependency.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        Updated user default gear settings.
    """
    updated = user_default_gear_service.edit_default_gear(user_default_gear, token_user_id, db, if_match=if_match)
    core_etag.set_etag(response, updated.version)
    return updated

read_user_default_gear

read_user_default_gear(token_user_id, db, response)

Retrieve default gear settings for authenticated user.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

User ID from access token.

required
db DbSession

Database session dependency.

required
response Response

The response, which carries the settings' ETag.

required

Returns:

Type Description
UserDefaultGearRead | None

User default gear settings.

Source code in backend/app/modules/users/users_default_gear/router.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@router.get(
    "",
    response_model=user_default_gear_schema.UserDefaultGearRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["account"])],
)
def read_user_default_gear(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> user_default_gear_schema.UserDefaultGearRead | None:
    """Retrieve default gear settings for authenticated user.

    Args:
        token_user_id: User ID from access token.
        db: Database session dependency.
        response: The response, which carries the settings' ETag.

    Returns:
        User default gear settings.
    """
    default_gear = user_default_gear_service.get_default_gear(token_user_id, db)
    if default_gear is not None:
        core_etag.set_etag(response, default_gear.version)
    return default_gear

User default gear Pydantic schemas.

UserDefaultGearBase

Bases: BaseModel

Base schema for users default gear assignments.

Attributes:

Name Type Description
run_gear_id UUID | None

Default gear for run activities.

trail_run_gear_id UUID | None

Default gear for trail run activities.

virtual_run_gear_id UUID | None

Default gear for virtual run activities.

ride_gear_id UUID | None

Default gear for ride activities.

gravel_ride_gear_id UUID | None

Default gear for gravel ride activities.

mtb_ride_gear_id UUID | None

Default gear for MTB ride activities.

virtual_ride_gear_id UUID | None

Default gear for virtual ride activities.

ows_gear_id UUID | None

Default gear for open water swim activities.

walk_gear_id UUID | None

Default gear for walk activities.

hike_gear_id UUID | None

Default gear for hike activities.

tennis_gear_id UUID | None

Default gear for tennis activities.

alpine_ski_gear_id UUID | None

Default gear for alpine ski activities.

nordic_ski_gear_id UUID | None

Default gear for nordic ski activities.

snowboard_gear_id UUID | None

Default gear for snowboard activities.

windsurf_gear_id UUID | None

Default gear for windsurf activities.

Source code in backend/app/modules/users/users_default_gear/schema.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class UserDefaultGearBase(BaseModel):
    """Base schema for users default gear assignments.

    Attributes:
        run_gear_id: Default gear for run activities.
        trail_run_gear_id: Default gear for trail run
            activities.
        virtual_run_gear_id: Default gear for virtual run
            activities.
        ride_gear_id: Default gear for ride activities.
        gravel_ride_gear_id: Default gear for gravel ride
            activities.
        mtb_ride_gear_id: Default gear for MTB ride activities.
        virtual_ride_gear_id: Default gear for virtual ride
            activities.
        ows_gear_id: Default gear for open water swim
            activities.
        walk_gear_id: Default gear for walk activities.
        hike_gear_id: Default gear for hike activities.
        tennis_gear_id: Default gear for tennis activities.
        alpine_ski_gear_id: Default gear for alpine ski
            activities.
        nordic_ski_gear_id: Default gear for nordic ski
            activities.
        snowboard_gear_id: Default gear for snowboard
            activities.
        windsurf_gear_id: Default gear for windsurf activities.
    """

    run_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for run activities",
    )
    trail_run_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for trail run activities",
    )
    virtual_run_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for virtual run activities",
    )
    ride_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for ride activities",
    )
    gravel_ride_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for gravel ride activities",
    )
    mtb_ride_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for MTB ride activities",
    )
    virtual_ride_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for virtual ride activities",
    )
    ows_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for OWS activities",
    )
    walk_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for walk activities",
    )
    hike_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for hike activities",
    )
    tennis_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for tennis activities",
    )
    alpine_ski_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for alpine ski activities",
    )
    nordic_ski_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for nordic ski activities",
    )
    snowboard_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for snowboard activities",
    )
    windsurf_gear_id: uuid.UUID | None = Field(
        default=None,
        description="Default gear for windsurf activities",
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
    )

UserDefaultGearRead

Bases: UserDefaultGearBase

Schema for reading user default gear settings.

Extends base with identifier fields.

Attributes:

Name Type Description
id UUID

Unique identifier for the record.

user_id UUID

User ID reference.

Source code in backend/app/modules/users/users_default_gear/schema.py
110
111
112
113
114
115
116
117
118
119
120
121
122
class UserDefaultGearRead(UserDefaultGearBase):
    """Schema for reading user default gear settings.

    Extends base with identifier fields.

    Attributes:
        id: Unique identifier for the record.
        user_id: User ID reference.
    """

    id: uuid.UUID = Field(..., description="Unique identifier")
    user_id: uuid.UUID = Field(..., description="User ID")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")

UserDefaultGearUpdate

Bases: UserDefaultGearBase

Schema for updating user default gear settings.

Carries only the gear assignments, all optional for partial updates. The record is the authenticated user's own, so the body names neither the record nor the user.

Source code in backend/app/modules/users/users_default_gear/schema.py
125
126
127
128
129
130
class UserDefaultGearUpdate(UserDefaultGearBase):
    """Schema for updating user default gear settings.

    Carries only the gear assignments, all optional for partial updates. The record is the
    authenticated user's own, so the body names neither the record nor the user.
    """

Users integrations

User integrations Pydantic schemas and validators.

UserIntegrationsBase

Bases: BaseModel

Base schema for user integrations.

Attributes:

Name Type Description
strava_client_id StrictStr | None

Encrypted Strava client ID.

strava_client_secret StrictStr | None

Encrypted Strava client secret.

strava_token StrictStr | None

Encrypted Strava access token.

strava_refresh_token StrictStr | None

Encrypted Strava refresh token.

strava_token_expires_at datetime | None

Strava token expiration time.

strava_sync_gear StrictBool

Enable Strava gear synchronization.

garminconnect_token dict[str, Any] | None

Garmin Connect token data.

garminconnect_sync_gear StrictBool

Enable Garmin Connect gear synchronization.

Source code in backend/app/modules/users/users_integrations/schema.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class UserIntegrationsBase(BaseModel):
    """Base schema for user integrations.

    Attributes:
        strava_client_id: Encrypted Strava client ID.
        strava_client_secret: Encrypted Strava client secret.
        strava_token: Encrypted Strava access token.
        strava_refresh_token: Encrypted Strava refresh token.
        strava_token_expires_at: Strava token expiration time.
        strava_sync_gear: Enable Strava gear synchronization.
        garminconnect_token: Garmin Connect token data.
        garminconnect_sync_gear: Enable Garmin Connect gear
            synchronization.
    """

    strava_client_id: StrictStr | None = Field(
        default=None,
        max_length=512,
        description=("Strava client ID encrypted at rest with Fernet key"),
    )
    strava_client_secret: StrictStr | None = Field(
        default=None,
        max_length=512,
        description=("Strava client secret encrypted at rest with Fernet key"),
    )
    strava_token: StrictStr | None = Field(
        default=None,
        max_length=512,
        description=("Strava token after link process encrypted at rest with Fernet key"),
    )
    strava_refresh_token: StrictStr | None = Field(
        default=None,
        max_length=512,
        description=("Strava refresh token after link process encrypted at rest with Fernet key"),
    )
    strava_token_expires_at: datetime | None = Field(default=None, description="Strava token expiration date")
    strava_sync_gear: StrictBool = Field(default=False, description="Whether Strava gear is to be synced")
    garminconnect_token: dict[str, Any] | None = Field(default=None, description="Garmin Connect token")
    garminconnect_sync_gear: StrictBool = Field(
        default=False,
        description="Whether Garmin Connect gear is to be synced",
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
    )

UserIntegrationsCreate

Bases: UserIntegrationsBase

Pydantic model for creating user integrations.

Inherits all attributes from UserIntegrationsBase.

Source code in backend/app/modules/users/users_integrations/schema.py
67
68
69
70
71
class UserIntegrationsCreate(UserIntegrationsBase):
    """Pydantic model for creating user integrations.

    Inherits all attributes from UserIntegrationsBase.
    """

UserIntegrationsRead

Bases: UserIntegrationsBase

Schema for reading user integrations.

Attributes:

Name Type Description
id UUID

Unique identifier for the integrations record.

user_id UUID

Foreign key reference to the user.

version StrictInt

Optimistic-concurrency counter.

strava_revoked_at datetime | None

When Strava refused the refresh token, None while access is intact. Server-owned.

Source code in backend/app/modules/users/users_integrations/schema.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class UserIntegrationsRead(UserIntegrationsBase):
    """Schema for reading user integrations.

    Attributes:
        id: Unique identifier for the integrations record.
        user_id: Foreign key reference to the user.
        version: Optimistic-concurrency counter.
        strava_revoked_at: When Strava refused the refresh token, ``None`` while access is intact. Server-owned.
    """

    id: uuid.UUID = Field(..., description="Unique identifier for integrations")
    user_id: uuid.UUID = Field(..., description="Foreign key reference to the user")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    strava_revoked_at: datetime | None = Field(
        default=None, description="When Strava refused the refresh token; Strava data is deleted after a grace period"
    )

UserIntegrationsUpdate

Bases: UserIntegrationsBase

Schema for updating user integrations.

Inherits all validation from UserIntegrationsBase. All fields are optional for partial updates.

Source code in backend/app/modules/users/users_integrations/schema.py
74
75
76
77
78
79
class UserIntegrationsUpdate(UserIntegrationsBase):
    """Schema for updating user integrations.

    Inherits all validation from UserIntegrationsBase.
    All fields are optional for partial updates.
    """

Users privacy settings

User privacy settings Pydantic schemas and validators.

UserPrivacySettingsBase

Bases: BaseModel

Base schema for user privacy settings.

Attributes:

Name Type Description
default_activity_visibility ActivityVisibility | None

Default activity visibility level.

hide_activity_start_time StrictBool | None

Hide start time from activities.

hide_activity_location StrictBool | None

Hide location data from activities.

hide_activity_map StrictBool | None

Hide map visualization from activities.

hide_activity_hr StrictBool | None

Hide heart rate data from activities.

hide_activity_power StrictBool | None

Hide power data from activities.

hide_activity_cadence StrictBool | None

Hide cadence data from activities.

hide_activity_elevation StrictBool | None

Hide elevation data from activities.

hide_activity_speed StrictBool | None

Hide speed data from activities.

hide_activity_pace StrictBool | None

Hide pace data from activities.

hide_activity_laps StrictBool | None

Hide lap data from activities.

hide_activity_workout_sets_steps StrictBool | None

Hide workout sets and steps from activities.

hide_activity_gear StrictBool | None

Hide gear information from activities.

discoverable StrictBool | None

Appear in other users' username search.

Source code in backend/app/modules/users/users_privacy_settings/schema.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class UserPrivacySettingsBase(BaseModel):
    """Base schema for user privacy settings.

    Attributes:
        default_activity_visibility: Default activity visibility
            level.
        hide_activity_start_time: Hide start time from
            activities.
        hide_activity_location: Hide location data from
            activities.
        hide_activity_map: Hide map visualization from
            activities.
        hide_activity_hr: Hide heart rate data from activities.
        hide_activity_power: Hide power data from activities.
        hide_activity_cadence: Hide cadence data from
            activities.
        hide_activity_elevation: Hide elevation data from
            activities.
        hide_activity_speed: Hide speed data from activities.
        hide_activity_pace: Hide pace data from activities.
        hide_activity_laps: Hide lap data from activities.
        hide_activity_workout_sets_steps: Hide workout sets and
            steps from activities.
        hide_activity_gear: Hide gear information from
            activities.
        discoverable: Appear in other users' username search.
    """

    default_activity_visibility: activity_constants.ActivityVisibility | None = Field(
        default=activity_constants.ActivityVisibility.PRIVATE,
        description="Default activity visibility (public, followers, private)",
    )
    hide_activity_start_time: StrictBool | None = Field(default=False, description="Hide activity start time")
    hide_activity_location: StrictBool | None = Field(default=False, description="Hide activity location")
    hide_activity_map: StrictBool | None = Field(default=False, description="Hide activity map")
    hide_activity_hr: StrictBool | None = Field(default=False, description="Hide activity heart rate")
    hide_activity_power: StrictBool | None = Field(default=False, description="Hide activity power")
    hide_activity_cadence: StrictBool | None = Field(default=False, description="Hide activity cadence")
    hide_activity_elevation: StrictBool | None = Field(default=False, description="Hide activity elevation")
    hide_activity_speed: StrictBool | None = Field(default=False, description="Hide activity speed")
    hide_activity_pace: StrictBool | None = Field(default=False, description="Hide activity pace")
    hide_activity_laps: StrictBool | None = Field(default=False, description="Hide activity laps")
    hide_activity_workout_sets_steps: StrictBool | None = Field(
        default=False, description="Hide activity workout sets and steps"
    )
    hide_activity_gear: StrictBool | None = Field(default=False, description="Hide activity gear")
    discoverable: StrictBool | None = Field(default=True, description="Appear in other users' username search")

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

UserPrivacySettingsCreate

Bases: UserPrivacySettingsBase

Pydantic model for creating user privacy settings.

Inherits all attributes from UserPrivacySettingsBase.

Source code in backend/app/modules/users/users_privacy_settings/schema.py
73
74
75
76
77
class UserPrivacySettingsCreate(UserPrivacySettingsBase):
    """Pydantic model for creating user privacy settings.

    Inherits all attributes from UserPrivacySettingsBase.
    """

UserPrivacySettingsRead

Bases: UserPrivacySettingsBase

Schema for reading user privacy settings.

Attributes:

Name Type Description
id UUID

Unique identifier for the privacy settings record.

user_id UUID

Foreign key reference to the user.

Source code in backend/app/modules/users/users_privacy_settings/schema.py
105
106
107
108
109
110
111
112
113
114
115
class UserPrivacySettingsRead(UserPrivacySettingsBase):
    """Schema for reading user privacy settings.

    Attributes:
        id: Unique identifier for the privacy settings record.
        user_id: Foreign key reference to the user.
    """

    id: uuid.UUID = Field(..., description="Unique identifier for privacy settings")
    user_id: uuid.UUID = Field(..., description="Foreign key reference to the user")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")

UserPrivacySettingsUpdate

Bases: NotClearable, UserPrivacySettingsBase

Schema for updating user privacy settings.

Inherits all validation from UserPrivacySettingsBase. All fields are optional for partial updates.

Source code in backend/app/modules/users/users_privacy_settings/schema.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
class UserPrivacySettingsUpdate(core_partial_update.NotClearable, UserPrivacySettingsBase):
    """Schema for updating user privacy settings.

    Inherits all validation from UserPrivacySettingsBase.
    All fields are optional for partial updates.
    """

    not_clearable = (
        "default_activity_visibility",
        "hide_activity_start_time",
        "hide_activity_location",
        "hide_activity_map",
        "hide_activity_hr",
        "hide_activity_power",
        "hide_activity_cadence",
        "hide_activity_elevation",
        "hide_activity_speed",
        "hide_activity_pace",
        "hide_activity_laps",
        "hide_activity_workout_sets_steps",
        "hide_activity_gear",
        "discoverable",
    )