Skip to content

Server settings API reference

Admin routes for server settings, the login photo and the test email.

delete_login_photo

delete_login_photo(request, storage, db)

Delete custom login page photo.

Requires admin authentication with server-settings:write scope.

Parameters:

Name Type Description Default
request Request

The HTTP request object.

required
storage Storage

The platform storage provider.

required
db DbSession

Database session.

required
Source code in backend/app/modules/server_settings/router.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@router.delete(
    "/login-photo",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["server-settings:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_login_photo(
    request: Request,
    storage: core_dependencies.Storage,
    db: core_dependencies.DbSession,
) -> None:
    """Delete custom login page photo.

    Requires admin authentication with server-settings:write scope.

    Args:
        request: The HTTP request object.
        storage: The platform storage provider.
        db: Database session.
    """
    server_settings_login_photo_service.delete_login_photo(storage, db)

edit_mail_settings

edit_mail_settings(request, mail_settings_attributes, db, response, if_match, verify_step_up)

Update the mail server settings.

Requires admin authentication with server-settings:write scope and the administrator's own step-up verification in step_up, as pointing mail at another server exposes every password-reset link. The body replaces the whole configuration; only the password may be omitted, which keeps the stored one. If-Match with the ETag from the read is required: a request without it is refused with 428, and a stale tag with 412.

Parameters:

Name Type Description Default
request Request

The HTTP request object.

required
mail_settings_attributes MailSettingsEditRequest

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

required
db DbSession

Database session.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required
verify_step_up StepUpVerifierDep

Verifies the administrator's step-up.

required

Returns:

Type Description
MailSettingsAdminRead

Updated mail settings, without the password.

Raises:

Type Description
StepUpFailedError

403 if the step-up fails.

InvalidInputError

400 if the configuration is not usable.

ConflictError

409 if a field is set by an environment variable.

PreconditionFailedError

412 if the settings changed since the client read them.

Source code in backend/app/modules/server_settings/router.py
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
240
241
@router.put(
    "/email/settings",
    response_model=server_settings_schema.MailSettingsAdminRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["server-settings:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_mail_settings(
    request: Request,
    mail_settings_attributes: server_settings_schema.MailSettingsEditRequest,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
    verify_step_up: auth_dependencies.StepUpVerifierDep,
) -> server_settings_schema.MailSettingsAdminRead:
    """Update the mail server settings.

    Requires admin authentication with server-settings:write scope and the administrator's
    own step-up verification in `step_up`, as pointing mail at another server exposes
    every password-reset link. The body replaces the whole configuration; only the
    password may be omitted, which keeps the stored one.
    ``If-Match`` with the ETag from the read is required: a request without it is refused
    with 428, and a stale tag with 412.

    Args:
        request: The HTTP request object.
        mail_settings_attributes: Settings to update, and the administrator's step-up.
        db: Database session.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.
        verify_step_up: Verifies the administrator's step-up.

    Returns:
        Updated mail settings, without the password.

    Raises:
        StepUpFailedError: 403 if the step-up fails.
        InvalidInputError: 400 if the configuration is not usable.
        ConflictError: 409 if a field is set by an environment variable.
        PreconditionFailedError: 412 if the settings changed since the client read them.
    """
    updated = server_settings_mail_service.edit_mail_settings(
        mail_settings_attributes.to_edit(), mail_settings_attributes.step_up, verify_step_up, db, if_match=if_match
    )
    core_etag.set_etag(response, updated.version)
    return updated

edit_server_settings

edit_server_settings(request, server_settings_attributes, db, response, if_match, verify_step_up)

Update server settings.

Requires admin authentication with server-settings:write scope. A change to a setting that governs sign-up, sign-in, sessions, the audit trail or the owner info on public links also needs the administrator's own step-up verification in step_up; any other change needs none. The body replaces the whole configuration; only the API keys may be omitted, which keeps the stored ones. If-Match with the ETag from the read is required: a request without it is refused with 428, and a stale tag with 412 rather than reverting an admin who saved in between.

Parameters:

Name Type Description Default
request Request

The HTTP request object.

required
server_settings_attributes ServerSettingsEditRequest

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

required
db DbSession

Database session.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required
verify_step_up StepUpVerifierDep

Verifies the administrator's step-up.

required

Returns:

Type Description
ServerSettingsAdminRead

Updated server settings configuration, without the tile API key.

Source code in backend/app/modules/server_settings/router.py
 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
@router.put(
    "",
    response_model=server_settings_schema.ServerSettingsAdminRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["server-settings:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_server_settings(
    request: Request,
    server_settings_attributes: server_settings_schema.ServerSettingsEditRequest,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
    verify_step_up: auth_dependencies.StepUpVerifierDep,
) -> server_settings_schema.ServerSettingsAdminRead:
    """Update server settings.

    Requires admin authentication with server-settings:write scope. A change to a setting that governs
    sign-up, sign-in, sessions, the audit trail or the owner info on public links also needs the administrator's
    own step-up verification in `step_up`; any other change needs none. The body replaces
    the whole configuration; only the API keys may be omitted, which keeps the stored
    ones. ``If-Match`` with the ETag from the read is required: a request without it is
    refused with 428, and a stale tag with 412 rather than reverting an admin who saved
    in between.

    Args:
        request: The HTTP request object.
        server_settings_attributes: Settings to update, and the administrator's step-up.
        db: Database session.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.
        verify_step_up: Verifies the administrator's step-up.

    Returns:
        Updated server settings configuration, without the tile API key.
    """
    updated = server_settings_service.edit_server_settings(
        server_settings_attributes.to_edit(),
        server_settings_attributes.step_up,
        verify_step_up,
        db,
        if_match=if_match,
    )
    # This process applies the new CSP tile domains at once; the other processes poll for them.
    request.app.state.allowed_tile_domains = server_settings_tile_service.allowed_tile_domains_for_url(
        updated.tileserver_url
    )
    core_etag.set_etag(response, updated.version)
    return updated

put_login_photo

put_login_photo(request, file, storage, db, response)

Set the custom login page photo.

Requires admin authentication with server-settings:write scope. Answers 201 when there was no custom photo and 200 when it replaced one.

Parameters:

Name Type Description Default
request Request

The HTTP request object.

required
file UploadFile

Image file to upload.

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
LoginPhotoRead

The stored photo's version.

Source code in backend/app/modules/server_settings/router.py
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
@router.put(
    "/login-photo",
    response_model=server_settings_schema.LoginPhotoRead,
    status_code=status.HTTP_201_CREATED,
    responses=core_openapi_contract.replaced_response(server_settings_schema.LoginPhotoRead),
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["server-settings:write"])],
    openapi_extra=core_middleware_body_limit.upload_limit(server_settings_constants.LOGIN_PHOTO_MAX_BYTES),
)
@core_rate_limit.limiter.limit(core_rate_limit.UPLOAD)
def put_login_photo(
    request: Request,
    file: UploadFile,
    storage: core_dependencies.Storage,
    db: core_dependencies.DbSession,
    response: Response,
) -> server_settings_schema.LoginPhotoRead:
    """Set the custom login page photo.

    Requires admin authentication with server-settings:write scope. Answers 201 when there was no
    custom photo and 200 when it replaced one.

    Args:
        request: The HTTP request object.
        file: Image file to upload.
        storage: The platform storage provider.
        db: Database session.
        response: The response, whose status is 200 when a photo was replaced.

    Returns:
        The stored photo's version.
    """
    photo, replaced = server_settings_login_photo_service.upload_login_photo(file, storage, db)
    if replaced:
        response.status_code = status.HTTP_200_OK
    return photo

read_mail_settings

read_mail_settings(db, response)

Get the mail server settings.

Requires admin authentication with server-settings:read scope.

Parameters:

Name Type Description Default
db DbSession

Database session.

required
response Response

The response, which carries the ETag.

required

Returns:

Type Description
MailSettingsAdminRead

The mail settings. The password is never returned, only whether one is stored;

MailSettingsAdminRead

env_managed names the fields an environment variable currently sets.

Source code in backend/app/modules/server_settings/router.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@router.get(
    "/email/settings",
    response_model=server_settings_schema.MailSettingsAdminRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["server-settings:read"])],
)
def read_mail_settings(
    db: core_dependencies.DbSession,
    response: Response,
) -> server_settings_schema.MailSettingsAdminRead:
    """Get the mail server settings.

    Requires admin authentication with server-settings:read scope.

    Args:
        db: Database session.
        response: The response, which carries the ETag.

    Returns:
        The mail settings. The password is never returned, only whether one is stored;
        ``env_managed`` names the fields an environment variable currently sets.
    """
    mail_settings = server_settings_mail_service.get_mail_settings_for_admin(db)
    core_etag.set_etag(response, mail_settings.version)
    return mail_settings

