-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9994f0e
commit bb9e1d7
Showing
9 changed files
with
262 additions
and
45 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
POSTGRES_HOST=127.0.0.1 | ||
POSTGRES_PORT=5432 | ||
POSTGRES_USER=postgres | ||
POSTGRES_PASSWORD=aboba | ||
POSTGRES_DB=rinab | ||
|
||
DATABASE_URL=postgresql://postgres:[email protected]:5432/rinab?schema=public | ||
|
||
PGADMIN_DEFAULT_EMAIL=[email protected] | ||
PGADMIN_DEFAULT_PASSWORD=aboba | ||
|
||
JWT_SECRET=agjGKfVxVf2TbeuzLS8wKVnQchBEfz5XRWtSmDUkcmgErReWDPAa689VSKVTrrM2 | ||
JWT_EXPIRED_IN=60m | ||
JWT_MAXAGE=60 |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
use std::sync::Arc; | ||
|
||
use axum::{ | ||
extract::State, | ||
http::{header, Request, StatusCode}, | ||
middleware::Next, | ||
response::IntoResponse, | ||
Json, | ||
}; | ||
|
||
use axum_extra::extract::cookie::CookieJar; | ||
use jsonwebtoken::{decode, DecodingKey, Validation}; | ||
use serde::Serialize; | ||
|
||
use crate::{ | ||
model::{TokenClaims, User}, | ||
AppState, | ||
}; | ||
|
||
#[derive(Debug, Serialize)] | ||
pub struct ErrorResponse { | ||
pub status: &'static str, | ||
pub message: String, | ||
} | ||
|
||
pub async fn auth<B>( | ||
cookie_jar: CookieJar, | ||
State(data): State<Arc<AppState>>, | ||
mut req: Request<B>, | ||
next: Next<B>, | ||
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> { | ||
let token = cookie_jar | ||
.get("token") | ||
.map(|cookie| cookie.value().to_string()) | ||
.or_else(|| { | ||
req.headers() | ||
.get(header::AUTHORIZATION) | ||
.and_then(|auth_header| auth_header.to_str().ok()) | ||
.and_then(|auth_value| { | ||
if auth_value.starts_with("Bearer ") { | ||
Some(auth_value[7..].to_owned()) | ||
} else { | ||
None | ||
} | ||
}) | ||
}); | ||
|
||
let token = token.ok_or_else(|| { | ||
let json_error = ErrorResponse { | ||
status: "fail", | ||
message: "You are not logged in, please provide token".to_string(), | ||
}; | ||
(StatusCode::UNAUTHORIZED, Json(json_error)) | ||
})?; | ||
|
||
let claims = decode::<TokenClaims>( | ||
&token, | ||
&DecodingKey::from_secret(data.env.jwt_secret.as_ref()), | ||
&Validation::default(), | ||
) | ||
.map_err(|_| { | ||
let json_error = ErrorResponse { | ||
status: "fail", | ||
message: "Invalid token".to_string(), | ||
}; | ||
(StatusCode::UNAUTHORIZED, Json(json_error)) | ||
})? | ||
.claims; | ||
|
||
let user_id = uuid::Uuid::parse_str(&claims.sub).map_err(|_| { | ||
let json_error = ErrorResponse { | ||
status: "fail", | ||
message: "Invalid token".to_string(), | ||
}; | ||
(StatusCode::UNAUTHORIZED, Json(json_error)) | ||
})?; | ||
|
||
let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", user_id) | ||
.fetch_optional(&data.db_pool) | ||
.await | ||
.map_err(|e| { | ||
let json_error = ErrorResponse { | ||
status: "fail", | ||
message: format!("Error fetching user from database: {}", e), | ||
}; | ||
(StatusCode::INTERNAL_SERVER_ERROR, Json(json_error)) | ||
})?; | ||
|
||
let user = user.ok_or_else(|| { | ||
let json_error = ErrorResponse { | ||
status: "fail", | ||
message: "The user belonging to this token no longer exists".to_string(), | ||
}; | ||
(StatusCode::UNAUTHORIZED, Json(json_error)) | ||
})?; | ||
|
||
req.extensions_mut().insert(user); | ||
Ok(next.run(req).await) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
#[derive(Debug, Clone)] | ||
pub struct Config { | ||
pub database_url: String, | ||
pub jwt_secret: String, | ||
pub jwt_expires_in: String, | ||
pub jwt_maxage: i32, | ||
} | ||
|
||
impl Config { | ||
pub fn init() -> Config { | ||
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); | ||
let jwt_secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set"); | ||
let jwt_expires_in = std::env::var("JWT_EXPIRED_IN").expect("JWT_EXPIRED_IN must be set"); | ||
let jwt_maxage = std::env::var("JWT_MAXAGE").expect("JWT_MAXAGE must be set"); | ||
Config { | ||
database_url, | ||
jwt_secret, | ||
jwt_expires_in, | ||
jwt_maxage: jwt_maxage.parse::<i32>().unwrap(), | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.