Skip to content

API Reference

Server settings module for configuration and database management.

This module provides server-wide configuration management, including measurement units, currency settings, signup policies, SSO configuration, and map tile server settings.

Exports
  • CRUD operations: get_server_settings, edit_server_settings
  • Schemas: ServerSettings, ServerSettingsEdit, ServerSettingsRead, ServerSettingsReadPublic
  • Utilities: get_server_settings_or_404 (wrapper), get_tile_maps_templates
  • Models: ServerSettings (ORM model)
  • Enums: Units, Currency, PasswordType

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/server_settings/schema.py
35
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"

PasswordType

Bases: Enum

An enumeration representing password policy types.

Attributes:

Name Type Description
STRICT str

Strict password policy.

LENGTH_ONLY str

Length-only password policy.

Source code in backend/app/server_settings/schema.py
50
51
52
53
54
55
56
57
58
59
60
class PasswordType(Enum):
    """
    An enumeration representing password policy types.

    Attributes:
        STRICT (str): Strict password policy.
        LENGTH_ONLY (str): Length-only password policy.
    """

    STRICT = "strict"
    LENGTH_ONLY = "length_only"

ServerSettings

Bases: ServerSettingsBase

Internal complete server settings schema with identifier.

Extends ServerSettingsBase by adding the id field for internal operations. Not typically used for API responses.

Attributes:

Name Type Description
id StrictInt

Unique identifier (always 1, singleton pattern).

tileserver_api_key StrictStr | None

API key encrypted for the tile server.

Source code in backend/app/server_settings/schema.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
class ServerSettings(ServerSettingsBase):
    """
    Internal complete server settings schema with identifier.

    Extends ServerSettingsBase by adding the id field for internal
    operations. Not typically used for API responses.

    Attributes:
        id: Unique identifier (always 1, singleton pattern).
        tileserver_api_key: API key encrypted for the tile server.
    """

    id: StrictInt = Field(
        ..., description="Unique identifier for server settings (always 1)"
    )
    tileserver_api_key: StrictStr | None = Field(
        default=None,
        max_length=512,
        description="API key encrypted for the tile server",
    )

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.

login_photo_set StrictBool

Whether login photo is configured.

currency Currency

Currency type (EURO, DOLLAR, or POUND).

num_records_per_page StrictInt

Number of records per page in lists (1-100, default: 25).

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 only one IdP is configured.

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_type PasswordType

Password policy enforcement level (STRICT or LENGTH_ONLY).

password_length_regular_users StrictInt

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

password_length_admin_users StrictInt

Minimum password length for admin users (8-128, default: 12).

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/server_settings/schema.py
 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
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
242
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.
        login_photo_set (StrictBool): Whether login photo is configured.
        currency (Currency): Currency type (EURO, DOLLAR, or POUND).
        num_records_per_page (StrictInt): Number of records per page in lists (1-100, default: 25).
        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 only one IdP is configured.
        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_type (PasswordType): Password policy enforcement level (STRICT or LENGTH_ONLY).
        password_length_regular_users (StrictInt): Minimum password length for regular users (8-128, default: 8).
        password_length_admin_users (StrictInt): Minimum password length for admin users (8-128, default: 12).

    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(Units.METRIC, 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)",
    )
    login_photo_set: StrictBool = Field(
        ..., description="Is login photo set (true - yes, false - no)"
    )
    currency: Currency = Field(..., description="Currency (euro, dollar, pound)")
    num_records_per_page: StrictInt = Field(
        25,
        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(
        False,
        description=(
            "Delete and regenerate all activity thumbnails when "
            "tile server settings change"
        ),
    )
    password_type: PasswordType = Field(
        PasswordType.STRICT, description="Password type policy (strict, length_only)"
    )
    password_length_regular_users: StrictInt = Field(
        8, ge=8, le=128, description="Minimum password length for regular users"
    )
    password_length_admin_users: StrictInt = Field(
        12, 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://"):
            if 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.lower()]
        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/server_settings/schema.py
230
231
232
233
234
235
236
237
238
239
240
241
242
@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/server_settings/schema.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@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://"):
        if 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.lower()]
    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: ServerSettings