read_server_settings

read_server_settings(db, response)

Get current server settings.

Requires admin authentication with server-settings:read scope.

Parameters:

Name Type Description Default
db DbSession

Database session.

required
response Response

The response, which carries the ETag.

required

Returns:

Type Description
ServerSettingsAdminRead

Current server settings configuration. The tile API key is never returned,

ServerSettingsAdminRead

only whether one is stored.

Source code in backend/app/modules/server_settings/router.py
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
@router.get(
    "",
    response_model=server_settings_schema.ServerSettingsAdminRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["server-settings:read"])],
)
def read_server_settings(
    db: core_dependencies.DbSession,
    response: Response,
) -> server_settings_schema.ServerSettingsAdminRead:
    """Get current server settings.

    Requires admin authentication with server-settings:read scope.

    Args:
        db: Database session.
        response: The response, which carries the ETag.

    Returns:
        Current server settings configuration. The tile API key is never returned,
        only whether one is stored.
    """
    settings = server_settings_service.get_server_settings_for_admin(db)
    # The tag the client echoes back in If-Match when it later saves.
    core_etag.set_etag(response, settings.version)
    return settings

send_test_email

send_test_email(request, token_user_id, mail, db)

Send a test email to the requesting admin.

Requires admin authentication with server-settings:write scope. The recipient is always the caller's own email address.

Parameters:

Name Type Description Default
request Request

The HTTP request object.

required
token_user_id CurrentUserId

The requesting admin's user ID, from the access token.

required
mail Annotated[MailProvider, Depends(get_mail)]

The platform mail provider.

required
db DbSession

Database session.

required

Raises:

Type Description
ServiceUnavailableError

503 if email is not configured.

UpstreamError

502 if the mail server did not accept the message.

