allowthem-core 0.0.9

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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
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
546
547
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
use base64ct::{Base64UrlUnpadded, Encoding};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::db::Db;
use crate::error::AuthError;
use crate::event_sink::AuthEvent;
use crate::handle::AllowThem;
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>,
    /// Optional filter on `email_verified`. `Some(true)` returns only users
    /// with verified emails; `Some(false)` only unverified; `None` includes
    /// both. Surfaced for the dashboard user-management page (99c.4).
    pub email_verified: 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,
}

/// Opaque keyset cursor for paginating `list_users_paginated`.
///
/// Encodes `(created_at, id)` as a base64url-encoded JSON blob.
pub struct UserCursor {
    pub created_at: DateTime<Utc>,
    pub id: UserId,
}

#[derive(Serialize, Deserialize)]
struct RawUserCursor {
    ca: String,
    id: String,
}

impl UserCursor {
    pub fn from_entry(entry: &UserListEntry) -> Self {
        Self {
            created_at: entry.created_at,
            id: entry.id,
        }
    }

    pub fn encode(&self) -> String {
        let raw = RawUserCursor {
            ca: self.created_at.to_rfc3339(),
            id: self.id.to_string(),
        };
        let json = serde_json::to_string(&raw).expect("RawUserCursor serializes");
        Base64UrlUnpadded::encode_string(json.as_bytes())
    }

    pub fn decode(s: &str) -> Option<Self> {
        let bytes = Base64UrlUnpadded::decode_vec(s).ok()?;
        let raw: RawUserCursor = serde_json::from_slice(&bytes).ok()?;
        let created_at = chrono::DateTime::parse_from_rfc3339(&raw.ca)
            .ok()?
            .with_timezone(&Utc);
        let id = raw.id.parse::<uuid::Uuid>().ok().map(UserId::from_uuid)?;
        Some(Self { created_at, id })
    }
}

impl Db {
    /// Count of all users in the tenant DB. Used by the SaaS super-admin
    /// tenant detail panel (99c.6 §6.1).
    pub async fn count_users(&self) -> Result<u64, AuthError> {
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM allowthem_users")
            .fetch_one(self.pool())
            .await
            .map_err(AuthError::Database)?;
        Ok(n as u64)
    }

    /// 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(())
    }

    /// Update a user's `email_verified` flag. Also updates `updated_at`.
    ///
    /// Pool-level helper for callers that update verification status outside
    /// the token-redemption transaction (e.g. the seed-admin CLI marking a
    /// freshly created super-admin verified). The transactional update inside
    /// `verify_email` keeps its inline `UPDATE` to stay atomic with the
    /// "mark token used" write.
    pub async fn set_email_verified(&self, id: UserId, verified: 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 email_verified = ?1, updated_at = ?2 WHERE id = ?3",
        )
        .bind(verified)
        .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)
    }

    /// Paginated list of users using a `(created_at, id)` keyset cursor.
    ///
    /// Limits are capped at 200. Pass `None` for cursor to start from the beginning.
    /// Results are ordered oldest-first.
    pub async fn list_users_paginated(
        &self,
        limit: u32,
        cursor: Option<&UserCursor>,
    ) -> Result<Vec<UserListEntry>, AuthError> {
        let limit = (limit as i64).min(200);
        match cursor {
            None => sqlx::query_as::<_, UserListEntry>(
                "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 \
                 ORDER BY u.created_at ASC, u.id ASC \
                 LIMIT ?",
            )
            .bind(limit)
            .fetch_all(self.pool())
            .await
            .map_err(AuthError::Database),
            Some(c) => {
                let ca = c.created_at.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
                sqlx::query_as::<_, UserListEntry>(
                    "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 (u.created_at > ?1 OR (u.created_at = ?1 AND u.id > ?2)) \
                     ORDER BY u.created_at ASC, u.id ASC \
                     LIMIT ?3",
                )
                .bind(&ca)
                .bind(c.id)
                .bind(limit)
                .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)"
            ));
        }

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

        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(())
    }
}

