rusty_api/core/auth_routes.rs
1/*!
2 * The auth_routes module for handling user authentication and registration.
3 *
4 * This module defines the routes for user login and registration, including
5 * the necessary input and output structures. It uses Actix Web for routing
6 * and SQLx for database interaction.
7 */
8use actix_web::{web, HttpResponse};
9use crate::core::auth::{login_user, register_user};
10use crate::core::user::{LoginInput, RegisterInput};
11
12/**
13 * Configure routes for user authentication and registration.
14 *
15 * This function sets up the routes for user login and registration, using
16 * Actix Web's `ServiceConfig`. It also applies middleware for JWT validation.
17 *
18 * # Arguments
19 * - `cfg`: A mutable reference to the Actix Web `ServiceConfig`.
20 */
21pub fn configure_auth_routes(cfg: &mut web::ServiceConfig, login_path: &str, register_path: &str) {
22 cfg.route(login_path, web::post().to(login))
23 .route(register_path, web::post().to(register));
24}
25
26/**
27 * Login route handler.
28 *
29 * This function handles user login requests. It extracts the login input
30 * from the request, calls the `login_user` function to authenticate the user,
31 * and returns a JSON response with the login token or an error message.
32 *
33 * # Arguments
34 * - `pool`: A reference to the SQLx SQLite connection pool.
35 * - `input`: The login input data, containing the username and password.
36 *
37 * # Returns
38 * An `HttpResponse` containing the login token or an error message.
39 */
40async fn login(
41 pool: web::Data<sqlx::SqlitePool>,
42 input: web::Json<LoginInput>,
43) -> HttpResponse {
44 match login_user(&pool, input.into_inner()).await {
45 Ok(response) => HttpResponse::Ok().json(response),
46 Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })),
47 }
48}
49
50/**
51 * Register route handler.
52 *
53 * This function handles user registration requests. It extracts the registration
54 * input from the request, calls the `register_user` function to create a new user,
55 * and returns a JSON response with the user data or an error message.
56 *
57 * # Arguments
58 * - `pool`: A reference to the SQLx SQLite connection pool.
59 * - `input`: The registration input data, containing the username and password.
60 *
61 * # Returns
62 * An `HttpResponse` containing the user data or an error message.
63 */
64async fn register(
65 pool: web::Data<sqlx::SqlitePool>,
66 input: web::Json<RegisterInput>,
67) -> HttpResponse {
68 match register_user(&pool, input.into_inner()).await {
69 Ok(user) => HttpResponse::Created().json(user),
70 Err(e) => HttpResponse::BadRequest().json(serde_json::json!({ "error": e })),
71 }
72}