Source code in backend/app/modules/server_settings/router.py
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
@router.post(
    "/email/test",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["server-settings:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.SENSITIVE)
def send_test_email(
    request: Request,
    token_user_id: auth_dependencies.CurrentUserId,
    mail: Annotated[
        platform_providers.MailProvider,
        Depends(core_dependencies.get_mail),
    ],
    db: core_dependencies.DbSession,
) -> None:
    """Send a test email to the requesting admin.

    Requires admin authentication with server-settings:write scope. The recipient
    is always the caller's own email address.

    Args:
        request: The HTTP request object.
        token_user_id: The requesting admin's user ID, from the access token.
        mail: The platform mail provider.
        db: Database session.

    Raises:
        ServiceUnavailableError: 503 if email is not configured.
        UpstreamError: 502 if the mail server did not accept the message.
    """
    server_settings_mail_service.send_test_email(token_user_id, mail, db)

Request and response shapes for server settings.

Currency

Bases: Enum

An enumeration representing supported currencies.

Attributes:

Name Type Description
EURO

Represents the Euro currency.

DOLLAR

Represents the US Dollar currency.

POUND

Represents the British Pound currency.

Source code in backend/app/modules/server_settings/schema.py
36
37
38
39
40
41
42
43
44
45
46
47
class Currency(Enum):
    """An enumeration representing supported currencies.

    Attributes:
        EURO: Represents the Euro currency.
        DOLLAR: Represents the US Dollar currency.
        POUND: Represents the British Pound currency.
    """

    EURO = "euro"
    DOLLAR = "dollar"
    POUND = "pound"

EmailStatus

Bases: BaseModel

Whether outgoing email is usable, and why not when it is not.

Attributes:

Name Type Description
configured bool

True when the mail settings are valid and email can be sent.

problems list[str]

Reasons email is disabled. Names settings, never their values.

Source code in backend/app/modules/server_settings/schema.py
715
716
717
718
719
720
721
722
723
724
class EmailStatus(BaseModel):
    """Whether outgoing email is usable, and why not when it is not.

    Attributes:
        configured: True when the mail settings are valid and email can be sent.
        problems: Reasons email is disabled. Names settings, never their values.
    """

    configured: bool
    problems: list[str]

LoginPhotoRead

Bases: BaseModel

The login photo after an upload.

Attributes:

Name Type Description
version StrictInt

The server settings version that identifies the stored photo; the public photo route sends it as the ETag.

Source code in backend/app/modules/server_settings/schema.py
579
580
581
582
583
584
585
586
587
class LoginPhotoRead(BaseModel):
    """The login photo after an upload.

    Attributes:
        version: The server settings version that identifies the stored photo; the public photo route
            sends it as the ``ETag``.
    """

    version: StrictInt = Field(..., ge=1, description="Version that identifies the stored photo")

MailSettingsAdminRead

Bases: BaseModel

Mail server settings response for admins; the password is never returned.

Attributes:

Name Type Description
id StrictInt

Unique identifier (always 1, singleton pattern).

version StrictInt

Optimistic-concurrency counter, also sent as the ETag.

host StrictStr | None

Mail server hostname, or null when mail is disabled.

port StrictInt

Mail server port.

security MailSecurity

Connection security.

username StrictStr | None

Authentication username.

from_address StrictStr | None

Sender address, or null when the username is used.

password_set StrictBool

Whether a password is stored.

env_managed dict[str, str]

Field name to the environment variable that sets it; those fields cannot be edited while the variable is set.

email_status EmailStatus

Whether outgoing email is usable with these settings; read-only.

Source code in backend/app/modules/server_settings/schema.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
class MailSettingsAdminRead(BaseModel):
    """Mail server settings response for admins; the password is never returned.

    Attributes:
        id: Unique identifier (always 1, singleton pattern).
        version: Optimistic-concurrency counter, also sent as the ``ETag``.
        host: Mail server hostname, or null when mail is disabled.
        port: Mail server port.
        security: Connection security.
        username: Authentication username.
        from_address: Sender address, or null when the username is used.
        password_set: Whether a password is stored.
        env_managed: Field name to the environment variable that sets it; those
            fields cannot be edited while the variable is set.
        email_status: Whether outgoing email is usable with these settings; read-only.
    """

    id: StrictInt
    version: StrictInt = Field(..., ge=1, description="Optimistic-concurrency counter")
    host: StrictStr | None
    port: StrictInt
    security: core_mail.MailSecurity
    username: StrictStr | None
    from_address: StrictStr | None
    password_set: StrictBool = Field(..., description="Is a mail server password stored (true - yes, false - no)")
    env_managed: dict[str, str] = Field(
        ..., description="Field name to the environment variable that sets it (not editable while set)"
    )
    email_status: EmailStatus = Field(..., description="Whether outgoing email is usable with these settings")

    model_config = ConfigDict(use_enum_values=True)

MailSettingsEdit

Bases: BaseModel

Request body for editing the mail server settings.

A full replacement except for the password.

Attributes:

Name Type Description
host StrictStr | None

Mail server hostname; empty or null disables mail.

port StrictInt

Mail server port.

security MailSecurity

Connection security.

username StrictStr | None

Authentication username.

from_address StrictStr | None

Sender address; the username is used when empty.

password StrictStr | None

Plain-text password; stored encrypted and never returned. Omit it to keep the stored password; send null or an empty string to remove it.

Source code in backend/app/modules/server_settings/schema.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
class MailSettingsEdit(BaseModel):
    """Request body for editing the mail server settings.

    A full replacement except for the password.

    Attributes:
        host: Mail server hostname; empty or null disables mail.
        port: Mail server port.
        security: Connection security.
        username: Authentication username.
        from_address: Sender address; the username is used when empty.
        password: Plain-text password; stored encrypted and never returned. Omit it
            to keep the stored password; send null or an empty string to remove it.
    """

    host: StrictStr | None = Field(..., max_length=253, description="Mail server hostname (empty - mail disabled)")
    port: StrictInt = Field(..., ge=1, le=65535, description="Mail server port")
    security: core_mail.MailSecurity = Field(..., description="Connection security (starttls, ssl, none)")
    username: StrictStr | None = Field(..., max_length=320, description="Mail server authentication username")
    from_address: StrictStr | None = Field(
        ..., max_length=320, description="Sender address (empty - the username is used)"
    )
    # Capped so the Fernet token (about 1.37x the plain length) fits the 512-char column.
    password: StrictStr | None = Field(
        default=None,
        max_length=256,
        description="Mail server password (write-only); omit to keep, null or empty to remove",
    )

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

    @field_validator("host", "username", "from_address", mode="after")
    @classmethod
    def _empty_to_none(cls, value: str | None) -> str | None:
        """Treat a blank string as unset.

        Args:
            value: The submitted value.

        Returns:
            The stripped value, or None when it is blank.
        """
        return (value.strip() or None) if value is not None else None

MailSettingsEditRequest

Bases: MailSettingsEdit

The body of PUT /server-settings/email/settings: the mail settings and the administrator's step-up.

Attributes:

Name Type Description
step_up StepUpVerification

The administrator's own step-up verification; it is never a mail setting.

Source code in backend/app/modules/server_settings/schema.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
class MailSettingsEditRequest(MailSettingsEdit):
    """The body of ``PUT /server-settings/email/settings``: the mail settings and the administrator's step-up.

    Attributes:
        step_up: The administrator's own step-up verification; it is never a mail setting.
    """

    step_up: auth_schema.StepUpVerification = Field(
        ..., description="The administrator's step-up verification, required to edit the mail settings"
    )

    def to_edit(self) -> MailSettingsEdit:
        """Return the mail settings the client sent, without the step-up.

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

to_edit

to_edit()

Return the mail settings the client sent, without the step-up.

Returns:

Type Description
MailSettingsEdit

The settings as a :class:MailSettingsEdit, with the same fields set.

Source code in backend/app/modules/server_settings/schema.py
688
689
690
691
692
693
694
def to_edit(self) -> MailSettingsEdit:
    """Return the mail settings the client sent, without the step-up.

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

MailSettingsRead

Bases: MailSettingsEdit

The mail settings row as stored, for in-process use only.

Never a response model: the password is the stored (encrypted) value.

Attributes:

Name Type Description
id StrictInt

Unique identifier (always 1, singleton pattern).

version StrictInt

Optimistic-concurrency counter, also sent as the ETag.

Source code in backend/app/modules/server_settings/schema.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
class MailSettingsRead(MailSettingsEdit):
    """The mail settings row as stored, for in-process use only.

    Never a response model: the password is the stored (encrypted) value.

    Attributes:
        id: Unique identifier (always 1, singleton pattern).
        version: Optimistic-concurrency counter, also sent as the ``ETag``.
    """

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

    # Wider than the edit cap: the stored value is the Fernet token, which this model also reads.
    password: StrictStr | None = Field(default=None, max_length=512, description="Mail server password")
    id: StrictInt = Field(..., description="Unique identifier for mail settings (always 1)")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter")

ServerSettingsAdminRead

Bases: ServerSettingsBase, ServerSettingsGeocoding, ServerSettingsSessionPolicy, ServerSettingsRetention

Complete server settings response for admins; API keys are never returned.

Attributes:

Name Type Description
id StrictInt

Unique identifier (always 1, singleton pattern).

login_photo_set StrictBool

Whether a custom login photo is configured.

version StrictInt

Optimistic-concurrency counter, also sent as the ETag.

tileserver_api_key_set StrictBool

Whether a tile API key is stored.

geocoding_api_key_set StrictBool

Whether a geocoding API key is stored.

env_managed dict[str, str]

Field name to the environment variable that sets it; those fields cannot be edited while the variable is set.

signup_sso_enabled StrictBool

Allow identity providers to create accounts at first sign-in.

signup_require_admin_approval StrictBool

Require admin approval for new sign-ups.

signup_require_email_verification StrictBool

Require email verification for new sign-ups.

password_breach_check_enabled StrictBool

Refuse a new password found in a known data breach.

require_mfa RequireMfa

Which accounts must have MFA (off, administrators, everyone).

step_up_fields list[StrictStr]

The settings whose change needs the administrator's step-up; read-only.

logs_viewer_enabled StrictBool

Whether the server log can be read through the API on this deployment; read-only.

Source code in backend/app/modules/server_settings/schema.py
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
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 ServerSettingsAdminRead(
    ServerSettingsBase, ServerSettingsGeocoding, ServerSettingsSessionPolicy, ServerSettingsRetention
):
    """Complete server settings response for admins; API keys are never returned.

    Attributes:
        id: Unique identifier (always 1, singleton pattern).
        login_photo_set: Whether a custom login photo is configured.
        version: Optimistic-concurrency counter, also sent as the ``ETag``.
        tileserver_api_key_set: Whether a tile API key is stored.
        geocoding_api_key_set: Whether a geocoding API key is stored.
        env_managed: Field name to the environment variable that sets it; those
            fields cannot be edited while the variable is set.
        signup_sso_enabled: Allow identity providers to create accounts at first sign-in.
        signup_require_admin_approval: Require admin approval for new sign-ups.
        signup_require_email_verification: Require email verification for new sign-ups.
        password_breach_check_enabled: Refuse a new password found in a known data breach.
        require_mfa: Which accounts must have MFA (off, administrators, everyone).
        step_up_fields: The settings whose change needs the administrator's step-up; read-only.
        logs_viewer_enabled: Whether the server log can be read through the API on this deployment; read-only.
    """

    id: StrictInt = Field(..., description="Unique identifier for server settings (always 1)")
    login_photo_set: StrictBool = Field(..., description="Is login photo set (true - yes, false - no)")
    version: StrictInt = Field(..., ge=1, description="Optimistic-concurrency counter")
    tileserver_api_key_set: StrictBool = Field(
        ..., description="Is a tile server API key stored (true - yes, false - no)"
    )
    geocoding_api_key_set: StrictBool = Field(..., description="Is a geocoding API key stored (true - yes, false - no)")
    env_managed: dict[str, str] = Field(
        ..., description="Field name to the environment variable that sets it (not editable while set)"
    )
    signup_sso_enabled: StrictBool = Field(
        ...,
        description=(
            "Allow identity providers to create accounts at first sign-in; a provider must also allow it "
            "(true - yes, false - no)"
        ),
    )
    signup_require_admin_approval: StrictBool = Field(
        ...,
        description="Require admin approval for new sign-ups (true - yes, false - no)",
    )
    signup_require_email_verification: StrictBool = Field(
        ...,
        description="Require email verification for new sign-ups (true - yes, false - no)",
    )
    password_breach_check_enabled: StrictBool = Field(
        ...,
        description=(
            "Refuse a new password found in a known data breach, checked against the Have I Been Pwned range API "
            "with a 5-character hash prefix; allowed when the service is unreachable (true - yes, false - no)"
        ),
    )
    require_mfa: server_settings_contracts.RequireMfa = Field(
        ...,
        description=(
            "Which accounts must have MFA: off, administrators or everyone. An account it covers without MFA can "
            "only enrol it and sign out"
        ),
    )
    step_up_fields: list[StrictStr] = Field(
        ..., description="The settings whose change needs the administrator's step-up"
    )
    logs_viewer_enabled: StrictBool = Field(
        ..., description="Can the server log be read through the API (true - yes, false - no)"
    )

ServerSettingsBase

Bases: BaseModel

Pydantic model for server settings configuration.

This model defines all configurable server settings for the Endurain application, including units, currency, authentication methods, map configuration, and password policies.

Attributes:

Name Type Description
units Units

Unit system for measurements (METRIC or IMPERIAL).

public_shareable_links StrictBool

Enable/disable public shareable links.

public_shareable_links_user_info StrictBool

Show user info on public shareable links.

currency Currency

Currency type (EURO, DOLLAR, or POUND).

num_records_per_page StrictInt

Number of records per page in lists (1-100).

signup_enabled StrictBool

Allow new user registration.

sso_enabled StrictBool

Enable SSO/IdP authentication.

local_login_enabled StrictBool

Allow local username/password authentication.

sso_auto_redirect StrictBool

Automatically redirect to SSO when exactly one identity provider is enabled and local login is disabled.

tileserver_url StrictStr

URL template for map tile server with coordinate placeholders.

tileserver_attribution StrictStr

Attribution string for map tile server.

map_background_color StrictStr

Hex color code for map background (#RRGGBB format).

password_length_regular_users StrictInt

Minimum password length for regular users (8-128).

password_length_admin_users StrictInt

Minimum password length for admin users (8-128).

Validators
  • validate_tileserver_url: Ensures tile server URL is secure, uses proper protocol, contains required placeholders, and blocks dangerous patterns.
  • validate_attribution: Sanitizes attribution string to prevent XSS attacks.
Model Config
  • Validates on assignment.
  • Forbids extra fields.
  • Uses enum values in serialization.
  • Supports ORM attribute mapping.
Source code in backend/app/modules/server_settings/schema.py
 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
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
163
164
165
166
167
168
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
207
class ServerSettingsBase(BaseModel):
    """Pydantic model for server settings configuration.

    This model defines all configurable server settings for the Endurain application,
    including units, currency, authentication methods, map configuration, and password policies.

    Attributes:
        units (Units): Unit system for measurements (METRIC or IMPERIAL).
        public_shareable_links (StrictBool): Enable/disable public shareable links.
        public_shareable_links_user_info (StrictBool): Show user info on public shareable links.
        currency (Currency): Currency type (EURO, DOLLAR, or POUND).
        num_records_per_page (StrictInt): Number of records per page in lists (1-100).
        signup_enabled (StrictBool): Allow new user registration.
        sso_enabled (StrictBool): Enable SSO/IdP authentication.
        local_login_enabled (StrictBool): Allow local username/password authentication.
        sso_auto_redirect (StrictBool): Automatically redirect to SSO when exactly one identity provider is
            enabled and local login is disabled.
        tileserver_url (StrictStr): URL template for map tile server with coordinate placeholders.
        tileserver_attribution (StrictStr): Attribution string for map tile server.
        map_background_color (StrictStr): Hex color code for map background (#RRGGBB format).
        password_length_regular_users (StrictInt): Minimum password length for regular users (8-128).
        password_length_admin_users (StrictInt): Minimum password length for admin users (8-128).

    Validators:
        - validate_tileserver_url: Ensures tile server URL is secure, uses proper protocol, contains required
          placeholders, and blocks dangerous patterns.
        - validate_attribution: Sanitizes attribution string to prevent XSS attacks.

    Model Config:
        - Validates on assignment.
        - Forbids extra fields.
        - Uses enum values in serialization.
        - Supports ORM attribute mapping.
    """

    units: Units = Field(..., description="Units (metric, imperial)")
    public_shareable_links: StrictBool = Field(..., description="Allow public shareable links (true - yes, false - no)")
    public_shareable_links_user_info: StrictBool = Field(
        ...,
        description="Allow show user info on public shareable links (true - yes, false - no)",
    )
    currency: Currency = Field(..., description="Currency (euro, dollar, pound)")
    num_records_per_page: StrictInt = Field(
        ...,
        ge=1,
        le=100,
        description="Number of records per page in lists",
    )
    signup_enabled: StrictBool = Field(..., description="Allow user sign-up registration (true - yes, false - no)")
    sso_enabled: StrictBool = Field(
        ...,
        description="Enable SSO/IdP login (true - yes, false - no)",
    )
    local_login_enabled: StrictBool = Field(
        ..., description="Allow local username/password login (true - yes, false - no)"
    )
    sso_auto_redirect: StrictBool = Field(
        ..., description="Auto-redirect to SSO if only one IdP (true - yes, false - no)"
    )
    tileserver_url: StrictStr = Field(
        max_length=2048,
        min_length=1,
        description="URL template for the map tileserver",
    )
    tileserver_attribution: StrictStr = Field(
        max_length=1024,
        min_length=1,
        description="Attribution string for the map tileserver",
    )
    map_background_color: StrictStr = Field(
        max_length=7,
        pattern=r"^#[0-9A-Fa-f]{6}$",
        description=("Background color for the map (hex format)"),
    )
    tileserver_regenerate_thumbnails_on_change: StrictBool = Field(
        ...,
        description=("Delete and regenerate all activity thumbnails when tile server settings change"),
    )
    password_length_regular_users: StrictInt = Field(
        ..., ge=8, le=128, description="Minimum password length for regular users"
    )
    password_length_admin_users: StrictInt = Field(
        ..., ge=8, le=128, description="Minimum password length for admin users"
    )

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

    @field_validator("tileserver_url")
    @classmethod
    def validate_tileserver_url(cls, value: str) -> str:
        """Validate tile server URL for security and correctness.

        Args:
            value: Tile server URL template.

        Returns:
            Validated URL.

        Raises:
            ValueError: If URL is invalid or insecure.
        """
        if not value:
            return value

        # Must use http or https protocol
        if not re.match(r"^https?://", value, re.IGNORECASE):
            raise ValueError("Tile server URL must use http:// or https://")

        # Enforce HTTPS except for localhost
        if value.lower().startswith("http://") and not re.match(
            r"^http://(localhost|127\.0\.0\.1)(:|/)",
            value,
            re.IGNORECASE,
        ):
            raise ValueError("Tile server URL must use https:// (http:// only allowed for localhost)")

        # Must contain required tile coordinate placeholders
        required = ["{z}", "{x}", "{y}"]
        missing = [p for p in required if p not in value]
        if missing:
            missing_str = ", ".join(missing)
            raise ValueError(f"Tile server URL must contain placeholders: {missing_str}")

        # Block dangerous patterns
        dangerous = [
            r"javascript:",
            r"data:",
            r"vbscript:",
            r"file:",
            r"<script",
            r"onerror",
            r"onclick",
        ]

        for pattern in dangerous:
            if re.search(pattern, value, re.IGNORECASE):
                msg = f"Tile server URL contains disallowed: {pattern}"
                raise ValueError(msg)

        return value

    @field_validator("tileserver_attribution")
    @classmethod
    def validate_attribution(cls, value: str) -> str:
        """Sanitize tileserver attribution to prevent XSS.

        Args:
            value: Raw attribution string.

        Returns:
            Sanitized string with only safe HTML.
        """
        return core_sanitization.sanitize_attribution(value) or ""

validate_attribution classmethod

validate_attribution(value)

Sanitize tileserver attribution to prevent XSS.

Parameters:

Name Type Description Default
value str

Raw attribution string.

required

Returns:

Type Description
str

Sanitized string with only safe HTML.

Source code in backend/app/modules/server_settings/schema.py
196
197
198
199
200
201
202
203
204
205
206
207
@field_validator("tileserver_attribution")
@classmethod
def validate_attribution(cls, value: str) -> str:
    """Sanitize tileserver attribution to prevent XSS.

    Args:
        value: Raw attribution string.

    Returns:
        Sanitized string with only safe HTML.
    """
    return core_sanitization.sanitize_attribution(value) or ""

validate_tileserver_url classmethod

validate_tileserver_url(value)

Validate tile server URL for security and correctness.

Parameters:

Name Type Description Default
value str

Tile server URL template.

required

Returns:

Type Description
str

Validated URL.

Raises:

Type Description
ValueError

If URL is invalid or insecure.

Source code in backend/app/modules/server_settings/schema.py
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@field_validator("tileserver_url")
@classmethod
def validate_tileserver_url(cls, value: str) -> str:
    """Validate tile server URL for security and correctness.

    Args:
        value: Tile server URL template.

    Returns:
        Validated URL.

    Raises:
        ValueError: If URL is invalid or insecure.
    """
    if not value:
        return value

    # Must use http or https protocol
    if not re.match(r"^https?://", value, re.IGNORECASE):
        raise ValueError("Tile server URL must use http:// or https://")

    # Enforce HTTPS except for localhost
    if value.lower().startswith("http://") and not re.match(
        r"^http://(localhost|127\.0\.0\.1)(:|/)",
        value,
        re.IGNORECASE,
    ):
        raise ValueError("Tile server URL must use https:// (http:// only allowed for localhost)")

    # Must contain required tile coordinate placeholders
    required = ["{z}", "{x}", "{y}"]
    missing = [p for p in required if p not in value]
    if missing:
        missing_str = ", ".join(missing)
        raise ValueError(f"Tile server URL must contain placeholders: {missing_str}")

    # Block dangerous patterns
    dangerous = [
        r"javascript:",
        r"data:",
        r"vbscript:",
        r"file:",
        r"<script",
        r"onerror",
        r"onclick",
    ]

    for pattern in dangerous:
        if re.search(pattern, value, re.IGNORECASE):
            msg = f"Tile server URL contains disallowed: {pattern}"
            raise ValueError(msg)

    return value

ServerSettingsEdit

Bases: ServerSettingsBase, ServerSettingsGeocoding, ServerSettingsSessionPolicy, ServerSettingsRetention

Request body for editing the server settings.

A full replacement: every setting except the tile API key is required. The row id and the login-photo flag are not here: the id is fixed (singleton) and the flag is set only by the login-photo upload and delete routes, so a stale form can never reset it.

Attributes:

Name Type Description
tileserver_api_key StrictStr | None

Plain-text API key for the tile server; stored encrypted and never returned. Omit it to keep the stored key; send null or an empty string to remove it.

signup_sso_enabled StrictBool

Allow identity providers to create accounts at first sign-in (true - yes, false - no).

signup_require_admin_approval StrictBool

Require admin approval for new sign-ups (true - yes, false - no).

signup_require_email_verification StrictBool

Require email verification for new sign-ups (true - yes, false - no).

password_breach_check_enabled StrictBool

Refuse a new password found in a known data breach, checked against the Have I Been Pwned range API (true - yes, false - no).

require_mfa RequireMfa

Which accounts must have MFA (off, administrators, everyone).

geocoding_api_key StrictStr | None

Plain-text API key for the geocoding service; same write-only semantics as tileserver_api_key.

Source code in backend/app/modules/server_settings/schema.py
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
class ServerSettingsEdit(
    ServerSettingsBase, ServerSettingsGeocoding, ServerSettingsSessionPolicy, ServerSettingsRetention
):
    """Request body for editing the server settings.

    A full replacement: every setting except the tile API key is required. The row
    id and the login-photo flag are not here: the id is fixed (singleton) and the
    flag is set only by the login-photo upload and delete routes, so a stale form
    can never reset it.

    Attributes:
        tileserver_api_key: Plain-text API key for the tile server; stored encrypted
            and never returned. Omit it to keep the stored key; send null or an
            empty string to remove it.
        signup_sso_enabled: Allow identity providers to create accounts at first sign-in
            (true - yes, false - no).
        signup_require_admin_approval: Require admin approval for new sign-ups
            (true - yes, false - no).
        signup_require_email_verification: Require email verification for new
            sign-ups (true - yes, false - no).
        password_breach_check_enabled: Refuse a new password found in a known data breach, checked against
            the Have I Been Pwned range API (true - yes, false - no).
        require_mfa: Which accounts must have MFA (off, administrators, everyone).
        geocoding_api_key: Plain-text API key for the geocoding service; same
            write-only semantics as ``tileserver_api_key``.
    """

    # Capped so the Fernet token (about 1.37x the plain length) fits the 512-char column.
    tileserver_api_key: StrictStr | None = Field(
        default=None,
        max_length=256,
        description="API key for the tile server (write-only); omit to keep, null or empty to remove",
    )
    geocoding_api_key: StrictStr | None = Field(
        default=None,
        max_length=256,
        description="API key for the geocoding service (write-only); omit to keep, null or empty to remove",
    )
    signup_sso_enabled: StrictBool = Field(
        ...,
        description=(
            "Allow identity providers to create accounts at first sign-in; a provider must also allow it "
            "(true - yes, false - no)"
        ),
    )
    signup_require_admin_approval: StrictBool = Field(
        ...,
        description="Require admin approval for new sign-ups (true - yes, false - no)",
    )
    signup_require_email_verification: StrictBool = Field(
        ...,
        description="Require email verification for new sign-ups (true - yes, false - no)",
    )
    password_breach_check_enabled: StrictBool = Field(
        ...,
        description=(
            "Refuse a new password found in a known data breach, checked against the Have I Been Pwned range API "
            "with a 5-character hash prefix; allowed when the service is unreachable (true - yes, false - no)"
        ),
    )
    require_mfa: server_settings_contracts.RequireMfa = Field(
        ...,
        description=(
            "Which accounts must have MFA: off, administrators or everyone. An account it covers without MFA can "
            "only enrol it and sign out"
        ),
    )

ServerSettingsEditRequest

Bases: ServerSettingsEdit

The body of PUT /server-settings: the settings and, when needed, the administrator's step-up.

Attributes:

Name Type Description
step_up StepUpVerification | None

The administrator's own step-up verification, or null when no security-relevant setting changes; it is never a setting. The key is always sent, as a PUT body states the whole resource.

Source code in backend/app/modules/server_settings/schema.py
408
409
410
411
412
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
class ServerSettingsEditRequest(ServerSettingsEdit):
    """The body of ``PUT /server-settings``: the settings and, when needed, the administrator's step-up.

    Attributes:
        step_up: The administrator's own step-up verification, or null when no security-relevant setting changes;
            it is never a setting. The key is always sent, as a ``PUT`` body states the whole resource.
    """

    step_up: auth_schema.StepUpVerification | None = Field(
        ...,
        description=(
            "The administrator's step-up verification, required when a security-relevant setting changes; "
            "null otherwise"
        ),
    )

    @model_validator(mode="after")
    def validate_access_token_lifetime(self) -> "ServerSettingsEditRequest":
        """Refuse an access token lifetime that is not shorter than the enforced idle timeout.

        The check belongs to the request, not to the shared session policy fields: a stored row that predates it
        must still read, and the administrator edits it into validity.

        Returns:
            The validated model.

        Raises:
            ValueError: If the idle timeout is enforced and the access token lifetime is not shorter than it.
        """
        require_access_token_below_idle_timeout(
            self.session_idle_timeout_enabled, self.session_idle_timeout_hours, self.access_token_expire_minutes
        )
        return self

    def to_edit(self) -> ServerSettingsEdit:
        """Return the settings the client sent, without the step-up.

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

to_edit

to_edit()

Return the settings the client sent, without the step-up.

Returns:

Type Description
ServerSettingsEdit

The settings as a :class:ServerSettingsEdit, with the same fields set.

Source code in backend/app/modules/server_settings/schema.py
442
443
444
445
446
447
448
def to_edit(self) -> ServerSettingsEdit:
    """Return the settings the client sent, without the step-up.

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

validate_access_token_lifetime

validate_access_token_lifetime()

Refuse an access token lifetime that is not shorter than the enforced idle timeout.

The check belongs to the request, not to the shared session policy fields: a stored row that predates it must still read, and the administrator edits it into validity.

Returns:

Type Description
ServerSettingsEditRequest

The validated model.

Raises:

Type Description
ValueError

If the idle timeout is enforced and the access token lifetime is not shorter than it.

Source code in backend/app/modules/server_settings/schema.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
@model_validator(mode="after")
def validate_access_token_lifetime(self) -> "ServerSettingsEditRequest":
    """Refuse an access token lifetime that is not shorter than the enforced idle timeout.

    The check belongs to the request, not to the shared session policy fields: a stored row that predates it
    must still read, and the administrator edits it into validity.

    Returns:
        The validated model.

    Raises:
        ValueError: If the idle timeout is enforced and the access token lifetime is not shorter than it.
    """
    require_access_token_below_idle_timeout(
        self.session_idle_timeout_enabled, self.session_idle_timeout_hours, self.access_token_expire_minutes
    )
    return self

ServerSettingsGeocoding

Bases: BaseModel

The reverse-geocoding fields, kept off the public settings model.

A separate mixin rather than part of :class:ServerSettingsBase, which the public settings inherit: the geocoding host of a self-hosted instance is not for anonymous visitors.

Attributes:

Name Type Description
geocoding_service GeocodingService

The reverse-geocoding service.

geocoding_host StrictStr | None

Host (and optional port) of the service; empty for the service's default host.

geocoding_use_https StrictBool

Address the host over HTTPS.

geocoding_rate_limit float

Maximum requests per second (0 disables throttling).

Source code in backend/app/modules/server_settings/schema.py
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
class ServerSettingsGeocoding(BaseModel):
    """The reverse-geocoding fields, kept off the public settings model.

    A separate mixin rather than part of :class:`ServerSettingsBase`, which the public
    settings inherit: the geocoding host of a self-hosted instance is not for anonymous visitors.

    Attributes:
        geocoding_service: The reverse-geocoding service.
        geocoding_host: Host (and optional port) of the service; empty for the service's default host.
        geocoding_use_https: Address the host over HTTPS.
        geocoding_rate_limit: Maximum requests per second (0 disables throttling).
    """

    geocoding_service: core_geocoding.GeocodingService = Field(
        ..., description="Reverse-geocoding service (nominatim, photon, geocode)"
    )
    geocoding_host: StrictStr | None = Field(
        ...,
        max_length=253,
        description="Host of the geocoding service, e.g. nominatim.example.org:8080 (empty - the service's default)",
    )
    geocoding_use_https: StrictBool = Field(
        ..., description="Address the geocoding host over HTTPS (true - yes, false - no)"
    )
    geocoding_rate_limit: float = Field(
        ..., ge=0, le=100, description="Maximum geocoding requests per second (0 disables throttling)"
    )

    @field_validator("geocoding_host", mode="after")
    @classmethod
    def validate_geocoding_host(cls, value: str | None) -> str | None:
        """Normalise the geocoding host and refuse anything but ``host[:port]``.

        Args:
            value: The submitted host.

        Returns:
            The lower-cased host, or None when blank.

        Raises:
            ValueError: If the value carries a scheme, path or other characters.
        """
        value = (value or "").strip().lower()
        if not value:
            return None
        if not _GEOCODING_HOST_PATTERN.fullmatch(value):
            raise ValueError("Geocoding host must be a hostname or IP address with an optional port")
        return value

validate_geocoding_host classmethod

validate_geocoding_host(value)

Normalise the geocoding host and refuse anything but host[:port].

Parameters:

Name Type Description Default
value str | None

The submitted host.

required

Returns:

Type Description
str | None

The lower-cased host, or None when blank.

Raises:

Type Description
ValueError

If the value carries a scheme, path or other characters.

Source code in backend/app/modules/server_settings/schema.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
@field_validator("geocoding_host", mode="after")
@classmethod
def validate_geocoding_host(cls, value: str | None) -> str | None:
    """Normalise the geocoding host and refuse anything but ``host[:port]``.

    Args:
        value: The submitted host.

    Returns:
        The lower-cased host, or None when blank.

    Raises:
        ValueError: If the value carries a scheme, path or other characters.
    """
    value = (value or "").strip().lower()
    if not value:
        return None
    if not _GEOCODING_HOST_PATTERN.fullmatch(value):
        raise ValueError("Geocoding host must be a hostname or IP address with an optional port")
    return value

ServerSettingsRead

Bases: ServerSettingsEdit

The settings row as stored, for in-process use only.

Never a response model: the tile API key is the stored (encrypted) value. Clients get :class:ServerSettingsAdminRead or :class:ServerSettingsReadPublic.

Attributes:

Name Type Description
id StrictInt

Unique identifier (always 1, singleton pattern).

login_photo_set StrictBool

Whether a custom login photo is configured.

version StrictInt

Optimistic-concurrency counter, also sent as the ETag.

Source code in backend/app/modules/server_settings/schema.py
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
class ServerSettingsRead(ServerSettingsEdit):
    """The settings row as stored, for in-process use only.

    Never a response model: the tile API key is the stored (encrypted) value.
    Clients get :class:`ServerSettingsAdminRead` or :class:`ServerSettingsReadPublic`.

    Attributes:
        id: Unique identifier (always 1, singleton pattern).
        login_photo_set: Whether a custom login photo is configured.
        version: Optimistic-concurrency counter, also sent as the ``ETag``.
    """

    # Wider than the edit cap: the stored value is the Fernet token, which this model also reads.
    tileserver_api_key: StrictStr | None = Field(
        default=None,
        max_length=512,
        description="API key for the tile server",
    )
    geocoding_api_key: StrictStr | None = Field(
        default=None,
        max_length=512,
        description="API key for the geocoding service",
    )
    id: StrictInt = Field(..., description="Unique identifier for server settings (always 1)")
    login_photo_set: StrictBool = Field(..., description="Is login photo set (true - yes, false - no)")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter")

ServerSettingsReadPublic

Bases: ServerSettingsBase

Public-facing schema for unauthenticated server settings access.

Provides only public-safe server settings. Used for the public API endpoint that doesn't require authentication.

Inherits all safe fields from ServerSettingsBase but explicitly excludes admin-level configuration fields. The email-verification requirement is public because the sign-up form depends on it and the sign-up response already discloses it; admin approval stays admin-only.

Attributes:

Name Type Description
signup_require_email_verification StrictBool

Whether a new sign-up must verify its email address, which is also when the password is chosen.

login_photo_set StrictBool

Whether a custom login photo is configured.

allowed_redirect_uris list[str]

Exact redirect addresses (ALLOWED_REDIRECT_URIS) that SSO redirects may target, so the frontend validates the same allow-list as the backend.

Source code in backend/app/modules/server_settings/schema.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
class ServerSettingsReadPublic(ServerSettingsBase):
    """Public-facing schema for unauthenticated server settings access.

    Provides only public-safe server settings. Used for the public API
    endpoint that doesn't require authentication.

    Inherits all safe fields from ServerSettingsBase but explicitly
    excludes admin-level configuration fields. The email-verification
    requirement is public because the sign-up form depends on it and the
    sign-up response already discloses it; admin approval stays admin-only.

    Attributes:
        signup_require_email_verification: Whether a new sign-up must verify its email
            address, which is also when the password is chosen.
        login_photo_set: Whether a custom login photo is configured.
        allowed_redirect_uris: Exact redirect addresses (ALLOWED_REDIRECT_URIS) that
            SSO redirects may target, so the frontend validates the same allow-list
            as the backend.
    """

    login_photo_set: StrictBool = Field(..., description="Is login photo set (true - yes, false - no)")
    signup_require_email_verification: StrictBool = Field(
        ...,
        description="Require email verification for new sign-ups (true - yes, false - no)",
    )
    allowed_redirect_uris: list[str] = Field(
        ...,
        description="Exact addresses SSO redirects may target",
    )

ServerSettingsRetention

Bases: BaseModel

The data retention fields, kept off the public settings model.

Attributes:

Name Type Description
read_notification_retention_days StrictInt

Days after which read notifications are purged (0 disables pruning).

Source code in backend/app/modules/server_settings/schema.py
327
328
329
330
331
332
333
334
335
336
class ServerSettingsRetention(BaseModel):
    """The data retention fields, kept off the public settings model.

    Attributes:
        read_notification_retention_days: Days after which read notifications are purged (0 disables pruning).
    """

    read_notification_retention_days: StrictInt = Field(
        ..., ge=0, le=3650, description="Days after which read notifications are purged (0 - never)"
    )

ServerSettingsSessionPolicy

Bases: BaseModel

The session and token policy fields, kept off the public settings model.

Attributes:

Name Type Description
session_idle_timeout_enabled StrictBool

Enforce the idle session timeout; the absolute timeout always applies.

session_idle_timeout_hours StrictInt

Hours of inactivity that end a session (1-8760).

session_absolute_timeout_hours StrictInt

Hours after which a session ends (1-8760, not below the idle timeout).

access_token_expire_minutes StrictInt

Access token lifetime in minutes (1-1440).

refresh_token_expire_days StrictInt

Refresh token lifetime in days (1-365).

api_key_max_lifetime_days StrictInt

Longest lifetime of a new API key, and its default, in days (1-3650).

Source code in backend/app/modules/server_settings/schema.py
284
285
286
287
288
289
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
class ServerSettingsSessionPolicy(BaseModel):
    """The session and token policy fields, kept off the public settings model.

    Attributes:
        session_idle_timeout_enabled: Enforce the idle session timeout; the absolute timeout always applies.
        session_idle_timeout_hours: Hours of inactivity that end a session (1-8760).
        session_absolute_timeout_hours: Hours after which a session ends (1-8760, not below the idle timeout).
        access_token_expire_minutes: Access token lifetime in minutes (1-1440).
        refresh_token_expire_days: Refresh token lifetime in days (1-365).
        api_key_max_lifetime_days: Longest lifetime of a new API key, and its default, in days (1-3650).
    """

    session_idle_timeout_enabled: StrictBool = Field(
        ...,
        description="Enforce the session idle timeout (true - yes, false - no); the absolute timeout always applies",
    )
    session_idle_timeout_hours: StrictInt = Field(
        ..., ge=1, le=8760, description="Hours of inactivity after which a session ends"
    )
    session_absolute_timeout_hours: StrictInt = Field(
        ..., ge=1, le=8760, description="Hours after which a session ends whatever its activity"
    )
    access_token_expire_minutes: StrictInt = Field(..., ge=1, le=1440, description="Access token lifetime in minutes")
    refresh_token_expire_days: StrictInt = Field(..., ge=1, le=365, description="Refresh token lifetime in days")
    api_key_max_lifetime_days: StrictInt = Field(
        ..., ge=1, le=3650, description="Longest lifetime of a new API key, and its default, in days"
    )

    @model_validator(mode="after")
    def validate_absolute_timeout(self) -> "ServerSettingsSessionPolicy":
        """Refuse an absolute timeout shorter than the idle timeout.

        Returns:
            The validated model.

        Raises:
            ValueError: If the absolute timeout is below the idle timeout.
        """
        if self.session_absolute_timeout_hours < self.session_idle_timeout_hours:
            raise ValueError("The absolute session timeout cannot be shorter than the idle timeout")
        return self

validate_absolute_timeout

validate_absolute_timeout()

Refuse an absolute timeout shorter than the idle timeout.

Returns:

Type Description
ServerSettingsSessionPolicy

The validated model.

Raises:

Type Description
ValueError

If the absolute timeout is below the idle timeout.

Source code in backend/app/modules/server_settings/schema.py
312
313
314
315
316
317
318
319
320
321
322
323
324
@model_validator(mode="after")
def validate_absolute_timeout(self) -> "ServerSettingsSessionPolicy":
    """Refuse an absolute timeout shorter than the idle timeout.

    Returns:
        The validated model.

    Raises:
        ValueError: If the absolute timeout is below the idle timeout.
    """
    if self.session_absolute_timeout_hours < self.session_idle_timeout_hours:
        raise ValueError("The absolute session timeout cannot be shorter than the idle timeout")
    return self

TileMapsTemplate

Bases: BaseModel

Schema representing available tile map templates.

Attributes:

Name Type Description
name StrictStr

Human-readable name of the tile map template.

url_template StrictStr

URL template for fetching map tiles.

attribution StrictStr

HTML string for map attribution.

requires_api_key_frontend StrictBool

Indicates if an API key is required on the frontend to use the tile map.

requires_api_key_backend StrictBool

Indicates if an API key is required on the backend to use the tile map.

Source code in backend/app/modules/server_settings/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
622
623
624
625
626
627
628
629
class TileMapsTemplate(BaseModel):
    """Schema representing available tile map templates.

    Attributes:
        name: Human-readable name of the tile map template.
        url_template: URL template for fetching map tiles.
        attribution: HTML string for map attribution.
        requires_api_key_frontend: Indicates if an API key is required on the
            frontend to use the tile map.
        requires_api_key_backend: Indicates if an API key is required on the
            backend to use the tile map.
    """

    template_id: StrictStr = Field(
        ...,
        min_length=1,
        description=("Template identifier (e.g., 'openstreetmap', 'stadia_outdoors')"),
    )
    name: StrictStr = Field(..., min_length=1, description="Human-readable name of the tile map template")
    url_template: StrictStr = Field(..., min_length=1, description="URL template for fetching map tiles")
    attribution: StrictStr = Field(..., min_length=1, description="HTML string for map attribution")
    map_background_color: StrictStr = Field(
        max_length=7,
        min_length=7,
        pattern=r"^#[0-9A-Fa-f]{6}$",
        description=("Hex color code for map background (e.g., #dddddd)"),
    )
    requires_api_key_frontend: StrictBool = Field(
        ...,
        description=("Indicates if an API key is required on the frontend to use the tile map"),
    )
    requires_api_key_backend: StrictBool = Field(
        ...,
        description=("Indicates if an API key is required on the backend to use the tile map"),
    )

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

Units

Bases: Enum

An enumeration representing measurement units.

Attributes:

Name Type Description
METRIC

Metric system (e.g., meters, kilograms).

IMPERIAL

Imperial system (e.g., miles, pounds).

Source code in backend/app/modules/server_settings/schema.py
24
25
26
27
28
29
30
31
32
33
class Units(Enum):
    """An enumeration representing measurement units.

    Attributes:
        METRIC: Metric system (e.g., meters, kilograms).
        IMPERIAL: Imperial system (e.g., miles, pounds).
    """

    METRIC = "metric"
    IMPERIAL = "imperial"

require_access_token_below_idle_timeout

require_access_token_below_idle_timeout(idle_timeout_enabled, idle_timeout_hours, access_token_expire_minutes)

Refuse an access token that lives as long as the enforced idle timeout.

The idle timeout counts from the last refresh, which the client does only after an access token expires, so a lifetime at or above the idle timeout can end the session of a user who is active.

Parameters:

Name Type Description Default
idle_timeout_enabled bool

Whether the idle timeout is enforced; nothing is refused while it is not.

required
idle_timeout_hours int

The idle timeout in hours.

required
access_token_expire_minutes int

The access token lifetime in minutes.

required

Raises:

Type Description
ValueError

If the idle timeout is enforced and the access token lifetime is not shorter than it.

Source code in backend/app/modules/server_settings/schema.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def require_access_token_below_idle_timeout(
    idle_timeout_enabled: bool, idle_timeout_hours: int, access_token_expire_minutes: int
) -> None:
    """Refuse an access token that lives as long as the enforced idle timeout.

    The idle timeout counts from the last refresh, which the client does only after an access token expires, so
    a lifetime at or above the idle timeout can end the session of a user who is active.

    Args:
        idle_timeout_enabled: Whether the idle timeout is enforced; nothing is refused while it is not.
        idle_timeout_hours: The idle timeout in hours.
        access_token_expire_minutes: The access token lifetime in minutes.

    Raises:
        ValueError: If the idle timeout is enforced and the access token lifetime is not shorter than it.
    """
    if idle_timeout_enabled and access_token_expire_minutes >= idle_timeout_hours * 60:
        raise ValueError("The access token lifetime must be shorter than the idle timeout")