// ─── AllowThem wrappers ───────────────────────────────────────────────────────

impl AllowThem {
    /// Create a user and emit a `user.created` event on success.
    pub async fn create_user(
        &self,
        email: Email,
        password: &str,
        username: Option<Username>,
        custom_data: Option<&Value>,
    ) -> Result<User, AuthError> {
        let user = self
            .db()
            .create_user(email, password, username, custom_data)
            .await?;
        self.emit_event(AuthEvent::new(
            "user.created",
            Some(user.id),
            serde_json::json!({
                "user_id": user.id,
                "email": user.email,
                "username": user.username,
            }),
        ))
        .await;
        Ok(user)
    }

    /// Update a user's email address and emit a `user.updated` event on success.
    pub async fn update_user_email(&self, id: UserId, email: Email) -> Result<(), AuthError> {
        self.db().update_user_email(id, email).await?;
        self.emit_event(AuthEvent::new(
            "user.updated",
            Some(id),
            serde_json::json!({ "user_id": id, "field": "email" }),
        ))
        .await;
        Ok(())
    }

    /// Update a user's username and emit a `user.updated` event on success.
    pub async fn update_user_username(
        &self,
        id: UserId,
        username: Option<Username>,
    ) -> Result<(), AuthError> {
        self.db().update_user_username(id, username).await?;
        self.emit_event(AuthEvent::new(
            "user.updated",
            Some(id),
            serde_json::json!({ "user_id": id, "field": "username" }),
        ))
        .await;
        Ok(())
    }

    /// Update a user's password and emit a `password.changed` event on success.
    pub async fn update_user_password(
        &self,
        id: UserId,
        new_password: &str,
    ) -> Result<(), AuthError> {
        self.db().update_user_password(id, new_password).await?;
        self.emit_event(AuthEvent::new(
            "password.changed",
            Some(id),
            serde_json::json!({ "user_id": id }),
        ))
        .await;
        Ok(())
    }

    /// Delete a user and emit a `user.deleted` event on success.
    pub async fn delete_user(&self, id: UserId) -> Result<(), AuthError> {
        self.db().delete_user(id).await?;
        self.emit_event(AuthEvent::new(
            "user.deleted",
            Some(id),
            serde_json::json!({ "user_id": id }),
        ))
        .await;
        Ok(())
    }