Edit schema for server settings updates.

Extends ServerSettings with signup requirement fields.

Attributes:

Name Type Description
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).

Source code in backend/app/server_settings/schema.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
class ServerSettingsEdit(ServerSettings):
    """
    Edit schema for server settings updates.

    Extends ServerSettings with signup requirement fields.

    Attributes:
        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).
    """

    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)",
    )

ServerSettingsModel

Bases: Base

Server-wide configuration settings.

Attributes:

Name Type Description
id Mapped[int]

Primary key (always 1, singleton pattern).

units Mapped[str]

Measurement units (metric, imperial).

public_shareable_links Mapped[bool]

Allow public shareable links.

public_shareable_links_user_info Mapped[bool]

Show user info on public links.

login_photo_set Mapped[bool]

Login photo has been configured.

currency Mapped[str]

Currency type (euro, dollar, pound).

num_records_per_page Mapped[int]

Default pagination size.

signup_enabled Mapped[bool]

Allow user registration.

signup_require_admin_approval Mapped[bool]

Require approval for new signups.

signup_require_email_verification Mapped[bool]

Require email verification for new signups.

sso_enabled Mapped[bool]

Enable SSO/IdP login.

local_login_enabled Mapped[bool]

Allow local login.

sso_auto_redirect Mapped[bool]

Auto-redirect to SSO.

tileserver_url Mapped[str]

Map tile server URL template.

tileserver_attribution Mapped[str]

Map tile attribution.

tileserver_api_key Mapped[str | None]

API key for tile server (encrypted).

tileserver_regenerate_thumbnails_on_change Mapped[bool]

Regenerate thumbnails when tile server settings change.

map_background_color Mapped[str]

Map background hex color.

password_type Mapped[str]

Password policy type.

password_length_regular_users Mapped[int]

Min password length for regular users.

password_length_admin_users Mapped[int]

Min password length for admin users.

