Skip to main content

rustio_admin/auth/
users.rs

1//! User records, password hashing, and the login flow.
2
3use argon2::password_hash::{
4    rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString,
5};
6use argon2::Argon2;
7use chrono::{DateTime, Utc};
8use sqlx::Row as SqlxRow;
9
10use crate::error::{Error, Result};
11use crate::orm::{Db, Row};
12
13use super::role::Role;
14use super::sessions::create_session;
15
16/// The identity attached to a request by the auth middleware. Kept
17/// cheap to clone because we pass it into handler bodies.
18#[derive(Debug, Clone)]
19pub struct Identity {
20    pub user_id: i64,
21    pub email: String,
22    pub role: Role,
23    pub is_active: bool,
24    /// Whether this user was seeded by a demo-fixture flow. Drives the
25    /// red banner in the admin UI; remains FALSE for users created via
26    /// the normal `create_user` path.
27    pub is_demo: bool,
28    pub demo_label: Option<String>,
29}
30
31impl Identity {
32    /// Administrator-or-higher (Administrator, Developer).
33    pub fn is_admin(&self) -> bool {
34        self.is_active && self.role.includes(Role::Administrator)
35    }
36
37    /// Anyone allowed into the admin panel (Staff and above).
38    pub fn can_access_admin(&self) -> bool {
39        self.is_active && self.role.can_access_panel()
40    }
41}
42
43pub struct StoredUser {
44    pub id: i64,
45    pub email: String,
46    pub password_hash: String,
47    pub role: Role,
48    pub is_active: bool,
49    pub is_demo: bool,
50    pub demo_label: Option<String>,
51}
52
53/// Read-only view of a user, used by the built-in admin profile page.
54/// Excludes `password_hash` deliberately. Construct via
55/// [`load_user_profile`].
56#[derive(Debug, Clone)]
57pub struct UserProfile {
58    pub id: i64,
59    pub email: String,
60    pub role: Role,
61    pub is_active: bool,
62    pub created_at: DateTime<Utc>,
63    pub full_name: Option<String>,
64    pub locale: Option<String>,
65    pub timezone: Option<String>,
66    pub is_demo: bool,
67    pub demo_label: Option<String>,
68}
69
70pub async fn init_user_tables(db: &Db) -> Result<()> {
71    sqlx::query(
72        "CREATE TABLE IF NOT EXISTS rustio_users (
73            id            BIGSERIAL PRIMARY KEY,
74            email         TEXT NOT NULL UNIQUE,
75            password_hash TEXT NOT NULL,
76            role          TEXT NOT NULL DEFAULT 'user',
77            is_active     BOOLEAN NOT NULL DEFAULT TRUE,
78            created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
79            updated_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
80        )",
81    )
82    .execute(db.pool())
83    .await?;
84
85    sqlx::query("CREATE INDEX IF NOT EXISTS rustio_users_email_idx ON rustio_users (email)")
86        .execute(db.pool())
87        .await?;
88
89    Ok(())
90}
91
92/// Idempotent schema upgrade for the 5-tier role hierarchy + demo + profile
93/// columns. Safe to call repeatedly; safe on a fresh DB and on a legacy
94/// `'admin'`-roled DB.
95///
96/// Order is load-bearing:
97/// 1. Rename existing `'admin'` rows to `'administrator'` BEFORE the CHECK
98///    constraint is added, otherwise the constraint would reject the row.
99/// 2. Add the demo columns idempotently.
100/// 3. Add the CHECK constraint conditionally (PG has no `IF NOT EXISTS`
101///    for CHECK constraints, so we guard via `pg_constraint`).
102/// 4. Add the indexes.
103/// 5. Add the profile-display columns.
104pub async fn migrate_user_schema(db: &Db) -> Result<()> {
105    sqlx::query("UPDATE rustio_users SET role = 'administrator' WHERE role = 'admin'")
106        .execute(db.pool())
107        .await?;
108
109    sqlx::query(
110        "ALTER TABLE rustio_users \
111         ADD COLUMN IF NOT EXISTS is_demo BOOLEAN NOT NULL DEFAULT FALSE",
112    )
113    .execute(db.pool())
114    .await?;
115    sqlx::query("ALTER TABLE rustio_users ADD COLUMN IF NOT EXISTS demo_label TEXT")
116        .execute(db.pool())
117        .await?;
118
119    sqlx::query(
120        "DO $$
121         BEGIN
122            IF NOT EXISTS (
123                SELECT 1 FROM pg_constraint WHERE conname = 'rustio_users_role_check'
124            ) THEN
125                ALTER TABLE rustio_users
126                ADD CONSTRAINT rustio_users_role_check
127                CHECK (role IN ('user','staff','supervisor','administrator','developer'));
128            END IF;
129         END $$",
130    )
131    .execute(db.pool())
132    .await?;
133
134    sqlx::query("CREATE INDEX IF NOT EXISTS rustio_users_role_idx ON rustio_users(role)")
135        .execute(db.pool())
136        .await?;
137    sqlx::query(
138        "CREATE INDEX IF NOT EXISTS rustio_users_is_demo_idx \
139         ON rustio_users(is_demo) WHERE is_demo = TRUE",
140    )
141    .execute(db.pool())
142    .await?;
143
144    sqlx::query("ALTER TABLE rustio_users ADD COLUMN IF NOT EXISTS full_name TEXT")
145        .execute(db.pool())
146        .await?;
147    sqlx::query("ALTER TABLE rustio_users ADD COLUMN IF NOT EXISTS locale TEXT")
148        .execute(db.pool())
149        .await?;
150    sqlx::query("ALTER TABLE rustio_users ADD COLUMN IF NOT EXISTS timezone TEXT")
151        .execute(db.pool())
152        .await?;
153
154    Ok(())
155}
156
157pub fn hash_password(plain: &str) -> Result<String> {
158    let salt = SaltString::generate(&mut OsRng);
159    Argon2::default()
160        .hash_password(plain.as_bytes(), &salt)
161        .map(|h| h.to_string())
162        .map_err(|e| Error::Internal(format!("password hashing: {e}")))
163}
164
165pub fn verify_password(plain: &str, stored_hash: &str) -> bool {
166    match PasswordHash::new(stored_hash) {
167        Ok(parsed) => Argon2::default()
168            .verify_password(plain.as_bytes(), &parsed)
169            .is_ok(),
170        Err(_) => false,
171    }
172}
173
174pub async fn create_user(db: &Db, email: &str, password: &str, role: Role) -> Result<i64> {
175    let hash = hash_password(password)?;
176    let row = sqlx::query(
177        "INSERT INTO rustio_users (email, password_hash, role)
178         VALUES ($1, $2, $3)
179         RETURNING id",
180    )
181    .bind(email)
182    .bind(&hash)
183    .bind(role.as_str())
184    .fetch_one(db.pool())
185    .await
186    .map_err(|e| {
187        // Keep Postgres internals out of the client response. The full
188        // error stays in the operator's log; the user sees a clean,
189        // generic message — except the unique-email collision, which
190        // is worth surfacing because it's actionable.
191        log::warn!("create_user failed for {email}: {e}");
192        let detail = e.to_string();
193        if detail.contains("rustio_users_email_key") {
194            Error::BadRequest("An account with this email already exists.".into())
195        } else {
196            Error::BadRequest("Could not create user. Please check your input.".into())
197        }
198    })?;
199    let id: i64 = row
200        .try_get("id")
201        .map_err(|e| Error::Internal(format!("returning id: {e}")))?;
202    Ok(id)
203}
204
205pub async fn find_user_by_email(db: &Db, email: &str) -> Result<Option<StoredUser>> {
206    let row = sqlx::query(
207        "SELECT id, email, password_hash, role, is_active, is_demo, demo_label
208           FROM rustio_users
209          WHERE email = $1",
210    )
211    .bind(email)
212    .fetch_optional(db.pool())
213    .await?;
214    match row {
215        Some(r) => {
216            let r = Row::from_pg(&r);
217            Ok(Some(StoredUser {
218                id: r.get_i64("id")?,
219                email: r.get_string("email")?,
220                password_hash: r.get_string("password_hash")?,
221                role: Role::parse(&r.get_string("role")?)?,
222                is_active: r.get_bool("is_active")?,
223                is_demo: r.get_bool("is_demo")?,
224                demo_label: r.get_optional_string("demo_label")?,
225            }))
226        }
227        None => Ok(None),
228    }
229}
230
231/// Load a user by id for display purposes. Returns `Ok(None)` for a
232/// missing id (callers map to 404). Returns `Err` only on a real DB
233/// failure or a corrupted role string. Never reads `password_hash`.
234pub async fn load_user_profile(db: &Db, user_id: i64) -> Result<Option<UserProfile>> {
235    let row = sqlx::query(
236        "SELECT id, email, role, is_active, created_at,
237                full_name, locale, timezone, is_demo, demo_label
238           FROM rustio_users
239          WHERE id = $1",
240    )
241    .bind(user_id)
242    .fetch_optional(db.pool())
243    .await?;
244    match row {
245        Some(r) => {
246            let r = Row::from_pg(&r);
247            Ok(Some(UserProfile {
248                id: r.get_i64("id")?,
249                email: r.get_string("email")?,
250                role: Role::parse(&r.get_string("role")?)?,
251                is_active: r.get_bool("is_active")?,
252                created_at: r.get_datetime("created_at")?,
253                full_name: r.get_optional_string("full_name")?,
254                locale: r.get_optional_string("locale")?,
255                timezone: r.get_optional_string("timezone")?,
256                is_demo: r.get_bool("is_demo")?,
257                demo_label: r.get_optional_string("demo_label")?,
258            }))
259        }
260        None => Ok(None),
261    }
262}
263
264pub async fn set_password(db: &Db, user_id: i64, new_password: &str) -> Result<()> {
265    let hash = hash_password(new_password)?;
266    sqlx::query("UPDATE rustio_users SET password_hash = $1, updated_at = $2 WHERE id = $3")
267        .bind(&hash)
268        .bind(Utc::now())
269        .bind(user_id)
270        .execute(db.pool())
271        .await?;
272    Ok(())
273}
274
275pub async fn update_user_role(db: &Db, user_id: i64, role: Role) -> Result<()> {
276    sqlx::query("UPDATE rustio_users SET role = $1, updated_at = $2 WHERE id = $3")
277        .bind(role.as_str())
278        .bind(Utc::now())
279        .bind(user_id)
280        .execute(db.pool())
281        .await?;
282    Ok(())
283}
284
285/// Pure verdict for the orphan check, factored out so it can be
286/// unit-tested without a `Db`. The async wrapper [`would_orphan_role`]
287/// supplies `active_count` and `target_is_protected` from SQL.
288///
289/// Returns `true` only when removing this user from the protected
290/// pool would empty it (count == 1 and the target user IS in that
291/// pool, AND the proposed new state would no longer satisfy
292/// membership).
293pub fn verdict_for_orphan_role(
294    active_count_in_protected: i64,
295    target_is_in_protected: bool,
296    new_role_is_protected: bool,
297    new_active: bool,
298) -> bool {
299    if !target_is_in_protected {
300        return false;
301    }
302    if active_count_in_protected != 1 {
303        return false;
304    }
305    // The target IS the only active member. Block unless the proposed
306    // state keeps them in the same protected role and active.
307    !(new_active && new_role_is_protected)
308}
309
310/// Would the proposed change leave the system with zero active members
311/// of `protected_role`?
312///
313/// `new_role` / `new_active` describe the target row's proposed state:
314/// - delete: pass `new_active = false` (the row goes away).
315/// - role change: pass the new role.
316/// - deactivate: pass `new_active = false`.
317///
318/// Returns `true` only when:
319/// - exactly one active member of `protected_role` exists, AND
320/// - the target user IS that member, AND
321/// - the proposed state would remove them from the protected pool.
322pub async fn would_orphan_role(
323    db: &Db,
324    user_id: i64,
325    protected_role: Role,
326    new_role: Role,
327    new_active: bool,
328) -> Result<bool> {
329    let active_count: i64 = sqlx::query_scalar(
330        "SELECT COUNT(*) FROM rustio_users WHERE role = $1 AND is_active = TRUE",
331    )
332    .bind(protected_role.as_str())
333    .fetch_one(db.pool())
334    .await?;
335
336    let target_role_str: Option<String> =
337        sqlx::query_scalar("SELECT role FROM rustio_users WHERE id = $1 AND is_active = TRUE")
338            .bind(user_id)
339            .fetch_optional(db.pool())
340            .await?;
341    let target_is_in_protected = target_role_str.as_deref() == Some(protected_role.as_str());
342
343    Ok(verdict_for_orphan_role(
344        active_count,
345        target_is_in_protected,
346        new_role == protected_role,
347        new_active,
348    ))
349}
350
351/// Walk every entry in [`super::role::protected_roles`] and return
352/// the first protected role whose membership would be orphaned by
353/// the proposed change. `None` means the change is safe.
354pub async fn would_orphan_protected(
355    db: &Db,
356    user_id: i64,
357    new_role: Role,
358    new_active: bool,
359) -> Result<Option<Role>> {
360    for &role in super::role::protected_roles() {
361        if would_orphan_role(db, user_id, role, new_role, new_active).await? {
362            return Ok(Some(role));
363        }
364    }
365    Ok(None)
366}
367
368/// Legacy alias preserved so external callers keep compiling. Prefer
369/// [`would_orphan_protected`] which generalises across every role in
370/// [`super::role::protected_roles`].
371#[deprecated(
372    since = "0.3.0",
373    note = "use `would_orphan_protected` to cover every protected role, not just Developer"
374)]
375pub async fn would_orphan_developers(
376    db: &Db,
377    user_id: i64,
378    new_role: Option<Role>,
379) -> Result<bool> {
380    let (role, active) = match new_role {
381        Some(r) => (r, true),
382        None => (Role::User, false),
383    };
384    would_orphan_role(db, user_id, Role::Developer, role, active).await
385}
386
387/// Verify credentials and create a session. Returns the session token
388/// to set in the cookie. A deliberately vague error on failure — we
389/// don't want to leak whether the email was valid.
390pub async fn login(db: &Db, email: &str, password: &str) -> Result<String> {
391    let user = find_user_by_email(db, email)
392        .await?
393        .ok_or_else(|| Error::Unauthorized("invalid email or password".into()))?;
394    if !user.is_active {
395        return Err(Error::Forbidden("account disabled".into()));
396    }
397    if !verify_password(password, &user.password_hash) {
398        return Err(Error::Unauthorized("invalid email or password".into()));
399    }
400    create_session(db, user.id).await
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    #[test]
408    fn user_profile_derives_debug_and_clone() {
409        fn assert_traits<T: std::fmt::Debug + Clone>() {}
410        assert_traits::<UserProfile>();
411    }
412
413    #[test]
414    fn password_round_trip() {
415        let h = hash_password("secret").unwrap();
416        assert!(verify_password("secret", &h));
417        assert!(!verify_password("wrong", &h));
418    }
419
420    // ---- verdict_for_orphan_role ----
421
422    #[test]
423    fn verdict_safe_when_target_not_in_protected_pool() {
424        // Target is Staff; we're checking Administrator orphan-ness.
425        // Even if active_count == 0 the change is irrelevant to that pool.
426        assert!(!verdict_for_orphan_role(0, false, false, true));
427        assert!(!verdict_for_orphan_role(1, false, false, false));
428        assert!(!verdict_for_orphan_role(5, false, true, true));
429    }
430
431    #[test]
432    fn verdict_safe_when_more_than_one_member() {
433        // Target IS the protected role, but there's a second active
434        // member — losing this one keeps the floor satisfied.
435        assert!(!verdict_for_orphan_role(2, true, false, true));
436        assert!(!verdict_for_orphan_role(5, true, false, false));
437    }
438
439    #[test]
440    fn verdict_blocks_when_last_member_demoting() {
441        // active_count = 1, target IS that member, new state drops
442        // them out of the pool → block.
443        assert!(verdict_for_orphan_role(1, true, false, true));
444    }
445
446    #[test]
447    fn verdict_blocks_when_last_member_deactivating() {
448        // Same shape but new_active = false; new_role doesn't matter.
449        assert!(verdict_for_orphan_role(1, true, true, false));
450    }
451
452    #[test]
453    fn verdict_blocks_when_last_member_deleting() {
454        // Delete is modelled as new_active = false in the wrapper.
455        assert!(verdict_for_orphan_role(1, true, false, false));
456    }
457
458    #[test]
459    fn verdict_safe_when_last_member_keeps_role() {
460        // No-op save: still in pool, still active → safe.
461        assert!(!verdict_for_orphan_role(1, true, true, true));
462    }
463}