diff --git a/src/api/v1/auth.rs b/src/api/v1/auth.rs index 6689b1bf..6939b2fe 100644 --- a/src/api/v1/auth.rs +++ b/src/api/v1/auth.rs @@ -142,6 +142,44 @@ pub async fn get_secret(id: Identity, data: web::Data) -> ServiceResult, +) -> ServiceResult { + is_authenticated(&id)?; + + let username = id.identity().unwrap(); + + let mut secret; + + loop { + secret = get_random(32); + let res = sqlx::query!( + "UPDATE mcaptcha_users set secret = $1 + WHERE name = $2", + &secret, + &username, + ) + .execute(&data.db) + .await; + if res.is_ok() { + break; + } else { + if let Err(sqlx::Error::Database(err)) = res { + if err.code() == Some(Cow::from("23505")) + && err.message().contains("mcaptcha_users_secret_key") + { + continue; + } else { + Err(sqlx::Error::Database(err))?; + } + }; + } + } + Ok(HttpResponse::Ok()) +} + #[post("/api/v1/signout")] pub async fn signout(id: Identity) -> impl Responder { if let Some(_) = id.identity() { diff --git a/src/api/v1/mod.rs b/src/api/v1/mod.rs index dd9bb1a3..314778d5 100644 --- a/src/api/v1/mod.rs +++ b/src/api/v1/mod.rs @@ -34,6 +34,7 @@ pub fn services(cfg: &mut ServiceConfig) { cfg.service(auth::username_exists); cfg.service(auth::email_exists); cfg.service(auth::get_secret); + cfg.service(auth::update_user_secret); // mcaptcha cfg.service(mcaptcha::mcaptcha::add_mcaptcha); diff --git a/src/api/v1/tests/auth.rs b/src/api/v1/tests/auth.rs index a2bc4f22..42ccf1da 100644 --- a/src/api/v1/tests/auth.rs +++ b/src/api/v1/tests/auth.rs @@ -44,6 +44,7 @@ async fn auth_works() { let (_, _, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await; let cookies = get_cookie!(signin_resp); + // chech if get user secret works let resp = test::call_service( &mut app, test::TestRequest::get() @@ -54,6 +55,17 @@ async fn auth_works() { .await; assert_eq!(resp.status(), StatusCode::OK); + // check if update user secret works + let resp = test::call_service( + &mut app, + test::TestRequest::post() + .cookie(cookies.clone()) + .uri(GET_SECRET) + .to_request(), + ) + .await; + assert_eq!(resp.status(), StatusCode::OK); + // 2. check if duplicate username is allowed let msg = Register { username: NAME.into(), diff --git a/src/errors.rs b/src/errors.rs index bb061b04..c43bae48 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -187,16 +187,11 @@ impl From for ServiceError { fn from(e: sqlx::Error) -> Self { use sqlx::error::Error; use std::borrow::Cow; - - println!("{:?}", &e); if let Error::Database(err) = e { if err.code() == Some(Cow::from("23505")) { return ServiceError::UsernameTaken; } - - println!("{:?}", &err.code()); } - ServiceError::InternalServerError } } @@ -204,9 +199,7 @@ impl From for ServiceError { pub fn dup_error(e: sqlx::Error, dup_error: ServiceError) -> ServiceError { use sqlx::error::Error; use std::borrow::Cow; - // println!("sqlx:Error: {:#?}", &e); if let Error::Database(err) = e { - // println!("Database Error: {:#?}", &err); if err.code() == Some(Cow::from("23505")) { dup_error } else {