mcaptcha token generation unique constration err handling

This commit is contained in:
realaravinth
2021-04-11 11:17:15 +05:30
parent 08ec215709
commit 36b505ef59
2 changed files with 32 additions and 30 deletions

View File

@@ -14,6 +14,7 @@
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use std::borrow::Cow;
use actix_identity::Identity; use actix_identity::Identity;
use actix_web::{post, web, HttpResponse, Responder}; use actix_web::{post, web, HttpResponse, Responder};
@@ -38,28 +39,43 @@ pub struct MCaptchaDetails {
pub async fn add_mcaptcha(data: web::Data<Data>, id: Identity) -> ServiceResult<impl Responder> { pub async fn add_mcaptcha(data: web::Data<Data>, id: Identity) -> ServiceResult<impl Responder> {
is_authenticated(&id)?; is_authenticated(&id)?;
let username = id.identity().unwrap(); let username = id.identity().unwrap();
let key = get_random(32); let mut key;
let res = sqlx::query!( let resp;
"INSERT INTO mcaptcha_config
loop {
key = get_random(32);
let res = sqlx::query!(
"INSERT INTO mcaptcha_config
(key, user_id) (key, user_id)
VALUES ($1, (SELECT ID FROM mcaptcha_users WHERE name = $2))", VALUES ($1, (SELECT ID FROM mcaptcha_users WHERE name = $2))",
&key, &key,
&username, &username,
) )
.execute(&data.db) .execute(&data.db)
.await; .await;
match res { match res {
Err(e) => { Err(sqlx::Error::Database(err)) => {
println!("{}", &e); if err.code() == Some(Cow::from("23505"))
Err(dup_error(e, ServiceError::TokenNameTaken)) && err.message().contains("mcaptcha_config_key_key")
} {
Ok(_) => { continue;
let resp = MCaptchaDetails { key, name: None }; } else {
Ok(HttpResponse::Ok().json(resp)) Err(sqlx::Error::Database(err))?;
}
}
Err(e) => Err(e)?,
Ok(_) => {
resp = MCaptchaDetails { key, name: None };
break;
}
} }
} }
Ok(HttpResponse::Ok().json(resp))
} }
#[post("/api/v1/mcaptcha/update/key")] #[post("/api/v1/mcaptcha/update/key")]

View File

@@ -196,19 +196,5 @@ impl From<sqlx::Error> for ServiceError {
} }
} }
pub fn dup_error(e: sqlx::Error, dup_error: ServiceError) -> ServiceError {
use sqlx::error::Error;
use std::borrow::Cow;
if let Error::Database(err) = e {
if err.code() == Some(Cow::from("23505")) {
dup_error
} else {
ServiceError::InternalServerError
}
} else {
ServiceError::InternalServerError
}
}
#[cfg(not(tarpaulin_include))] #[cfg(not(tarpaulin_include))]
pub type ServiceResult<V> = std::result::Result<V, ServiceError>; pub type ServiceResult<V> = std::result::Result<V, ServiceError>;