- add: initial database and auth services

This commit is contained in:
2024-11-25 20:45:16 -05:00
parent 6a35b5b373
commit 3ff22c9a5b
24 changed files with 817 additions and 1 deletions

52
auth-service/src/grpc.rs Normal file
View File

@@ -0,0 +1,52 @@
use tonic::{Request, Response, Status};
use crate::jwt::{generate_token, validate_token};
use crate::users::verify_user;
use crate::database_client::DatabaseClient;
use crate::auth::auth_service_server::{AuthService};
use crate::auth::{LoginRequest, LoginResponse, ValidateTokenRequest, ValidateTokenResponse};
use tracing::{info, warn};
pub struct MyAuthService {
pub db_client: DatabaseClient,
}
#[tonic::async_trait]
impl AuthService for MyAuthService {
async fn login(
&self,
request: Request<LoginRequest>,
) -> Result<Response<LoginResponse>, Status> {
let req = request.into_inner();
info!("Login attempt for username: {}", req.username);
if let Some(user_id) = verify_user(self.db_client.clone(), &req.username, &req.password).await {
let token = generate_token(&user_id, vec!["user".to_string()])
.map_err(|_| Status::internal("Token generation failed"))?;
info!("Login successful for username: {}", req.username);
Ok(Response::new(LoginResponse { token, user_id }))
} else {
warn!("Invalid login attempt for username: {}", req.username);
Err(Status::unauthenticated("Invalid credentials"))
}
}
async fn validate_token(
&self,
request: Request<ValidateTokenRequest>,
) -> Result<Response<ValidateTokenResponse>, Status> {
let req = request.into_inner();
match validate_token(&req.token) {
Ok(user_id) => Ok(Response::new(ValidateTokenResponse {
valid: true,
user_id,
})),
Err(_) => Ok(Response::new(ValidateTokenResponse {
valid: false,
user_id: "".to_string(),
})),
}
}
}