- fix: issue where login failed to return the user if their role was null

- add: register route for api-service
- update: spawn a thread for the rest api in the api service
This commit is contained in:
2024-12-17 04:06:56 -05:00
parent 52455d6ffc
commit c67cdd5b2a
8 changed files with 74 additions and 23 deletions

View File

@@ -8,7 +8,7 @@ use tonic::transport::Channel;
use tower_http::cors::{Any, CorsLayer};
use auth::auth_service_client::AuthServiceClient;
use auth::LoginRequest;
use auth::{LoginRequest, RegisterRequest};
use log::error;
use tokio::sync::Mutex;
@@ -27,6 +27,19 @@ struct RestLoginResponse {
token: String,
}
#[derive(Serialize, Deserialize)]
struct RestRegisterRequest {
username: String,
email: String,
password: String,
}
#[derive(Serialize, Deserialize)]
struct RestRegisterResponse {
success: bool,
message: String,
}
async fn login_handler(
State(grpc_client): State<Arc<Mutex<AuthServiceClient<Channel>>>>,
Json(payload): Json<RestLoginRequest>,
@@ -49,9 +62,34 @@ async fn login_handler(
}
}
async fn register_handler(
State(grpc_client): State<Arc<Mutex<AuthServiceClient<Channel>>>>,
Json(payload): Json<RestRegisterRequest>,
) -> Result<Json<RestRegisterResponse>, axum::http::StatusCode> {
let mut client = grpc_client.lock().await;
let request = tonic::Request::new(RegisterRequest {
username: payload.username,
email: payload.email,
password: payload.password,
});
match client.register(request).await {
Ok(response) => Ok(Json(RestRegisterResponse {
success: response.into_inner().user_id != 0,
message: "Registration successful".to_string(),
})),
Err(e) => {
error!("gRPC Login call failed: {}", e);
Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
},
}
}
pub async fn serve_rest_api(
grpc_client: Arc<Mutex<AuthServiceClient<Channel>>>,
) -> Result<(), Box<dyn std::error::Error>> {
) -> Result<(), Box<dyn std::error::Error + Send>> {
let cors = CorsLayer::new()
.allow_origin(Any) // Allow requests from any origin
.allow_methods([Method::GET, Method::POST]) // Allow specific methods
@@ -59,6 +97,7 @@ pub async fn serve_rest_api(
let app = Router::new()
.route("/api/login", post(login_handler))
.route("/api/register", post(register_handler))
.with_state(grpc_client)
.layer(cors);

View File

@@ -65,7 +65,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Start the Axum REST API
info!("Starting REST API on {}:{}", addr, port);
axum_gateway::serve_rest_api(grpc_client).await?;
tokio::spawn(axum_gateway::serve_rest_api(grpc_client));
select! {
_ = signal::ctrl_c() => {},