response contains username but jwt is holding username also

This commit is contained in:
filipriec
2025-04-13 13:45:22 +02:00
parent ad2c783870
commit e856e9d6c7
2 changed files with 6 additions and 3 deletions

View File

@@ -11,7 +11,7 @@ pub async fn login(
) -> Result<Response<LoginResponse>, 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,
}))
}

View File

@@ -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<String, AuthError> {
pub fn generate_token(user_id: Uuid, role: &str, username: &str) -> Result<String, AuthError> {
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<String, AuthError> {
sub: user_id,
exp: exp.unix_timestamp(),
role: role.to_string(),
username: username.to_string(),
};
encode(&Header::default(), &claims, &keys.encoding)