allowthem-core 0.0.3

Core types, database, and auth logic for allowthem
Documentation
1
2
3
4
5
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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
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
406
407
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
use chrono::{DateTime, Utc};
use serde::Serialize;
use serde_json::Value;

use crate::db::Db;
use crate::error::AuthError;
use crate::password::hash_password;
use crate::types::{Email, User, UserId, Username};

/// Map a SQLite UNIQUE constraint violation to `AuthError::Conflict`.
///
/// SQLite UNIQUE violations include the constraint name in the message,
/// e.g. "UNIQUE constraint failed: allowthem_users.email".
pub(crate) fn map_unique_violation(err: sqlx::Error) -> AuthError {
    if let sqlx::Error::Database(ref db_err) = err {
        let msg = db_err.message();
        if msg.contains("UNIQUE constraint failed") {
            if msg.contains("email") {
                return AuthError::Conflict("email already exists".into());
            }
            if msg.contains("username") {
                return AuthError::Conflict("username already exists".into());
            }
            return AuthError::Conflict(msg.to_string());
        }
    }
    AuthError::Database(err)
}

/// Parameters for searching/filtering users in the admin directory.
pub struct SearchUsersParams<'a> {
    pub query: Option<&'a str>,
    pub is_active: Option<bool>,
    pub has_mfa: Option<bool>,
    pub limit: u32,
    pub offset: u32,
}

/// User with MFA enrollment status, for list display.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct UserListEntry {
    pub id: UserId,
    pub email: Email,
    pub username: Option<Username>,
    pub is_active: bool,
    pub has_mfa: bool,
    pub created_at: DateTime<Utc>,
}

/// Result of a paginated user search.
pub struct SearchUsersResult {
    pub users: Vec<UserListEntry>,
    pub total: u32,
}

impl Db {
    /// Create a user with email, plaintext password, optional username, and optional custom data.
    ///
    /// Hashes the password with Argon2id (via `password::hash_password`).
    /// Returns the created User (without password_hash in the returned struct).
    pub async fn create_user(
        &self,
        email: Email,
        password: &str,
        username: Option<Username>,
        custom_data: Option<&Value>,
    ) -> Result<User, AuthError> {
        let id = UserId::new();
        let pw_hash = hash_password(password)?;
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();

        sqlx::query(
            "INSERT INTO allowthem_users \
             (id, email, username, password_hash, email_verified, is_active, created_at, updated_at, custom_data) \
             VALUES (?1, ?2, ?3, ?4, 0, 1, ?5, ?5, ?6)",
        )
        .bind(id)
        .bind(&email)
        .bind(&username)
        .bind(&pw_hash)
        .bind(&now)
        .bind(custom_data.map(sqlx::types::Json))
        .execute(self.pool())
        .await
        .map_err(map_unique_violation)?;

        self.get_user(id).await
    }

    /// Import a user with a pre-existing password hash (for migration from external systems).
    /// The hash must be a valid Argon2 PHC string. No validation is performed on it.
    pub async fn create_user_with_hash(
        &self,
        email: Email,
        password_hash: &str,
        username: Option<Username>,
        custom_data: Option<&Value>,
    ) -> Result<User, AuthError> {
        let id = UserId::new();
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();

        sqlx::query(
            "INSERT INTO allowthem_users (id, email, username, password_hash, email_verified, is_active, created_at, updated_at, custom_data)
             VALUES (?1, ?2, ?3, ?4, 0, 1, ?5, ?5, ?6)",
        )
        .bind(id)
        .bind(&email)
        .bind(&username)
        .bind(password_hash)
        .bind(&now)
        .bind(custom_data.map(sqlx::types::Json))
        .execute(self.pool())
        .await
        .map_err(map_unique_violation)?;

        self.get_user(id).await
    }

    /// Look up a user by ID. Returns User with password_hash = None.
    pub async fn get_user(&self, id: UserId) -> Result<User, AuthError> {
        sqlx::query_as::<_, User>(
            "SELECT id, email, username, NULL as password_hash, \
             email_verified, is_active, created_at, updated_at, custom_data \
             FROM allowthem_users WHERE id = ?",
        )
        .bind(id)
        .fetch_optional(self.pool())
        .await?
        .ok_or(AuthError::NotFound)
    }

    /// Look up a user by email. Returns User with password_hash = None.
    pub async fn get_user_by_email(&self, email: &Email) -> Result<User, AuthError> {
        sqlx::query_as::<_, User>(
            "SELECT id, email, username, NULL as password_hash, \
             email_verified, is_active, created_at, updated_at, custom_data \
             FROM allowthem_users WHERE email = ?",
        )
        .bind(email)
        .fetch_optional(self.pool())
        .await?
        .ok_or(AuthError::NotFound)
    }

