add using refresh token to get access token
This commit is contained in:
@@ -1,12 +1,6 @@
|
||||
use std::time::Duration;
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
http::{Request as HttpRequest, StatusCode, header::{SET_COOKIE, HeaderValue} },
|
||||
http::request::Parts,
|
||||
middleware::Next,
|
||||
response::{Response, IntoResponse},
|
||||
Json,
|
||||
extract::{Path, State, FromRequest, FromRequestParts, Extension}
|
||||
body::{to_bytes, Body}, extract::{Extension, FromRequest, FromRequestParts, Path, State}, http::{header::{HeaderValue, SET_COOKIE}, request::Parts, Request as HttpRequest, StatusCode }, middleware::Next, response::{IntoResponse, IntoResponseParts, Response}, Json
|
||||
};
|
||||
|
||||
use axum_extra::extract::TypedHeader;
|
||||
@@ -44,11 +38,11 @@ pub struct JwtKeys {
|
||||
pub async fn token_tester(
|
||||
State(state): State<AppState>,
|
||||
//Extension(keys): Extension<JwtKeys>,
|
||||
AuthClaims { user_id, hotel_id, username }: AuthClaims,
|
||||
AuthClaims { user_id, hotel_id }: AuthClaims,
|
||||
) -> impl IntoResponse {
|
||||
format!(
|
||||
"Hello {} (user_id: {}) from hotel {}",
|
||||
username, user_id, hotel_id
|
||||
"(user_id: {}) from hotel {}",
|
||||
user_id, hotel_id
|
||||
)
|
||||
}
|
||||
|
||||
@@ -58,7 +52,7 @@ pub struct AuthUser(pub Claims); //??
|
||||
pub struct AuthClaims {
|
||||
pub user_id: i32,
|
||||
pub hotel_id: i32,
|
||||
pub username: String,
|
||||
//pub username: String,
|
||||
}
|
||||
|
||||
impl<S> FromRequestParts<S> for AuthClaims
|
||||
@@ -96,7 +90,7 @@ where
|
||||
Ok(AuthClaims {
|
||||
user_id: token_data.claims.id,
|
||||
hotel_id: token_data.claims.hotel_id,
|
||||
username: token_data.claims.username,
|
||||
//username: token_data.claims.username,
|
||||
})
|
||||
|
||||
}
|
||||
@@ -381,7 +375,7 @@ pub async fn clean_auth_loging(
|
||||
|
||||
let claims = serde_json::json!({
|
||||
"id": user_id,
|
||||
"hotel_id": payload.hotel_id,
|
||||
"hotel_id": hotel_id,
|
||||
"username": payload.username,
|
||||
"exp": expiration
|
||||
});
|
||||
@@ -402,7 +396,7 @@ pub struct CreateRefreshTokenValue {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
pub device_id: Uuid,
|
||||
pub timestamp: Option<String>,
|
||||
//pub timestamp: Option<String>,
|
||||
|
||||
}
|
||||
|
||||
@@ -424,28 +418,29 @@ pub async fn create_refresh_token(
|
||||
let mut bytes = [0u8; 64];
|
||||
OsRng.fill_bytes(&mut bytes);
|
||||
|
||||
let raw_token = Uuid::new_v4().to_string();
|
||||
|
||||
let hashed_token = argon2
|
||||
.hash_password(&bytes, &salt)
|
||||
.hash_password(raw_token.as_bytes(), &salt)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.to_string();
|
||||
|
||||
let raw_token = general_purpose::STANDARD.encode(&bytes);
|
||||
|
||||
let conn = state.logs_pool.get()
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "DB connection error".to_string()))?;
|
||||
|
||||
let user_row = conn.query_row(
|
||||
"SELECT id, password FROM users WHERE username = ?1",
|
||||
"SELECT id, password, hotel_id FROM users WHERE username = ?1",
|
||||
params![&payload.username],
|
||||
|row| {
|
||||
let user_id: i32 = row.get(0)?;
|
||||
let password: String = row.get(1)?;
|
||||
Ok((user_id, password))
|
||||
let hotel_id: i32 = row.get(2)?;
|
||||
Ok((user_id, password, hotel_id))
|
||||
},
|
||||
).optional()
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "DB get user id error".to_string()))?;
|
||||
|
||||
let (user_id, stored_hash) = user_row
|
||||
let (user_id, stored_hash, hotel_id) = user_row
|
||||
.ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;
|
||||
|
||||
if !verify_password(&payload.password, &stored_hash) {
|
||||
@@ -453,8 +448,8 @@ pub async fn create_refresh_token(
|
||||
}
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO refresh_token (user_id, token_hash, device_id, user_agent) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![user_id, hashed_token, device_id_str, user_agent_str],
|
||||
"INSERT INTO refresh_token (user_id, token_hash, device_id, user_agent, hotel_id) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![user_id, hashed_token, device_id_str, user_agent_str, hotel_id],
|
||||
)
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "DB insert error".to_string()))?;
|
||||
|
||||
@@ -469,6 +464,84 @@ pub async fn create_refresh_token(
|
||||
Ok(response) // ← Wrap in Ok()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginRefreshTokenValues{
|
||||
device_id: Uuid,
|
||||
refresh_token: String,
|
||||
}
|
||||
|
||||
pub async fn login_refresh_token (
|
||||
State(state): State<AppState>,
|
||||
Extension(keys): Extension<JwtKeys>,
|
||||
user_agent: Option<TypedHeader<UserAgent>>,
|
||||
Json(payload): Json<LoginRefreshTokenValues>
|
||||
) -> impl IntoResponse {
|
||||
|
||||
let conn = match state.logs_pool.get() {
|
||||
Ok(c) => c,
|
||||
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "DB connection error").into_response(),
|
||||
};
|
||||
|
||||
let user_agent_str = user_agent
|
||||
.map(|ua| ua.to_string())
|
||||
.unwrap_or_else(|| "Unknown".to_string());
|
||||
|
||||
let device_id_str = payload.device_id.to_string();
|
||||
|
||||
//"SELECT user_id, token_hash, hotel_id FROM refresh_token WHERE device_id = ?1 AND user_agent = ?2",
|
||||
|
||||
let device_row = match conn.query_row(
|
||||
"SELECT user_id, token_hash, hotel_id FROM refresh_token WHERE device_id = ?1 AND user_agent = ?2",
|
||||
params![&device_id_str, &user_agent_str],
|
||||
|row| {
|
||||
let user_id: i32 = row.get(0)?;
|
||||
let token_hash: String = row.get(1)?;
|
||||
let hotel_id: i32 = row.get(2)?;
|
||||
//let displayname: String = row.get(3)?;
|
||||
Ok((user_id, token_hash, hotel_id))
|
||||
},
|
||||
).optional() {
|
||||
Ok(opt) => opt,
|
||||
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "DB query error").into_response(),
|
||||
};
|
||||
|
||||
|
||||
let (user_id, token_hash, hotel_id) = match device_row {
|
||||
Some(tuple) => tuple,
|
||||
None => return (StatusCode::UNAUTHORIZED, "No matching device").into_response(),
|
||||
};
|
||||
|
||||
|
||||
if !verify_password(&payload.refresh_token, &token_hash) {
|
||||
return (StatusCode::UNAUTHORIZED, "Invalid or mismatched token").into_response();
|
||||
}
|
||||
|
||||
|
||||
let expiration = match chrono::Utc::now().checked_add_signed(chrono::Duration::hours(15)) {
|
||||
Some(time) => time.timestamp() as usize,
|
||||
None => {
|
||||
// Handle overflow — probably a 500, since this should never happen
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, "Time overflow".to_string()).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let claims = serde_json::json!({
|
||||
"id": user_id,
|
||||
"hotel_id": hotel_id,
|
||||
//"username": payload.username,
|
||||
"exp": expiration
|
||||
});
|
||||
|
||||
let token = match encode(
|
||||
&Header::default(),
|
||||
&claims,
|
||||
&keys.encoding
|
||||
) {
|
||||
Ok(t) => t,
|
||||
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "JWT creation failed").into_response(),
|
||||
};
|
||||
Json(LoginResponse { token }).into_response()
|
||||
}
|
||||
|
||||
fn internal_error<E: std::fmt::Display>(err: E) -> (StatusCode, String) {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, format!("Internal error: {}", err))
|
||||
|
||||
Reference in New Issue
Block a user