From e856e9d6c7505d495e894febb90a27eb58b8770f Mon Sep 17 00:00:00 2001 From: filipriec Date: Sun, 13 Apr 2025 13:45:22 +0200 Subject: [PATCH] response contains username but jwt is holding username also --- server/src/auth/handlers/login.rs | 5 +++-- server/src/auth/logic/jwt.rs | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/server/src/auth/handlers/login.rs b/server/src/auth/handlers/login.rs index 0eb6a7b..10d9277 100644 --- a/server/src/auth/handlers/login.rs +++ b/server/src/auth/handlers/login.rs @@ -11,7 +11,7 @@ pub async fn login( ) -> Result, Status> { let user = sqlx::query!( r#" - SELECT id, password_hash, role + SELECT id, username, password_hash, role FROM users WHERE username = $1 OR email = $1 "#, @@ -33,7 +33,7 @@ pub async fn login( return Err(Status::unauthenticated("Invalid credentials")); } - let token = jwt::generate_token(user.id, &user.role) + let token = jwt::generate_token(user.id, &user.role, &user.username) .map_err(|e| Status::internal(e.to_string()))?; Ok(Response::new(LoginResponse { @@ -42,5 +42,6 @@ pub async fn login( expires_in: 86400, // 24 hours user_id: user.id.to_string(), role: user.role, + username: user.username, })) } diff --git a/server/src/auth/logic/jwt.rs b/server/src/auth/logic/jwt.rs index 7766159..5c667dc 100644 --- a/server/src/auth/logic/jwt.rs +++ b/server/src/auth/logic/jwt.rs @@ -18,6 +18,7 @@ pub struct Claims { pub sub: Uuid, // User ID pub exp: i64, // Expiration time pub role: String, // User role + pub username: String, } pub fn init_jwt() -> Result<(), AuthError> { @@ -32,7 +33,7 @@ pub fn init_jwt() -> Result<(), AuthError> { Ok(()) } -pub fn generate_token(user_id: Uuid, role: &str) -> Result { +pub fn generate_token(user_id: Uuid, role: &str, username: &str) -> Result { let keys = KEYS.get().ok_or(AuthError::ConfigError("JWT not initialized".to_string()))?; let exp = OffsetDateTime::now_utc() + Duration::days(365000); @@ -40,6 +41,7 @@ pub fn generate_token(user_id: Uuid, role: &str) -> Result { sub: user_id, exp: exp.unix_timestamp(), role: role.to_string(), + username: username.to_string(), }; encode(&Header::default(), &claims, &keys.encoding)