From 9034c74cd36cdf3615dd80dc975500d235cebfcc Mon Sep 17 00:00:00 2001 From: Toby Vincent Date: Tue, 2 Apr 2024 19:07:23 -0500 Subject: refactor: move routes into individual modules --- src/routes/healthcheck.rs | 22 ++++++++ src/routes/login.rs | 140 ++++++++++++++++++++++++++++++++++++++++++++++ src/routes/register.rs | 139 +++++++++++++++++++++++++++++++++++++++++++++ src/routes/user.rs | 106 +++++++++++++++++++++++++++++++++++ 4 files changed, 407 insertions(+) create mode 100644 src/routes/healthcheck.rs create mode 100644 src/routes/login.rs create mode 100644 src/routes/register.rs create mode 100644 src/routes/user.rs (limited to 'src/routes') diff --git a/src/routes/healthcheck.rs b/src/routes/healthcheck.rs new file mode 100644 index 0000000..7627336 --- /dev/null +++ b/src/routes/healthcheck.rs @@ -0,0 +1,22 @@ +use axum::{response::IntoResponse, Json}; +use axum_extra::routing::TypedPath; +use serde::Deserialize; + +#[derive(Debug, Deserialize, TypedPath)] +#[typed_path("/api/healthcheck")] +pub struct HealthCheck; + +impl HealthCheck { + #[tracing::instrument] + pub async fn get(self) -> impl IntoResponse { + const MESSAGE: &str = "Unnamed server"; + + let json_response = serde_json::json!({ + "status": "success", + "message": MESSAGE + }); + + Json(json_response) + } +} + diff --git a/src/routes/login.rs b/src/routes/login.rs new file mode 100644 index 0000000..12442e8 --- /dev/null +++ b/src/routes/login.rs @@ -0,0 +1,140 @@ +use std::sync::Arc; + +use argon2::{Argon2, PasswordHash, PasswordVerifier}; +use axum::{extract::State, http::header::SET_COOKIE, response::IntoResponse, Json}; +use axum_extra::{ + extract::cookie::{Cookie, SameSite}, + routing::TypedPath, +}; +use jsonwebtoken::{EncodingKey, Header}; +use serde::Deserialize; + +use crate::{ + model::{LoginSchema, TokenClaims, User}, + state::AppState, + Error, +}; + +#[derive(Debug, Deserialize, TypedPath)] +#[typed_path("/api/login")] +pub struct Login; + +impl Login { + #[tracing::instrument(skip(state, password))] + pub async fn post( + self, + State(state): State>, + Json(LoginSchema { email, password }): Json, + ) -> Result { + let User { + uuid, + password_hash, + .. + } = sqlx::query_as!( + User, + "SELECT * FROM users WHERE email = $1", + email.to_ascii_lowercase() + ) + .fetch_optional(&state.pool) + .await? + .ok_or(Error::LoginInvalid)?; + + Argon2::default() + .verify_password(password.as_bytes(), &PasswordHash::new(&password_hash)?)?; + + let token = jsonwebtoken::encode( + &Header::default(), + &TokenClaims::new(uuid, state.jwt_max_age), + &EncodingKey::from_secret(state.jwt_secret.as_ref()), + )?; + + let cookie = Cookie::build(("token", token.to_owned())) + .path("/") + .max_age(state.jwt_max_age) + .same_site(SameSite::Lax) + .http_only(true) + .build(); + + let mut response = Json(token).into_response(); + + response + .headers_mut() + .insert(SET_COOKIE, cookie.to_string().parse().unwrap()); + + Ok(response) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use axum::{ + body::Body, + http::{header, Request, StatusCode}, + }; + use sqlx::PgPool; + use tower::ServiceExt; + + use crate::init_router; + + const JWT_SECRET: &str = "test-jwt-secret-token"; + const JWT_MAX_AGE: time::Duration = time::Duration::HOUR; + + #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))] + async fn test_login_unauthorized(pool: PgPool) -> Result<(), Error> { + let state = Arc::new(AppState { + pool, + jwt_secret: JWT_SECRET.to_string(), + jwt_max_age: JWT_MAX_AGE, + }); + let router = init_router(state.clone()); + + let user = LoginSchema { + email: "adent@earth.sol".to_string(), + password: "hunter2".to_string(), + }; + + let request = Request::builder() + .uri("/api/login") + .method("POST") + .header(header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref()) + .body(Body::from(serde_json::to_vec(&user).unwrap()))?; + + let response = router.oneshot(request).await.unwrap(); + + assert_eq!(StatusCode::UNAUTHORIZED, response.status()); + + Ok(()) + } + + #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))] + async fn test_login_ok(pool: PgPool) -> Result<(), Error> { + let state = Arc::new(AppState { + pool, + jwt_secret: JWT_SECRET.to_string(), + jwt_max_age: JWT_MAX_AGE, + }); + let router = init_router(state.clone()); + + let user = LoginSchema { + email: "adent@earth.sol".to_string(), + password: "solongandthanksforallthefish".to_string(), + }; + + let response = router + .oneshot( + Request::builder() + .uri("/api/login") + .method("POST") + .header(header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref()) + .body(Body::from(serde_json::to_vec(&user).unwrap()))?, + ) + .await + .unwrap(); + + assert_eq!(StatusCode::OK, response.status()); + + Ok(()) + } +} diff --git a/src/routes/register.rs b/src/routes/register.rs new file mode 100644 index 0000000..1c0f82d --- /dev/null +++ b/src/routes/register.rs @@ -0,0 +1,139 @@ +use std::{str::FromStr, sync::Arc}; + +use argon2::{ + password_hash::{rand_core::OsRng, SaltString}, + Argon2, PasswordHasher, +}; +use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; +use axum_extra::routing::TypedPath; +use serde::Deserialize; + +use crate::{ + model::{RegisterSchema, User}, + state::AppState, + Error, +}; + +#[derive(Debug, Deserialize, TypedPath)] +#[typed_path("/api/register")] +pub struct Register; + +impl Register { + #[tracing::instrument(skip(password))] + pub async fn post( + self, + State(state): State>, + Json(RegisterSchema { + name, + email, + password, + }): Json, + ) -> impl IntoResponse { + email_address::EmailAddress::from_str(&email)?; + + let exists: Option = + sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM users WHERE email = $1)") + .bind(email.to_ascii_lowercase()) + .fetch_one(&state.pool) + .await?; + + if exists.is_some_and(|b| b) { + return Err(Error::EmailExists); + } + + let salt = SaltString::generate(&mut OsRng); + let password_hash = Argon2::default().hash_password(password.as_bytes(), &salt)?; + + let user = sqlx::query_as!( + User, + "INSERT INTO users (name,email,password_hash) VALUES ($1, $2, $3) RETURNING *", + name, + email.to_ascii_lowercase(), + password_hash.to_string() + ) + .fetch_one(&state.pool) + .await?; + + Ok((StatusCode::CREATED, Json(user))) + } +} + +#[cfg(test)] +mod tests { + use crate::init_router; + + use super::*; + + use axum::{ + body::Body, + http::{header, Request, StatusCode}, + }; + use http_body_util::BodyExt; + use sqlx::PgPool; + use tower::ServiceExt; + + const JWT_SECRET: &str = "test-jwt-secret-token"; + const JWT_MAX_AGE: time::Duration = time::Duration::HOUR; + + #[sqlx::test] + async fn test_register_created(pool: PgPool) -> Result<(), Error> { + let state = Arc::new(AppState { + pool, + jwt_secret: JWT_SECRET.to_string(), + jwt_max_age: JWT_MAX_AGE, + }); + let router = init_router(state.clone()); + + let user = RegisterSchema { + name: "Arthur Dent".to_string(), + email: "adent@earth.sol".to_string(), + password: "solongandthanksforallthefish".to_string(), + }; + + let request = Request::builder() + .uri("/api/register") + .method("POST") + .header(header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref()) + .body(Body::from(serde_json::to_vec(&user).unwrap()))?; + + let response = router.oneshot(request).await.unwrap(); + + assert_eq!(StatusCode::CREATED, response.status()); + + let body_bytes = response.into_body().collect().await?.to_bytes(); + let User { name, email, .. } = serde_json::from_slice(&body_bytes)?; + + assert_eq!(user.name, name); + assert_eq!(user.email, email); + + Ok(()) + } + + #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))] + async fn test_register_conflict(pool: PgPool) -> Result<(), Error> { + let state = Arc::new(AppState { + pool, + jwt_secret: JWT_SECRET.to_string(), + jwt_max_age: JWT_MAX_AGE, + }); + let router = init_router(state.clone()); + + let user = RegisterSchema { + name: "Arthur Dent".to_string(), + email: "adent@earth.sol".to_string(), + password: "solongandthanksforallthefish".to_string(), + }; + + let request = Request::builder() + .uri("/api/register") + .method("POST") + .header(header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref()) + .body(Body::from(serde_json::to_vec(&user).unwrap()))?; + + let response = router.oneshot(request).await.unwrap(); + + assert_eq!(StatusCode::CONFLICT, response.status()); + + Ok(()) + } +} diff --git a/src/routes/user.rs b/src/routes/user.rs new file mode 100644 index 0000000..71ed9a0 --- /dev/null +++ b/src/routes/user.rs @@ -0,0 +1,106 @@ +use std::sync::Arc; + +use axum::{extract::State, response::IntoResponse, Json}; +use axum_extra::routing::TypedPath; +use serde::Deserialize; + +use crate::{model::User, state::AppState, Error}; + +#[derive(Debug, Deserialize, TypedPath)] +#[typed_path("/api/user/:uuid")] +pub struct UserUuid { + pub uuid: uuid::Uuid, +} + +impl UserUuid { + /// Get a user with a specific `uuid` + #[tracing::instrument] + pub async fn get(self, State(state): State>) -> impl IntoResponse { + sqlx::query_as!(User, "SELECT * FROM users WHERE uuid = $1", self.uuid) + .fetch_optional(&state.pool) + .await? + .ok_or_else(|| Error::UserNotFound) + .map(Json) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use axum::{ + body::Body, + http::{Request, StatusCode}, + }; + use http_body_util::BodyExt; + use sqlx::PgPool; + use tower::ServiceExt; + + use crate::init_router; + + const JWT_SECRET: &str = "test-jwt-secret-token"; + const JWT_MAX_AGE: time::Duration = time::Duration::HOUR; + + #[sqlx::test] + async fn test_user_not_found(pool: PgPool) -> Result<(), Error> { + let state = Arc::new(AppState { + pool, + jwt_secret: JWT_SECRET.to_string(), + jwt_max_age: JWT_MAX_AGE, + }); + let router = init_router(state.clone()); + + let user = User { + uuid: uuid::uuid!("4c14f795-86f0-4361-a02f-0edb966fb145"), + name: "Arthur Dent".to_string(), + email: "adent@earth.sol".to_string(), + ..Default::default() + }; + + let request = Request::builder() + .uri(format!("/api/user/{}", user.uuid)) + .body(Body::empty())?; + + let response = router.oneshot(request).await.unwrap(); + + assert_eq!(StatusCode::NOT_FOUND, response.status()); + + Ok(()) + } + + #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))] + async fn test_user_ok(pool: PgPool) -> Result<(), Error> { + let state = Arc::new(AppState { + pool, + jwt_secret: JWT_SECRET.to_string(), + jwt_max_age: JWT_MAX_AGE, + }); + let router = init_router(state.clone()); + + let user = User { + uuid: uuid::uuid!("4c14f795-86f0-4361-a02f-0edb966fb145"), + name: "Arthur Dent".to_string(), + email: "adent@earth.sol".to_string(), + ..Default::default() + }; + + let request = Request::builder() + .uri(format!("/api/user/{}", user.uuid)) + .body(Body::empty())?; + + let response = router.oneshot(request).await.unwrap(); + + assert_eq!(StatusCode::OK, response.status()); + + let body_bytes = response.into_body().collect().await?.to_bytes(); + let User { + uuid, name, email, .. + } = serde_json::from_slice(&body_bytes)?; + + assert_eq!(user.uuid, uuid); + assert_eq!(user.name, name); + assert_eq!(user.email, email); + + Ok(()) + } +} -- cgit v1.2.3-70-g09d2