    /// Look up a user by username. Returns User with password_hash = None.
    pub async fn get_user_by_username(&self, username: &Username) -> Result<User, AuthError> {
        sqlx::query_as::<_, User>(
            "SELECT id, email, username, NULL as password_hash, \
             email_verified, is_active, created_at, updated_at, custom_data \
             FROM allowthem_users WHERE username = ?",
        )
        .bind(username)
        .fetch_optional(self.pool())
        .await?
        .ok_or(AuthError::NotFound)
    }

    /// Look up a user by email OR username for login.
    ///
    /// Returns User WITH password_hash populated. The caller is responsible
    /// for calling `verify_password()` to check the password.
    pub async fn find_for_login(&self, identifier: &str) -> Result<User, AuthError> {
        sqlx::query_as::<_, User>(
            "SELECT id, email, username, password_hash, \
             email_verified, is_active, created_at, updated_at, custom_data \
             FROM allowthem_users WHERE email = ?1 OR username = ?1",
        )
        .bind(identifier)
        .fetch_optional(self.pool())
        .await?
        .ok_or(AuthError::NotFound)
    }

    /// Update a user's email. Also updates updated_at.
    pub async fn update_user_email(&self, id: UserId, email: Email) -> Result<(), AuthError> {
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let result =
            sqlx::query("UPDATE allowthem_users SET email = ?1, updated_at = ?2 WHERE id = ?3")
                .bind(&email)
                .bind(&now)
                .bind(id)
                .execute(self.pool())
                .await
                .map_err(map_unique_violation)?;

        if result.rows_affected() == 0 {
            return Err(AuthError::NotFound);
        }
        Ok(())
    }

    /// Update a user's username (set or clear). Also updates updated_at.
    pub async fn update_user_username(
        &self,
        id: UserId,
        username: Option<Username>,
    ) -> Result<(), AuthError> {
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let result =
            sqlx::query("UPDATE allowthem_users SET username = ?1, updated_at = ?2 WHERE id = ?3")
                .bind(&username)
                .bind(&now)
                .bind(id)
                .execute(self.pool())
                .await
                .map_err(map_unique_violation)?;

        if result.rows_affected() == 0 {
            return Err(AuthError::NotFound);
        }
        Ok(())
    }

    /// Update a user's is_active flag. Also updates updated_at.
    pub async fn update_user_active(&self, id: UserId, is_active: bool) -> Result<(), AuthError> {
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let result =
            sqlx::query("UPDATE allowthem_users SET is_active = ?1, updated_at = ?2 WHERE id = ?3")
                .bind(is_active)
                .bind(&now)
                .bind(id)
                .execute(self.pool())
                .await?;

        if result.rows_affected() == 0 {
            return Err(AuthError::NotFound);
        }
        Ok(())
    }

    /// Delete a user by ID. Cascades to sessions, user_roles, user_permissions.
    pub async fn delete_user(&self, id: UserId) -> Result<(), AuthError> {
        let result = sqlx::query("DELETE FROM allowthem_users WHERE id = ?")
            .bind(id)
            .execute(self.pool())
            .await?;

        if result.rows_affected() == 0 {
            return Err(AuthError::NotFound);
        }
        Ok(())
    }

    /// List all users ordered by `created_at ASC`. Returns User with `password_hash = None`.
    pub async fn list_users(&self) -> Result<Vec<User>, AuthError> {
        sqlx::query_as::<_, User>(
            "SELECT id, email, username, NULL as password_hash, \
             email_verified, is_active, created_at, updated_at, custom_data \
             FROM allowthem_users ORDER BY created_at ASC",
        )
        .fetch_all(self.pool())
        .await
        .map_err(AuthError::Database)
    }

    /// Search and filter users with pagination.
    ///
    /// Builds a dynamic query with optional search term (matched against
    /// email and username via LIKE), status filter, and MFA filter.
    /// Returns matching users with their MFA enrollment status.
    pub async fn search_users(
        &self,
        params: SearchUsersParams<'_>,
    ) -> Result<SearchUsersResult, AuthError> {
        let mut where_clauses: Vec<String> = Vec::new();
        let mut bind_values: Vec<String> = Vec::new();

        if let Some(q) = params.query {
            let trimmed = q.trim();
            if !trimmed.is_empty() {
                let escaped = trimmed
                    .replace('\\', "\\\\")
                    .replace('%', "\\%")
                    .replace('_', "\\_");
                let pattern = format!("%{escaped}%");
                where_clauses
                    .push("(u.email LIKE ? ESCAPE '\\' OR u.username LIKE ? ESCAPE '\\')".into());
                bind_values.push(pattern.clone());
                bind_values.push(pattern);
            }
        }

        if let Some(active) = params.is_active {
            where_clauses.push("u.is_active = ?".into());
            bind_values.push(if active { "1".into() } else { "0".into() });
        }

        if let Some(has_mfa) = params.has_mfa {
            let exists = if has_mfa { "EXISTS" } else { "NOT EXISTS" };
            where_clauses.push(format!(
                "{exists} (SELECT 1 FROM allowthem_mfa_secrets WHERE user_id = u.id AND enabled = 1)"
            ));
        }

        let where_sql = if where_clauses.is_empty() {
            String::new()
        } else {
            format!("WHERE {}", where_clauses.join(" AND "))
        };

        let count_sql: &'static str = Box::leak(
            format!("SELECT COUNT(*) FROM allowthem_users u {where_sql}").into_boxed_str(),
        );
        let mut count_query = sqlx::query_scalar::<_, i64>(count_sql);
        for val in &bind_values {
            count_query = count_query.bind(val);
        }
        let total = count_query
            .fetch_one(self.pool())
            .await
            .map_err(AuthError::Database)? as u32;

