diff options
| author | Santo Cariotti <santo@dcariotti.me> | 2022-09-01 16:45:04 +0000 |
|---|---|---|
| committer | Santo Cariotti <santo@dcariotti.me> | 2022-09-01 16:45:04 +0000 |
| commit | ab23761e090b8ab6311a360eada7131f6663a3bf (patch) | |
| tree | b5a99bb4cfc811e45fc2e3680b4f8b1e944515eb /src/routes | |
Fork from m6-ie project
Diffstat (limited to 'src/routes')
| -rw-r--r-- | src/routes/auth.rs | 25 | ||||
| -rw-r--r-- | src/routes/mod.rs | 2 | ||||
| -rw-r--r-- | src/routes/user.rs | 39 |
3 files changed, 66 insertions, 0 deletions
diff --git a/src/routes/auth.rs b/src/routes/auth.rs new file mode 100644 index 0000000..37c41b2 --- /dev/null +++ b/src/routes/auth.rs @@ -0,0 +1,25 @@ +use crate::errors::AppError; +use crate::models::{ + auth::{AuthBody, Claims}, + user::{User, UserCreate}, +}; +use axum::{routing::post, Json, Router}; + +/// Create routes for `/v1/auth/` namespace +pub fn create_route() -> Router { + Router::new().route("/login", post(make_login)) +} + +/// Make login. Check if a user with the email and password passed in request body exists into the +/// database +async fn make_login(Json(payload): Json<UserCreate>) -> Result<Json<AuthBody>, AppError> { + let user = User::new(payload.email, payload.password); + match User::find(user).await { + Ok(user) => { + let claims = Claims::new(user.id); + let token = claims.get_token()?; + Ok(Json(AuthBody::new(token))) + } + Err(_) => Err(AppError::NotFound), + } +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs new file mode 100644 index 0000000..f9bae3d --- /dev/null +++ b/src/routes/mod.rs @@ -0,0 +1,2 @@ +pub mod auth; +pub mod user; diff --git a/src/routes/user.rs b/src/routes/user.rs new file mode 100644 index 0000000..d44df66 --- /dev/null +++ b/src/routes/user.rs @@ -0,0 +1,39 @@ +use crate::errors::AppError; +use crate::models::{ + auth::Claims, + user::{User, UserCreate, UserList}, +}; +use axum::{extract::Path, routing::get, Json, Router}; + +/// Create routes for `/v1/users/` namespace +pub fn create_route() -> Router { + Router::new() + .route("/", get(list_users).post(create_user)) + .route("/:id", get(get_user)) +} + +/// List users. Checks Authorization token +async fn list_users(_: Claims) -> Result<Json<Vec<UserList>>, AppError> { + let users = User::list().await?; + + Ok(Json(users)) +} + +/// Create an user. Checks Authorization token +async fn create_user( + Json(payload): Json<UserCreate>, + _: Claims, +) -> Result<Json<UserList>, AppError> { + let user = User::new(payload.email, payload.password); + let user_new = User::create(user).await?; + + Ok(Json(user_new)) +} + +/// Get an user with id = `user_id`. Checks Authorization token +async fn get_user(Path(user_id): Path<i32>, _: Claims) -> Result<Json<UserList>, AppError> { + match User::find_by_id(user_id).await { + Ok(user) => Ok(Json(user)), + Err(_) => Err(AppError::NotFound), + } +} |