Source code in backend/app/server_settings/models.py
  6
  7
  8
  9
 10
 11
 12
 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
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
class ServerSettings(Base):
    """
    Server-wide configuration settings.

    Attributes:
        id: Primary key (always 1, singleton pattern).
        units: Measurement units (metric, imperial).
        public_shareable_links: Allow public shareable links.
        public_shareable_links_user_info: Show user info on
            public links.
        login_photo_set: Login photo has been configured.
        currency: Currency type (euro, dollar, pound).
        num_records_per_page: Default pagination size.
        signup_enabled: Allow user registration.
        signup_require_admin_approval: Require approval for
            new signups.
        signup_require_email_verification: Require email
            verification for new signups.
        sso_enabled: Enable SSO/IdP login.
        local_login_enabled: Allow local login.
        sso_auto_redirect: Auto-redirect to SSO.
        tileserver_url: Map tile server URL template.
        tileserver_attribution: Map tile attribution.
        tileserver_api_key: API key for tile server (encrypted).
        tileserver_regenerate_thumbnails_on_change: Regenerate
            thumbnails when tile server settings change.
        map_background_color: Map background hex color.
        password_type: Password policy type.
        password_length_regular_users: Min password length
            for regular users.
        password_length_admin_users: Min password length for
            admin users.
    """

    __tablename__ = "server_settings"

    id: Mapped[int] = mapped_column(
        primary_key=True,
        default=1,
        nullable=False,
    )
    units: Mapped[str] = mapped_column(
        String(20),
        default="metric",
        nullable=False,
        comment="Units (metric, imperial)",
    )
    public_shareable_links: Mapped[bool] = mapped_column(
        default=False,
        nullable=False,
        comment="Allow public shareable links (true - yes, false - no)",
    )
    public_shareable_links_user_info: Mapped[bool] = mapped_column(
        default=False,
        nullable=False,
        comment="Allow show user info on public shareable links (true - yes, false - no)",
    )
    login_photo_set: Mapped[bool] = mapped_column(
        default=False,
        nullable=False,
        comment="Is login photo set (true - yes, false - no)",
    )
    currency: Mapped[str] = mapped_column(
        String(20),
        default="euro",
        nullable=False,
        comment="Currency (euro, dollar, pound)",
    )
    num_records_per_page: Mapped[int] = mapped_column(
        default=25,
        nullable=False,
        comment="Number of records per page in lists",
    )
    signup_enabled: Mapped[bool] = mapped_column(
        default=False,
        nullable=False,
        comment="Allow user sign-up registration (true - yes, false - no)",
    )
    signup_require_admin_approval: Mapped[bool] = mapped_column(
        default=True,
        nullable=False,
        comment="Require admin approval for new sign-ups (true - yes, false - no)",
    )
    signup_require_email_verification: Mapped[bool] = mapped_column(
        default=True,
        nullable=False,
        comment="Require email verification for new sign-ups (true - yes, false - no)",
    )
    sso_enabled: Mapped[bool] = mapped_column(
        default=False,
        nullable=False,
        comment="Enable SSO/IdP login (true - yes, false - no)",
    )
    local_login_enabled: Mapped[bool] = mapped_column(
        default=True,
        nullable=False,
        comment="Allow local username/password login (true - yes, false - no)",
    )
    sso_auto_redirect: Mapped[bool] = mapped_column(
        default=False,
        nullable=False,
        comment="Auto-redirect to SSO if only one IdP (true - yes, false - no)",
    )
    tileserver_url: Mapped[str] = mapped_column(
        default=("https://{s}.tile.openstreetmap.org/" "{z}/{x}/{y}.png"),
        nullable=False,
        comment="URL template for the map tileserver",
    )
    tileserver_attribution: Mapped[str] = mapped_column(
        default=(
            '&copy; <a href="https://www.openstreetmap.org/'
            'copyright">OpenStreetMap</a> contributors'
        ),
        nullable=False,
        comment="Attribution string for the map tileserver",
    )
    tileserver_api_key: Mapped[str | None] = mapped_column(
        String(length=512),
        default=None,
        nullable=True,
        comment=("API key encrypted for the tile server"),
    )
    tileserver_regenerate_thumbnails_on_change: Mapped[bool] = mapped_column(
        default=False,
        nullable=False,
        comment=(
            "Delete and regenerate all activity thumbnails when "
            "tile server settings change"
        ),
    )
    map_background_color: Mapped[str] = mapped_column(
        default="#dddddd",
        nullable=False,
        comment="Background color for the map (hex format)",
    )
    password_type: Mapped[str] = mapped_column(
        default="strict",
        nullable=False,
        comment="Password type policy (strict, length_only)",
    )
    password_length_regular_users: Mapped[int] = mapped_column(
        default=8,
        nullable=False,
        comment="Minimum password length for regular users",
    )
    password_length_admin_users: Mapped[int] = mapped_column(
        default=12,
        nullable=False,
        comment="Minimum password length for admin users",
    )

    __table_args__ = (CheckConstraint("id = 1", name="single_row_check"),)

ServerSettingsRead

Bases: ServerSettingsEdit

Complete server settings response schema for API responses.

Read-only view of all server settings including administrative signup configuration. Used for authenticated endpoints returning complete server configuration.

Source code in backend/app/server_settings/schema.py
290
291
292
293
294
295
296
297
class ServerSettingsRead(ServerSettingsEdit):
    """
    Complete server settings response schema for API responses.

    Read-only view of all server settings including administrative
    signup configuration. Used for authenticated endpoints returning
    complete server configuration.
    """

ServerSettingsReadPublic

Bases: ServerSettingsBase

Public-facing schema for unauthenticated server settings access.

Provides only public-safe server settings, excluding sensitive configuration like signup requirements. Used for the public API endpoint that doesn't require authentication.

Inherits all safe fields from ServerSettingsBase but explicitly excludes admin-level configuration fields.

Source code in backend/app/server_settings/schema.py
300
301
302
303
304
305
306
307
308
309
310
class ServerSettingsReadPublic(ServerSettingsBase):
    """
    Public-facing schema for unauthenticated server settings access.

    Provides only public-safe server settings, excluding sensitive
    configuration like signup requirements. Used for the public API
    endpoint that doesn't require authentication.

    Inherits all safe fields from ServerSettingsBase but explicitly
    excludes admin-level configuration fields.
    """

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/server_settings/schema.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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/server_settings/schema.py
22
23
24
25
26
27
28
29
30
31
32
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"

