1use 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#[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 pub is_demo: bool,
28 pub demo_label: Option<String>,
29}
30
31impl Identity {
32 pub fn is_admin(&self) -> bool {
34 self.is_active && self.role.includes(Role::Administrator)
35 }
36
37 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#[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
92pub 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 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
231pub 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
285pub 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 !(new_active && new_role_is_protected)
308}
309
310pub 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
351pub 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#[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
387pub 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 #[test]
423 fn verdict_safe_when_target_not_in_protected_pool() {
424 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 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 assert!(verdict_for_orphan_role(1, true, false, true));
444 }
445
446 #[test]
447 fn verdict_blocks_when_last_member_deactivating() {
448 assert!(verdict_for_orphan_role(1, true, true, false));
450 }
451
452 #[test]
453 fn verdict_blocks_when_last_member_deleting() {
454 assert!(verdict_for_orphan_role(1, true, false, false));
456 }
457
458 #[test]
459 fn verdict_safe_when_last_member_keeps_role() {
460 assert!(!verdict_for_orphan_role(1, true, true, true));
462 }
463}