debt-pirate/api/src/db/user.rs

95 lines
2.2 KiB
Rust
Raw Normal View History

2024-10-03 15:27:30 -04:00
use std::fmt::Debug;
use sqlx::prelude::FromRow;
2024-10-03 15:27:30 -04:00
use tracing::error;
use crate::models::AppError;
use super::DbPool;
2024-10-03 15:27:30 -04:00
#[derive(Clone)]
pub struct NewUserEntity {
pub username: String,
pub password: String,
pub email: String,
pub name: String,
}
2024-10-03 15:27:30 -04:00
impl Debug for NewUserEntity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NewUserEntity")
.field("username", &self.username)
.field("password", &"********")
.field("email", &self.email)
.field("name", &self.name)
.finish()
}
}
#[allow(dead_code)]
#[derive(Debug, FromRow)]
pub struct UserEntity {
pub id: i32,
pub name: String,
2024-08-22 17:29:24 -04:00
pub email: String,
pub status_id: i32,
}
pub async fn insert_new_user(
pool: &DbPool,
new_user: NewUserEntity,
) -> Result<UserEntity, AppError> {
let NewUserEntity {
username,
password,
email,
name,
2024-10-03 15:27:30 -04:00
} = new_user.clone();
sqlx::query_as::<_, UserEntity>("INSERT INTO public.user (username, email, password, name) VALUES ($1, $2, $3, $4) RETURNING id, username, email, name, status_id;")
.bind(username)
.bind(email)
.bind(password)
.bind(name)
.fetch_one(pool).await
.map_err(|err| {
2024-10-03 15:27:30 -04:00
error!(%err, record = ?new_user, "Cannot insert new user record");
AppError::from(err)
})
}
2024-10-05 08:09:46 -04:00
#[derive(Debug, FromRow)]
pub struct UserIdAndHashedPassword {
pub id: i32,
pub password: String,
}
pub async fn get_username_and_password_by_username(
pool: &DbPool,
username: String,
) -> Result<UserIdAndHashedPassword, AppError> {
sqlx::query_as::<_, UserIdAndHashedPassword>(
"SELECT id, password FROM public.user WHERE username = $1;",
)
.bind(username)
.fetch_one(pool)
.await
.map_err(|err| {
error!(%err, "Unable to find user");
AppError::from(err)
})
}
pub async fn verify_user(pool: &DbPool, user_id: i32) -> Result<(), AppError> {
sqlx::query("UPDATE public.user SET status_id = 1, updated_at = now() WHERE id = $1;")
.bind(user_id)
.execute(pool)
.await
.map_err(|err| {
2024-10-05 08:09:46 -04:00
error!(%err, user_id, "Error verifying user");
AppError::from(err)
})
.map(|_| ())
}