feat(auth): implement user registration and login with JWT authentication

- Added `bcrypt`, `jsonwebtoken`, and `once_cell` dependencies to manage password hashing and JWT handling.
- Created `Claims` struct for JWT claims and implemented token generation in the login route.
- Implemented user registration and authentication logic in the `auth` module.
- Updated error handling to include validation errors.
- Created new routes for user registration and login, and integrated them into the main router.
- Added tests for the authentication flow, including registration and login scenarios.
- Updated user model to include a password hash field.
- Refactored user creation logic to include password validation.
- Adjusted feed and user routes to utilize JWT for authentication.
This commit is contained in:
2025-09-06 00:06:30 +02:00
parent d70015c887
commit 3d73c7f198
33 changed files with 575 additions and 136 deletions

View File

@@ -9,13 +9,10 @@ use crate::api::main::setup;
#[tokio::test]
async fn test_post_users() {
let app = setup().await;
let response = make_post_request(
app.router,
"/users",
r#"{"username": "test"}"#.to_owned(),
None,
)
.await;
let body = r#"{"username": "test", "password": "password123"}"#.to_owned();
let response = make_post_request(app.router, "/auth/register", body, None).await;
assert_eq!(response.status(), StatusCode::CREATED);
let body = response.into_body().collect().await.unwrap().to_bytes();
@@ -25,36 +22,25 @@ async fn test_post_users() {
#[tokio::test]
pub(super) async fn test_post_users_error() {
let app = setup().await;
let response = make_post_request(
app.router,
"/users",
r#"{"username": "1"}"#.to_owned(),
None,
)
.await;
let body = r#"{"username": "1", "password": "password123"}"#.to_owned();
let response = make_post_request(app.router, "/auth/register", body, None).await;
println!("{:?}", response);
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body = response.into_body().collect().await.unwrap().to_bytes();
let result: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(result["message"], "Validation error");
assert_eq!(result["details"]["username"][0]["code"], "length");
assert_eq!(result["details"]["username"][0]["message"], Value::Null);
assert_eq!(
result["details"]["username"][0]["params"]["min"],
Value::Number(2.into())
)
}
#[tokio::test]
pub async fn test_get_users() {
let app = setup().await;
make_post_request(
app.router.clone(),
"/users",
r#"{"username": "test"}"#.to_owned(),
None,
)
.await;
let body = r#"{"username": "test", "password": "password123"}"#.to_owned();
make_post_request(app.router.clone(), "/auth/register", body, None).await;
let response = make_get_request(app.router, "/users", None).await;
assert_eq!(response.status(), StatusCode::OK);