        let data_sql: &'static str = Box::leak(
            format!(
                "SELECT u.id, u.email, u.username, u.is_active, \
                 EXISTS (SELECT 1 FROM allowthem_mfa_secrets \
                         WHERE user_id = u.id AND enabled = 1) as has_mfa, \
                 u.created_at \
                 FROM allowthem_users u {where_sql} \
                 ORDER BY u.created_at ASC \
                 LIMIT ? OFFSET ?"
            )
            .into_boxed_str(),
        );
        let mut data_query = sqlx::query_as::<_, UserListEntry>(data_sql);
        for val in &bind_values {
            data_query = data_query.bind(val);
        }
        data_query = data_query.bind(params.limit).bind(params.offset);

        let users = data_query
            .fetch_all(self.pool())
            .await
            .map_err(AuthError::Database)?;

        Ok(SearchUsersResult { users, total })
    }

    /// Update a user's password. Hashes `new_password` with Argon2id and stores it.
    ///
    /// Returns `AuthError::NotFound` if no user with `id` exists.
    pub async fn update_user_password(
        &self,
        id: UserId,
        new_password: &str,
    ) -> Result<(), AuthError> {
        let pw_hash = hash_password(new_password)?;
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let result = sqlx::query(
            "UPDATE allowthem_users SET password_hash = ?1, updated_at = ?2 WHERE id = ?3",
        )
        .bind(&pw_hash)
        .bind(&now)
        .bind(id)
        .execute(self.pool())
        .await?;

        if result.rows_affected() == 0 {
            return Err(AuthError::NotFound);
        }
        Ok(())
    }

    /// Set a user's password hash to NULL.
    ///
    /// Used by admin force-password-reset to invalidate the current password.
    /// The login flow falls back to a dummy hash when `password_hash` is NULL,
    /// so `verify_password` will always fail.
    pub async fn clear_password_hash(&self, id: UserId) -> Result<(), AuthError> {
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let result = sqlx::query(
            "UPDATE allowthem_users SET password_hash = NULL, updated_at = ? WHERE id = ?",
        )
        .bind(&now)
        .bind(id)
        .execute(self.pool())
        .await?;

        if result.rows_affected() == 0 {
            return Err(AuthError::NotFound);
        }
        Ok(())
    }

    /// Get a user's custom data.
    ///
    /// Returns `Err(NotFound)` if no user with `id` exists.
    /// Returns `Ok(None)` if the user exists but has no custom data.
    pub async fn get_custom_data(&self, id: &UserId) -> Result<Option<Value>, AuthError> {
        let row: Option<(Option<Value>,)> =
            sqlx::query_as("SELECT custom_data FROM allowthem_users WHERE id = ?")
                .bind(id)
                .fetch_optional(self.pool())
                .await?;

        match row {
            None => Err(AuthError::NotFound),
            Some((data,)) => Ok(data),
        }
    }

    /// Set a user's custom data. Also updates `updated_at`.
    ///
    /// Returns `Err(NotFound)` if no user with `id` exists.
    pub async fn set_custom_data(&self, id: &UserId, data: &Value) -> Result<(), AuthError> {
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let result = sqlx::query(
            "UPDATE allowthem_users SET custom_data = ?1, updated_at = ?2 WHERE id = ?3",
        )
        .bind(sqlx::types::Json(data))
        .bind(&now)
        .bind(id)
        .execute(self.pool())
        .await?;

        if result.rows_affected() == 0 {
            return Err(AuthError::NotFound);
        }
        Ok(())
    }

    /// Delete (clear) a user's custom data by setting it to NULL. Also updates `updated_at`.
    ///
    /// Idempotent -- succeeds even if custom data is already NULL.
    pub async fn delete_custom_data(&self, id: &UserId) -> Result<(), AuthError> {
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        sqlx::query("UPDATE allowthem_users SET custom_data = NULL, updated_at = ?1 WHERE id = ?2")
            .bind(&now)
            .bind(id)
            .execute(self.pool())
            .await?;

        Ok(())
    }
}