edit_server_settings

edit_server_settings(server_settings, db)

Update server settings in database.

Parameters:

Name Type Description Default
server_settings ServerSettingsEdit

New settings to apply.

required
db Session

Database session.

required

Returns:

Type Description
ServerSettings

Updated ServerSettings instance.

Raises:

Type Description
HTTPException

If settings not found or database error.

Source code in backend/app/server_settings/crud.py
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
@core_decorators.handle_db_errors
def edit_server_settings(
    server_settings: server_settings_schema.ServerSettingsEdit, db: Session
) -> server_settings_models.ServerSettings:
    """
    Update server settings in database.

    Args:
        server_settings: New settings to apply.
        db: Database session.

    Returns:
        Updated ServerSettings instance.

    Raises:
        HTTPException: If settings not found or database error.
    """
    # Get the server_settings from the database
    db_server_settings = server_settings_utils.get_server_settings_or_404(db)

    if server_settings.tileserver_api_key is not None:
        # Encrypt the tile server API key before storing
        encrypted_api_key = core_cryptography.encrypt_token_fernet(
            server_settings.tileserver_api_key
        )
        server_settings.tileserver_api_key = encrypted_api_key

    # Dictionary of the fields to update if they are not None
    server_settings_data = server_settings.model_dump(exclude_unset=True)
    # Iterate over the fields and update the db_user dynamically
    for key, value in server_settings_data.items():
        setattr(db_server_settings, key, value)

    # Commit the transaction
    db.commit()
    # Refresh the object to ensure it reflects database state
    db.refresh(db_server_settings)

    return db_server_settings

get_server_settings_db

get_server_settings_db(db)

Retrieve singleton server settings from database.

Parameters:

Name Type Description Default
db Session

Database session.

required

Returns:

Type Description
ServerSettings | None

ServerSettings instance or None if not found.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/server_settings/crud.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@core_decorators.handle_db_errors
def get_server_settings(db: Session) -> server_settings_models.ServerSettings | None:
    """
    Retrieve singleton server settings from database.

    Args:
        db: Database session.

    Returns:
        ServerSettings instance or None if not found.

    Raises:
        HTTPException: If database error occurs.
    """
    # Get the server settings from the database
    stmt = select(server_settings_models.ServerSettings).where(
        server_settings_models.ServerSettings.id == 1
    )
    return db.execute(stmt).scalar_one_or_none()

get_server_settings_or_404

get_server_settings_or_404(db)

Get server settings or raise 404.

Parameters:

Name Type Description Default
db Session

Database session.

required

Returns:

Type Description
ServerSettings

ServerSettings instance.

Raises:

Type Description
HTTPException

If server settings not found.

Source code in backend/app/server_settings/utils.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def get_server_settings_or_404(db: Session) -> server_settings_models.ServerSettings:
    """
    Get server settings or raise 404.

    Args:
        db: Database session.

    Returns:
        ServerSettings instance.

    Raises:
        HTTPException: If server settings not found.
    """
    server_settings = server_settings_crud.get_server_settings(db)

    if not server_settings:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Server settings not found",
        ) from None

    return server_settings

get_tile_maps_templates

get_tile_maps_templates()

Retrieve a list of tile map templates.

Returns:

Type Description
list[TileMapsTemplate]

list[server_settings_schema.TileMapsTemplate]: A list of TileMapsTemplate objects for all tile maps.

Source code in backend/app/server_settings/utils.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def get_tile_maps_templates() -> list[server_settings_schema.TileMapsTemplate]:
    """
    Retrieve a list of tile map templates.

    Returns:
        list[server_settings_schema.TileMapsTemplate]:
            A list of TileMapsTemplate objects for all tile maps.
    """
    templates = []
    for template_id, template_data in TILE_MAPS_TEMPLATES.items():
        templates.append(
            server_settings_schema.TileMapsTemplate(
                template_id=template_id, **template_data
            )
        )
    return templates