broken only push user data

This commit is contained in:
filipriec
2025-03-24 21:46:04 +01:00
parent 8a248cab58
commit 70d83c284a
13 changed files with 608 additions and 6 deletions

View File

@@ -0,0 +1,61 @@
use bcrypt::{hash, DEFAULT_COST};
use tonic::{Request, Response, Status};
use uuid::Uuid;
use crate::{auth::{models::{RegisterRequest, AuthResponse, AuthError}, db::PgPool}};
pub struct AuthService {
pool: PgPool,
}
impl AuthService {
pub fn new(pool: PgPool) -> Self {
Self { pool }
}
}
#[tonic::async_trait]
impl multieko2::auth::auth_service_server::AuthService for AuthService {
async fn register(
&self,
request: Request<multieko2::auth::RegisterRequest>,
) -> Result<Response<multieko2::auth::AuthResponse>, Status> {
let payload = request.into_inner();
// Validate passwords match
if payload.password != payload.password_confirmation {
return Err(Status::invalid_argument(AuthError::PasswordMismatch.to_string()));
}
// Hash password
let password_hash = hash(payload.password, DEFAULT_COST)
.map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?;
// Insert user
let user = sqlx::query!(
r#"
INSERT INTO users (username, email, password_hash, role)
VALUES ($1, $2, $3, 'accountant')
RETURNING id, username, email, role
"#,
payload.username,
payload.email,
password_hash
)
.fetch_one(&self.pool)
.await
.map_err(|e| {
if e.to_string().contains("duplicate key") {
Status::already_exists(AuthError::UserExists.to_string())
} else {
Status::internal(AuthError::DatabaseError(e.to_string()).to_string())
}
})?;
Ok(Response::new(multieko2::auth::AuthResponse {
id: user.id.to_string(),
username: user.username,
email: user.email,
role: user.role,
}))
}
}