forge
Explore
Log in

Don't you dare go Hollow

Promote/demote CLI for migrated users

Browse files at this commit

bfb4aaf8d796573d454c947512da12f4c6a23f33Ahmet Kaan GümüşParent: f675a3d
  • feat
    • promote/demote CLI for migrated users
    • invites refuse existing accounts
Show full message
feat: promote/demote CLI for migrated users; invites refuse existing accounts

- im-web promote|demote <email>: the admin flag for accounts that already
  exist — the migration path's way in, since nobody migrated is admin
- create_invite refuses an address with an account at creation time (was:
  failed at acceptance); the panel shows email_taken, the CLI says to use
  promote instead

Verified: full workspace suite (34 tests) green.
crates/im-core/src/accounts.rsmodified+47 -4
@@ -228,6 +228,12 @@ pub async fn create_invite(
228228 invited_by: Option<UserId>,
229229 admin: bool,
230230 ) -> std::result::Result<Token, AccountError> {
231+ // Inviting an address that already has an account is refused here, not
232+ // at acceptance time — the admin learns immediately, and the account is
233+ // never shadowed by a pending invite.
234+ if user_by_email(store, email).await?.is_some() {
235+ return Err(AccountError::EmailTaken);
236+ }
231237 let token = Token::mint();
232238 let now = store::now();
233239 let expires = now + time::Duration::days(INVITE_DAYS);
@@ -479,6 +485,20 @@ pub async fn set_disabled(store: &Store, user: &UserId, disabled: bool) -> Resul
479485 Ok(())
480486 }
481487
488+/// Grants or revokes im's admin flag. Never crosses a token — this is im's
489+/// own panel, not a claim apps ever see.
490+pub async fn set_admin(store: &Store, user: &UserId, admin: bool) -> Result<()> {
491+ store
492+ .conn
493+ .execute(
494+ "UPDATE users SET admin = ?1 WHERE id = ?2",
495+ turso::params![admin as i64, user.to_string()],
496+ )
497+ .await
498+ .map_err(backend)?;
499+ Ok(())
500+}
501+
482502 #[cfg(test)]
483503 mod tests {
484504 use super::*;
@@ -488,6 +508,30 @@ mod tests {
488508 }
489509
490510 use std::path::Path;
511+ #[tokio::test]
512+ async fn invite_refuses_existing_account_and_admin_toggles() {
513+ let store = fixture().await;
514+ let invite = create_invite(&store, "ann@example.com", None, false)
515+ .await
516+ .unwrap();
517+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
518+ .await
519+ .unwrap();
520+ assert!(!user.admin);
521+
522+ // Inviting an address that already has an account is refused at
523+ // creation, not at acceptance.
524+ assert!(matches!(
525+ create_invite(&store, "ann@example.com", None, false).await,
526+ Err(AccountError::EmailTaken)
527+ ));
528+
529+ set_admin(&store, &user.id, true).await.unwrap();
530+ let promoted = user_by_id(&store, &user.id).await.unwrap().unwrap();
531+ assert!(promoted.admin);
532+ set_admin(&store, &user.id, false).await.unwrap();
533+ assert!(!user_by_id(&store, &user.id).await.unwrap().unwrap().admin);
534+ }
491535
492536 #[test]
493537 fn password_roundtrip() {
@@ -563,11 +607,10 @@ mod tests {
563607 create_user_from_invite(&store, first.expose(), "Ann", "tDLr9!mZQ2xv")
564608 .await
565609 .unwrap();
566- let second = create_invite(&store, "ann@example.com", None, false)
567- .await
568- .unwrap();
610+ // The second invite never exists: the refusal moved from acceptance
611+ // time to creation time.
569612 assert!(matches!(
570- create_user_from_invite(&store, second.expose(), "Ann Two", "tDLr9!mZQ2xv").await,
613+ create_invite(&store, "ann@example.com", None, false).await,
571614 Err(AccountError::EmailTaken)
572615 ));
573616 }
crates/im-web/src/admin.rsmodified+7 -3
@@ -275,9 +275,13 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> {
275275 let store = &app(cx).store;
276276 let email = input.email.trim().to_string();
277277 let admin = input.admin.as_deref() == Some("yes");
278- let token = accounts::create_invite(store, &email, Some(me.id.clone()), admin)
279- .await
280- .map_err(|e| topcoat::Error::from(std::io::Error::other(e.to_string())))?;
278+ let token = match accounts::create_invite(store, &email, Some(me.id.clone()), admin).await {
279+ Ok(token) => token,
280+ Err(accounts::AccountError::EmailTaken) => {
281+ return back(cx, "users", "&error=email_taken");
282+ }
283+ Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
284+ };
281285 // Mailed when a sender is configured; shown once on the page otherwise.
282286 let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose())
283287 .await
crates/im-web/src/main.rsmodified+54 -4
@@ -77,15 +77,58 @@ async fn main() {
7777 }
7878 create_client(config, name, uris).await;
7979 }
80+ Some("promote") => {
81+ let Some(email) = args.get(2) else {
82+ eprintln!("usage: im-web promote <email>");
83+ std::process::exit(2);
84+ };
85+ set_admin_cli(config, email, true).await;
86+ }
87+ Some("demote") => {
88+ let Some(email) = args.get(2) else {
89+ eprintln!("usage: im-web demote <email>");
90+ std::process::exit(2);
91+ };
92+ set_admin_cli(config, email, false).await;
93+ }
8094 Some(other) => {
8195 eprintln!(
82- "im: unknown command {other:?} (expected: invite, revoke, create-client, or none to serve)"
96+ "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, or none to serve)"
8397 );
8498 std::process::exit(2);
8599 }
86100 }
87101 }
88102
103+/// `im-web promote|demote <email>`: the admin flag for an account that
104+/// already exists — the migration path's way in, since invites refuse
105+/// addresses with accounts.
106+async fn set_admin_cli(config: Config, email: &str, admin: bool) {
107+ let store = open_store(&config).await;
108+ let Some(user) = im_core::accounts::user_by_email(&store, email)
109+ .await
110+ .expect("failed to read users")
111+ else {
112+ eprintln!("im: no account for {email}");
113+ std::process::exit(1);
114+ };
115+ im_core::accounts::set_admin(&store, &user.id, admin)
116+ .await
117+ .expect("failed to update");
118+ im_core::events::log(
119+ &store,
120+ if admin {
121+ "user_promoted"
122+ } else {
123+ "user_demoted"
124+ },
125+ Some("cli"),
126+ Some(email),
127+ )
128+ .await;
129+ println!("im {email}: admin = {admin}");
130+}
131+
89132 async fn open_store(config: &Config) -> Arc<Store> {
90133 Arc::new(
91134 Store::open(&config.database)
@@ -101,9 +144,16 @@ async fn open_store(config: &Config) -> Arc<Store> {
101144 /// process would hold the same file.
102145 async fn invite(config: Config, email: &str, admin: bool) {
103146 let store = open_store(&config).await;
104- let token = im_core::accounts::create_invite(&store, email, None, admin)
105- .await
106- .expect("failed to create the invite");
147+ let token = match im_core::accounts::create_invite(&store, email, None, admin).await {
148+ Ok(token) => token,
149+ Err(im_core::accounts::AccountError::EmailTaken) => {
150+ eprintln!(
151+ "im: {email} already has an account — `im-web promote {email}` if you mean admin"
152+ );
153+ std::process::exit(1);
154+ }
155+ Err(e) => panic!("failed to create the invite: {e}"),
156+ };
107157 im_core::events::log(
108158 &store,
109159 "invite_created",