diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index 7b2a72c..83bc5cf 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -228,6 +228,12 @@ pub async fn create_invite( invited_by: Option, admin: bool, ) -> std::result::Result { + // Inviting an address that already has an account is refused here, not + // at acceptance time — the admin learns immediately, and the account is + // never shadowed by a pending invite. + if user_by_email(store, email).await?.is_some() { + return Err(AccountError::EmailTaken); + } let token = Token::mint(); let now = store::now(); let expires = now + time::Duration::days(INVITE_DAYS); @@ -479,6 +485,20 @@ pub async fn set_disabled(store: &Store, user: &UserId, disabled: bool) -> Resul Ok(()) } +/// Grants or revokes im's admin flag. Never crosses a token — this is im's +/// own panel, not a claim apps ever see. +pub async fn set_admin(store: &Store, user: &UserId, admin: bool) -> Result<()> { + store + .conn + .execute( + "UPDATE users SET admin = ?1 WHERE id = ?2", + turso::params![admin as i64, user.to_string()], + ) + .await + .map_err(backend)?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -488,6 +508,30 @@ mod tests { } use std::path::Path; + #[tokio::test] + async fn invite_refuses_existing_account_and_admin_toggles() { + let store = fixture().await; + let invite = create_invite(&store, "ann@example.com", None, false) + .await + .unwrap(); + let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") + .await + .unwrap(); + assert!(!user.admin); + + // Inviting an address that already has an account is refused at + // creation, not at acceptance. + assert!(matches!( + create_invite(&store, "ann@example.com", None, false).await, + Err(AccountError::EmailTaken) + )); + + set_admin(&store, &user.id, true).await.unwrap(); + let promoted = user_by_id(&store, &user.id).await.unwrap().unwrap(); + assert!(promoted.admin); + set_admin(&store, &user.id, false).await.unwrap(); + assert!(!user_by_id(&store, &user.id).await.unwrap().unwrap().admin); + } #[test] fn password_roundtrip() { @@ -563,11 +607,10 @@ mod tests { create_user_from_invite(&store, first.expose(), "Ann", "tDLr9!mZQ2xv") .await .unwrap(); - let second = create_invite(&store, "ann@example.com", None, false) - .await - .unwrap(); + // The second invite never exists: the refusal moved from acceptance + // time to creation time. assert!(matches!( - create_user_from_invite(&store, second.expose(), "Ann Two", "tDLr9!mZQ2xv").await, + create_invite(&store, "ann@example.com", None, false).await, Err(AccountError::EmailTaken) )); } diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 6c73337..fafabfc 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -275,9 +275,13 @@ async fn invite(cx: &Cx, Form(input): Form) -> Result { let store = &app(cx).store; let email = input.email.trim().to_string(); let admin = input.admin.as_deref() == Some("yes"); - let token = accounts::create_invite(store, &email, Some(me.id.clone()), admin) - .await - .map_err(|e| topcoat::Error::from(std::io::Error::other(e.to_string())))?; + let token = match accounts::create_invite(store, &email, Some(me.id.clone()), admin).await { + Ok(token) => token, + Err(accounts::AccountError::EmailTaken) => { + return back(cx, "users", "&error=email_taken"); + } + Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), + }; // Mailed when a sender is configured; shown once on the page otherwise. let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose()) .await diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 39f6510..8ab6100 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -77,15 +77,58 @@ async fn main() { } create_client(config, name, uris).await; } + Some("promote") => { + let Some(email) = args.get(2) else { + eprintln!("usage: im-web promote "); + std::process::exit(2); + }; + set_admin_cli(config, email, true).await; + } + Some("demote") => { + let Some(email) = args.get(2) else { + eprintln!("usage: im-web demote "); + std::process::exit(2); + }; + set_admin_cli(config, email, false).await; + } Some(other) => { eprintln!( - "im: unknown command {other:?} (expected: invite, revoke, create-client, or none to serve)" + "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, or none to serve)" ); std::process::exit(2); } } } +/// `im-web promote|demote `: the admin flag for an account that +/// already exists — the migration path's way in, since invites refuse +/// addresses with accounts. +async fn set_admin_cli(config: Config, email: &str, admin: bool) { + let store = open_store(&config).await; + let Some(user) = im_core::accounts::user_by_email(&store, email) + .await + .expect("failed to read users") + else { + eprintln!("im: no account for {email}"); + std::process::exit(1); + }; + im_core::accounts::set_admin(&store, &user.id, admin) + .await + .expect("failed to update"); + im_core::events::log( + &store, + if admin { + "user_promoted" + } else { + "user_demoted" + }, + Some("cli"), + Some(email), + ) + .await; + println!("im {email}: admin = {admin}"); +} + async fn open_store(config: &Config) -> Arc { Arc::new( Store::open(&config.database) @@ -101,9 +144,16 @@ async fn open_store(config: &Config) -> Arc { /// process would hold the same file. async fn invite(config: Config, email: &str, admin: bool) { let store = open_store(&config).await; - let token = im_core::accounts::create_invite(&store, email, None, admin) - .await - .expect("failed to create the invite"); + let token = match im_core::accounts::create_invite(&store, email, None, admin).await { + Ok(token) => token, + Err(im_core::accounts::AccountError::EmailTaken) => { + eprintln!( + "im: {email} already has an account — `im-web promote {email}` if you mean admin" + ); + std::process::exit(1); + } + Err(e) => panic!("failed to create the invite: {e}"), + }; im_core::events::log( &store, "invite_created",