    /// Set a user's active status and emit `user.blocked` or `user.unblocked`.
    pub async fn update_user_active(&self, id: UserId, is_active: bool) -> Result<(), AuthError> {
        self.db().update_user_active(id, is_active).await?;
        let event_type = if is_active {
            "user.unblocked"
        } else {
            "user.blocked"
        };
        self.emit_event(AuthEvent::new(
            event_type,
            Some(id),
            serde_json::json!({ "user_id": id }),
        ))
        .await;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handle::{AllowThem, AllowThemBuilder};

    async fn setup() -> AllowThem {
        AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .build()
            .await
            .unwrap()
    }

    async fn make_user(db: &Db, tag: u32) -> crate::types::User {
        let email = Email::new(format!("user{tag}@example.com")).unwrap();
        db.create_user(email, "pw123456", None, None).await.unwrap()
    }

    #[tokio::test]
    async fn user_cursor_encode_decode_roundtrip() {
        let ath = setup().await;
        let db = ath.db();
        let user = make_user(db, 1).await;
        let entries = db.list_users_paginated(10, None).await.unwrap();
        assert_eq!(entries.len(), 1);
        let cursor = UserCursor::from_entry(&entries[0]);
        let encoded = cursor.encode();
        let decoded = UserCursor::decode(&encoded).unwrap();
        assert_eq!(decoded.id, user.id);
    }

    #[tokio::test]
    async fn list_users_paginated_returns_first_page() {
        let ath = setup().await;
        let db = ath.db();
        for i in 0..5 {
            make_user(db, i).await;
        }
        let page = db.list_users_paginated(3, None).await.unwrap();
        assert_eq!(page.len(), 3);
    }

    #[tokio::test]
    async fn set_email_verified_toggles_flag() {
        let ath = setup().await;
        let db = ath.db();
        let user = make_user(db, 99).await;
        assert!(!user.email_verified);

        db.set_email_verified(user.id, true).await.unwrap();
        let after = db.get_user(user.id).await.unwrap();
        assert!(after.email_verified);

        db.set_email_verified(user.id, false).await.unwrap();
        let after = db.get_user(user.id).await.unwrap();
        assert!(!after.email_verified);
    }

    #[tokio::test]
    async fn set_email_verified_unknown_id_returns_not_found() {
        let ath = setup().await;
        let db = ath.db();
        let err = db
            .set_email_verified(UserId::new(), true)
            .await
            .unwrap_err();
        assert!(matches!(err, AuthError::NotFound));
    }

    #[tokio::test]
    async fn list_users_paginated_cursor_advances() {
        let ath = setup().await;
        let db = ath.db();
        for i in 0..5 {
            make_user(db, i + 10).await;
        }
        let page1 = db.list_users_paginated(3, None).await.unwrap();
        assert_eq!(page1.len(), 3);
        let cursor = UserCursor::from_entry(page1.last().unwrap());
        let page2 = db.list_users_paginated(3, Some(&cursor)).await.unwrap();
        assert_eq!(page2.len(), 2);
        assert!(!page2.iter().any(|u| page1.iter().any(|v| v.id == u.id)));
    }

    fn unfiltered(limit: u32) -> SearchUsersParams<'static> {
        SearchUsersParams {
            query: None,
            is_active: None,
            has_mfa: None,
            email_verified: None,
            limit,
            offset: 0,
        }
    }

    #[tokio::test]
    async fn search_users_filter_email_verified_true() {
        let ath = setup().await;
        let db = ath.db();
        let u1 = make_user(db, 1).await;
        let _u2 = make_user(db, 2).await;
        db.set_email_verified(u1.id, true).await.unwrap();

        let result = db
            .search_users(SearchUsersParams {
                email_verified: Some(true),
                ..unfiltered(10)
            })
            .await
            .unwrap();
        assert_eq!(result.total, 1);
        assert_eq!(result.users.len(), 1);
        assert_eq!(result.users[0].id, u1.id);
    }

    #[tokio::test]
    async fn search_users_filter_email_verified_false() {
        let ath = setup().await;
        let db = ath.db();
        let u1 = make_user(db, 1).await;
        let u2 = make_user(db, 2).await;
        db.set_email_verified(u1.id, true).await.unwrap();

        let result = db
            .search_users(SearchUsersParams {
                email_verified: Some(false),
                ..unfiltered(10)
            })
            .await
            .unwrap();
        assert_eq!(result.total, 1);
        assert_eq!(result.users[0].id, u2.id);
    }

    #[tokio::test]
    async fn search_users_filter_email_verified_none_includes_both() {
        let ath = setup().await;
        let db = ath.db();
        let u1 = make_user(db, 1).await;
        let _u2 = make_user(db, 2).await;
        db.set_email_verified(u1.id, true).await.unwrap();

        let result = db.search_users(unfiltered(10)).await.unwrap();
        assert_eq!(result.total, 2);
        assert_eq!(result.users.len(), 2);
    }

    // count_users tests (99c.6 Step 2)

    #[tokio::test]
    async fn count_users_zero_on_empty_db() {
        let ath = setup().await;
        let n = ath.db().count_users().await.expect("count_users");
        assert_eq!(n, 0);
    }

    #[tokio::test]
    async fn count_users_after_create() {
        let ath = setup().await;
        let db = ath.db();
        make_user(db, 1).await;
        make_user(db, 2).await;
        make_user(db, 3).await;
        let n = db.count_users().await.expect("count_users");
        assert_eq!(n, 3);
    }
}