From 17044ad4f0c2a8ea34b5757457a9c0947f496c84 Mon Sep 17 00:00:00 2001 From: Fu Zi Xiang Date: Tue, 7 Nov 2023 00:32:28 +0800 Subject: [PATCH] feat: indempotency restart for email autoconfirm and non autoconfirm --- libs/gotrue-entity/src/dto.rs | 2 +- src/application.rs | 62 ++++++++++++++++++++--------------- 2 files changed, 37 insertions(+), 27 deletions(-) diff --git a/libs/gotrue-entity/src/dto.rs b/libs/gotrue-entity/src/dto.rs index 319e0d96..89d9992f 100644 --- a/libs/gotrue-entity/src/dto.rs +++ b/libs/gotrue-entity/src/dto.rs @@ -197,7 +197,7 @@ impl OAuthProvider { pub struct OAuthURL { pub url: String, } -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] pub enum SignUpResponse { Authenticated(GotrueTokenResponse), diff --git a/src/application.rs b/src/application.rs index 1c7ad25c..a915611c 100644 --- a/src/application.rs +++ b/src/application.rs @@ -215,33 +215,9 @@ async fn setup_admin_account( let password = gotrue_setting.admin_password.as_str(); let res_resp = gotrue_client.sign_up(admin_email, password).await; - match res_resp { - Ok(resp) => match resp { - gotrue_entity::dto::SignUpResponse::Authenticated(resp) => { - tracing::info!( - "Admin user already created and authenticated at {:?}", - resp.user.email_confirmed_at - ); - Ok(()) - }, - gotrue_entity::dto::SignUpResponse::NotAuthenticated(user) => { - let user_id = user.id.parse::().unwrap(); - let result = sqlx::query( - r#" - UPDATE auth.users - SET role = 'supabase_admin', email_confirmed_at = NOW() - WHERE id = $1 - "#, - ) - .bind(user_id) - .execute(pg_pool) - .await - .context("failed to update the admin user")?; + println!("res_resp: {:?}", &res_resp); - assert_eq!(result.rows_affected(), 1); - Ok(()) - }, - }, + match res_resp { Err(err) => { if let app_error::gotrue::GoTrueError::Internal(err) = err { match (err.code, err.msg.as_str()) { @@ -255,6 +231,40 @@ async fn setup_admin_account( Err(err.into()) } }, + Ok(resp) => match resp { + gotrue_entity::dto::SignUpResponse::Authenticated(resp) => { + tracing::info!( + "Admin user already created and authenticated at {:?}", + resp.user.email_confirmed_at + ); + Ok(()) + }, + gotrue_entity::dto::SignUpResponse::NotAuthenticated(user) => match user.role.as_str() { + "supabase_admin" => { + tracing::info!("Admin user already created and set role to supabase_admin"); + Ok(()) + }, + _ => { + let user_id = user.id.parse::().unwrap(); + let result = sqlx::query( + r#" + UPDATE auth.users + SET role = 'supabase_admin', email_confirmed_at = NOW() + WHERE id = $1 + "#, + ) + .bind(user_id) + .execute(pg_pool) + .await + .context("failed to update the admin user")?; + + assert_eq!(result.rows_affected(), 1); + tracing::info!("Admin user created and set role to supabase_admin"); + + Ok(()) + }, + }, + }, } }