Skip to content

Commit

Permalink
feat: add "authenticate" handler for user
Browse files Browse the repository at this point in the history
  • Loading branch information
rhwd committed Apr 10, 2024
1 parent 233ef5e commit 7b74757
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/handlers/user.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
models::user::{CheckUserLogin, CreateUser, LoginUser, User},
structs::app_state::AppState,
models::user::{ CheckUserLogin, CreateUser, LoginUser, User},
structs::app_state::AppState, utils::session,
};
use axum::{
extract::{Path, State},
Expand Down Expand Up @@ -31,17 +31,20 @@ pub async fn get_one(
}
}
}
pub async fn authorize_user(

pub async fn authenticate(
State(app_state): State<Arc<AppState>>,
Json(body):Json<LoginUser>
Json(body): Json<LoginUser>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let user = sqlx::query_as!(CheckUserLogin, "SELECT email, password_hash FROM users WHERE users.email = $1", body.email)
let user = sqlx::query_as!(CheckUserLogin, "SELECT id, email, password_hash FROM users WHERE users.email = $1", body.email)
.fetch_one(&app_state.db)
.await;

match user {
Ok(user) => {
let is_valid = bcrypt::verify(body.password, &user.password_hash).unwrap();
if is_valid {
let _session_id = session::create(user.id).await;
return Ok((StatusCode::OK, Json(json!({"status": "success", "message": "User is authorized"}))));
} else {
return Ok((StatusCode::UNAUTHORIZED, Json(json!({"status": "error", "message": "User is not authorized"}))));
Expand All @@ -53,7 +56,6 @@ pub async fn authorize_user(
Json(json!({"status": "error","message": format!("{:?}", e)})),
));
}

}
}

Expand Down
1 change: 1 addition & 0 deletions src/routes/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ pub fn create_routes(app_state: Arc<AppState>) -> Router {
Router::new()
.route("/users/:id", get(user::get_one))
.route("/users", post(user::create))
.route("/users/login", post(user::authenticate))
.with_state(app_state)
}

0 comments on commit 7b74757

Please sign in to comment.