use axum::{extract::State, routing::post, Json}; use rustyrails::{ app::AppContext, controller::{format, unauthorized, Routes}, Result, }; use crate::{ mailers::auth::AuthMailer, models::users::{self, LoginParams, RegisterParams}, views::auth::LoginResponse, }; async fn register( State(ctx): State, Json(params): Json, ) -> Result> { let res = users::Model::create_with_password(&ctx.db, ¶ms).await; let user = match res { Ok(user) => user, Err(err) => { tracing::info!( message = err.to_string(), user_email = ¶ms.email, "could not register user", ); return format::json(()); } }; // TODO:: send website base uri AuthMailer::send_welcome(&ctx, &user.email).await.unwrap(); format::json(()) } async fn login( State(ctx): State, Json(params): Json, ) -> Result> { let user = users::Model::find_by_email(&ctx.db, ¶ms.email).await?; let valid = user.verify_password(¶ms.password)?; if !valid { return unauthorized("unauthorized access"); } let token = user .generate_jwt(&ctx.config.auth.secret, &ctx.config.auth.expiration) .or_else(|_| unauthorized("unauthorized!"))?; format::json(LoginResponse::new(&user, &token)) } pub fn routes() -> Routes { Routes::new() .prefix("auth") .add("/register", post(register)) .add("/login", post(login)) }