using constants for routes

This commit is contained in:
realaravinth
2021-05-02 12:39:37 +05:30
parent c7bac9e623
commit 4f27e1ab8d
10 changed files with 587 additions and 363 deletions

View File

@@ -27,6 +27,27 @@ use crate::errors::*;
use crate::CheckLogin;
use crate::Data;
pub mod routes {
pub struct Auth {
pub login: &'static str,
pub logout: &'static str,
pub register: &'static str,
}
impl Default for Auth {
fn default() -> Self {
let login = "/api/v1/signin";
let logout = "/logout";
let register = "/api/v1/signup";
Self {
login,
logout,
register,
}
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Register {
pub username: String,
@@ -146,101 +167,6 @@ pub async fn signin(
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Secret {
pub secret: String,
}
#[get("/api/v1/account/secret/")]
pub async fn get_secret(id: Identity, data: web::Data<Data>) -> ServiceResult<impl Responder> {
let username = id.identity().unwrap();
let secret = sqlx::query_as!(
Secret,
r#"SELECT secret FROM mcaptcha_users WHERE name = ($1)"#,
&username,
)
.fetch_one(&data.db)
.await?;
Ok(HttpResponse::Ok().json(secret))
}
#[post("/api/v1/account/secret/", wrap = "CheckLogin")]
pub async fn update_user_secret(
id: Identity,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
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())
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Email {
pub email: String,
}
#[post("/api/v1/account/email/", wrap = "CheckLogin")]
pub async fn set_email(
id: Identity,
payload: web::Json<Email>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
let username = id.identity().unwrap();
data.creds.email(&payload.email)?;
let res = sqlx::query!(
"UPDATE mcaptcha_users set email = $1
WHERE name = $2",
&payload.email,
&username,
)
.execute(&data.db)
.await;
if !res.is_ok() {
if let Err(sqlx::Error::Database(err)) = res {
if err.code() == Some(Cow::from("23505"))
&& err.message().contains("mcaptcha_users_email_key")
{
Err(ServiceError::EmailTaken)?
} else {
Err(sqlx::Error::Database(err))?
}
};
}
Ok(HttpResponse::Ok())
}
#[get("/logout", wrap = "CheckLogin")]
pub async fn signout(id: Identity) -> impl Responder {
if let Some(_) = id.identity() {
@@ -250,96 +176,3 @@ pub async fn signout(id: Identity) -> impl Responder {
.set_header(header::LOCATION, "/login")
.body("")
}
#[post("/api/v1/account/delete", wrap = "CheckLogin")]
pub async fn delete_account(
id: Identity,
payload: web::Json<Password>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
use argon2_creds::Config;
use sqlx::Error::RowNotFound;
let username = id.identity().unwrap();
let rec = sqlx::query_as!(
Password,
r#"SELECT password FROM mcaptcha_users WHERE name = ($1)"#,
&username,
)
.fetch_one(&data.db)
.await;
id.forget();
match rec {
Ok(s) => {
if Config::verify(&s.password, &payload.password)? {
sqlx::query!("DELETE FROM mcaptcha_users WHERE name = ($1)", &username)
.execute(&data.db)
.await?;
Ok(HttpResponse::Ok())
} else {
Err(ServiceError::WrongPassword)
}
}
Err(RowNotFound) => return Err(ServiceError::UsernameNotFound),
Err(_) => return Err(ServiceError::InternalServerError)?,
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AccountCheckPayload {
pub val: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AccountCheckResp {
pub exists: bool,
}
#[post("/api/v1/account/username/exists")]
pub async fn username_exists(
payload: web::Json<AccountCheckPayload>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
let res = sqlx::query!(
"SELECT EXISTS (SELECT 1 from mcaptcha_users WHERE name = $1)",
&payload.val,
)
.fetch_one(&data.db)
.await?;
let mut resp = AccountCheckResp { exists: false };
if let Some(x) = res.exists {
if x {
resp.exists = true;
}
}
Ok(HttpResponse::Ok().json(resp))
}
#[post("/api/v1/account/email/exists")]
pub async fn email_exists(
payload: web::Json<AccountCheckPayload>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
let res = sqlx::query!(
"SELECT EXISTS (SELECT 1 from mcaptcha_users WHERE email = $1)",
&payload.val,
)
.fetch_one(&data.db)
.await?;
let mut resp = AccountCheckResp { exists: false };
if let Some(x) = res.exists {
if x {
resp.exists = true;
}
}
Ok(HttpResponse::Ok().json(resp))
}