-
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.
Add AuthMiddleware and change password
- Loading branch information
Showing
20 changed files
with
373 additions
and
178 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
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
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
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
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,107 @@ | ||
use actix_web::body::BoxBody; | ||
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform}; | ||
use actix_web::{Error, HttpResponse}; | ||
use futures_util::future::{ok, LocalBoxFuture, Ready}; | ||
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; | ||
use serde::Deserialize; | ||
use std::fs::File; | ||
use std::io::Read; | ||
use std::rc::Rc; | ||
use std::sync::Arc; | ||
use std::task::{Context, Poll}; | ||
use tokio::sync::RwLock; | ||
|
||
#[derive(Debug, Deserialize)] | ||
#[allow(dead_code)] | ||
struct Claims { | ||
sub: String, | ||
exp: usize, | ||
} | ||
|
||
pub struct AuthMiddleware; | ||
|
||
pub struct CheckAuthMiddleware<S> { | ||
service: Rc<S>, | ||
decoding_key: Arc<RwLock<DecodingKey>>, | ||
} | ||
|
||
impl<S> Transform<S, ServiceRequest> for AuthMiddleware | ||
where | ||
S: Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> + 'static, | ||
S::Future: 'static, | ||
{ | ||
type Response = ServiceResponse<BoxBody>; | ||
type Error = Error; | ||
type Transform = CheckAuthMiddleware<S>; | ||
type InitError = (); | ||
type Future = Ready<Result<Self::Transform, Self::InitError>>; | ||
|
||
fn new_transform(&self, service: S) -> Self::Future { | ||
let jwt_secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "secret".to_string()); | ||
let decoding_key = AuthMiddleware::new_from_file(&jwt_secret).expect("Failed to load key"); | ||
ok(CheckAuthMiddleware { | ||
service: Rc::new(service), | ||
decoding_key: Arc::new(RwLock::new(decoding_key)), | ||
}) | ||
} | ||
} | ||
|
||
impl<S> Service<ServiceRequest> for CheckAuthMiddleware<S> | ||
where | ||
S: Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> + 'static, | ||
S::Future: 'static, | ||
{ | ||
type Response = ServiceResponse<BoxBody>; | ||
type Error = Error; | ||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; | ||
|
||
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
Poll::Ready(Ok(())) | ||
} | ||
|
||
fn call(&self, req: ServiceRequest) -> Self::Future { | ||
let service = Rc::clone(&self.service); | ||
let decoding_key = self.decoding_key.clone(); | ||
|
||
Box::pin(async move { | ||
let auth_header = req.headers().get("Authorization"); | ||
|
||
if req.path() == "/login" || req.path() == "/register" || req.path() == "/" { | ||
return Ok(req.into_response(HttpResponse::Ok().finish())); | ||
} | ||
|
||
if let Some(auth_header) = auth_header { | ||
if let Ok(auth_token) = auth_header.to_str() { | ||
if let Some(auth_str) = auth_token.strip_prefix("Bearer ") { | ||
let token = &auth_str[7..]; | ||
|
||
let decoding_key = decoding_key.read().await; | ||
|
||
return match decode::<Claims>( | ||
token, | ||
&decoding_key, | ||
&Validation::new(Algorithm::HS256), | ||
) { | ||
Ok(_) => service.call(req).await, | ||
Err(_) => Ok(req.into_response(HttpResponse::Unauthorized().finish())), | ||
}; | ||
} | ||
} | ||
} | ||
|
||
Ok(req.into_response(HttpResponse::Unauthorized().finish())) | ||
}) | ||
} | ||
} | ||
|
||
impl AuthMiddleware { | ||
pub fn new_from_file(path: &str) -> Result<DecodingKey, std::io::Error> { | ||
let mut file = File::open(path)?; | ||
let mut key_data = Vec::new(); | ||
file.read_to_end(&mut key_data)?; | ||
|
||
let decoding_key = DecodingKey::from_secret(&key_data); | ||
|
||
Ok(decoding_key) | ||
} | ||
} |
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 @@ | ||
pub mod auth; |
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,83 @@ | ||
use crate::consts::{AUDIENCE, GRANT_TYPE_PASS}; | ||
use crate::user_flow::auth0_models::{ChangePassFlow, ConnectToAuth0, LoginFlow, RegistrationFlow}; | ||
use serde::{Deserialize, Serialize}; | ||
use uuid::Uuid; | ||
|
||
#[derive(Serialize, Deserialize, Debug, Clone)] | ||
pub struct Auth0Service { | ||
pub client_id: String, | ||
pub client_secret: String, | ||
pub connection: String, | ||
pub client_url: String, | ||
} | ||
|
||
impl Auth0Service { | ||
pub fn new( | ||
client_id: String, | ||
client_secret: String, | ||
connection: String, | ||
client_url: String, | ||
) -> Self { | ||
Auth0Service { | ||
client_id, | ||
client_secret, | ||
connection, | ||
client_url, | ||
} | ||
} | ||
|
||
pub fn generate_body_for_registration( | ||
&self, | ||
user_id: Uuid, | ||
username: String, | ||
password: String, | ||
email: String, | ||
) -> ConnectToAuth0<RegistrationFlow> { | ||
ConnectToAuth0 { | ||
client_id: self.client_id.clone(), | ||
client_secret: self.client_secret.clone(), | ||
audience: AUDIENCE.to_string(), | ||
grant_type: GRANT_TYPE_PASS.to_string(), | ||
user_id: user_id.to_string(), | ||
connection: self.connection.clone(), | ||
extra: RegistrationFlow { | ||
username, | ||
password, | ||
email, | ||
}, | ||
} | ||
} | ||
|
||
pub async fn generate_body_for_login( | ||
&self, | ||
user_id: Uuid, | ||
username: String, | ||
password: String, | ||
) -> ConnectToAuth0<LoginFlow> { | ||
ConnectToAuth0 { | ||
client_id: self.client_id.clone(), | ||
client_secret: self.client_secret.clone(), | ||
audience: AUDIENCE.to_string(), | ||
grant_type: GRANT_TYPE_PASS.to_string(), | ||
user_id: user_id.to_string(), | ||
connection: self.connection.clone(), | ||
extra: LoginFlow { username, password }, | ||
} | ||
} | ||
|
||
pub async fn generate_body_for_change_password( | ||
&self, | ||
user_id: Uuid, | ||
email: String, | ||
) -> ConnectToAuth0<ChangePassFlow> { | ||
ConnectToAuth0 { | ||
client_id: self.client_id.clone(), | ||
client_secret: self.client_secret.clone(), | ||
audience: AUDIENCE.to_string(), | ||
grant_type: GRANT_TYPE_PASS.to_string(), | ||
user_id: user_id.to_string(), | ||
connection: self.connection.clone(), | ||
extra: ChangePassFlow { email }, | ||
} | ||
} | ||
} |
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 @@ | ||
pub mod auth0; |
Oops, something went wrong.