it compiled

This commit is contained in:
filipriec
2025-03-25 10:28:29 +01:00
parent cd32c175a4
commit f40654d2c4
4 changed files with 81 additions and 56 deletions

View File

@@ -1,64 +1,48 @@
// src/auth/handlers/register.rs
use bcrypt::{hash, DEFAULT_COST};
use tonic::{Request, Response, Status};
use common::proto::multieko2::auth::{auth_service_server, RegisterRequest, AuthResponse};
use tonic::{Response, Status};
use common::proto::multieko2::auth::{RegisterRequest, AuthResponse};
use crate::db::PgPool;
use crate::auth::models::AuthError;
pub struct AuthService {
pool: PgPool,
}
impl AuthService {
pub fn new(pool: PgPool) -> Self {
Self { pool }
pub async fn register(
pool: &PgPool,
payload: RegisterRequest,
) -> Result<Response<AuthResponse>, Status> {
// Validate passwords match
if payload.password != payload.password_confirmation {
return Err(Status::invalid_argument(AuthError::PasswordMismatch.to_string()));
}
}
#[tonic::async_trait]
impl auth_service_server::AuthService for AuthService {
async fn register(
&self,
request: Request<RegisterRequest>,
) -> Result<Response<AuthResponse>, Status> {
let payload = request.into_inner();
// Hash password
let password_hash = hash(payload.password, DEFAULT_COST)
.map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?;
// Validate passwords match
if payload.password != payload.password_confirmation {
return Err(Status::invalid_argument(AuthError::PasswordMismatch.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(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())
}
})?;
// 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(AuthResponse {
id: user.id.to_string(),
username: user.username,
email: user.email.unwrap_or_default(),
role: user.role,
}))
}
Ok(Response::new(AuthResponse {
id: user.id.to_string(),
username: user.username,
email: user.email.unwrap_or_default(),
role: user.role,
}))
}