Skip to content

Commit

Permalink
Refactor code, add login for getting token
Browse files Browse the repository at this point in the history
  • Loading branch information
Daelon022 committed May 12, 2024
1 parent b5ab349 commit 5da0318
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 10 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Cargo.lock
*.pdb
.idea
.env
*.pem


# Added by cargo
Expand Down
13 changes: 8 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@ diesel = { version = "=2.1.4", features = [
diesel-derive-enum = { version = "2.0.0-rc.0", features = ["postgres"] }
diesel-async = { version = "0.4.1", features = ["postgres", "deadpool"] }
tokio = "1.36.0"
thiserror = "1.0.57"
uuid = { version = "1.7.0", features = ["v4", "serde"] }
thiserror = "1.0.58"
uuid = { version = "1.8.0", features = ["v4", "serde"] }
chrono = "0.4.35"
reqwest = { version = "0.11.25", features = ["json"] }
reqwest = { version = "0.12.1", features = ["json"] }
log = "0.4.21"
anyhow = "1.0.80"
anyhow = "1.0.81"
fern = "0.6.2"
colored = "2.1.0"
dotenv = "0.15.0"
jsonwebtoken = "9.2.0"
jsonwebtoken = "9.3.0"
http = "1.1.0"
openssl = "0.10.64"
alcoholic_jwt = "4091.0.0"
15 changes: 15 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,21 @@ pub enum Error {

#[error(transparent)]
SerdeJsonError(#[from] serde_json::Error),

#[error(transparent)]
ToStrError(#[from] actix_web::http::header::ToStrError),

#[error(transparent)]
DotenvError(#[from] dotenv::Error),

#[error(transparent)]
JsonWebTokenError(#[from] jsonwebtoken::errors::Error),

#[error(transparent)]
ErrorStackError(#[from] openssl::error::ErrorStack),

#[error(transparent)]
AlcoholicJwtValidationError(#[from] alcoholic_jwt::ValidationError),
}

pub type Result<T> = std::result::Result<T, Error>;
Expand Down
2 changes: 1 addition & 1 deletion src/user_flow/auth0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::consts::{ACCESS_TOKEN, APPLICATION_JSON, AUDIENCE, CONTENT_TYPE, GRAN
use crate::errors::Error;
use crate::models::{ConnectToAuth0, LoginFlow, RegisteredUserData, RegistrationFlow, UserData};
use crate::user_flow::consts::{LOGIN_URL, REGISTRATION_URL};
use actix_web::http::Method;
use http::Method;
use reqwest::Client;
use serde_json::Value;
use uuid::Uuid;
Expand Down
4 changes: 2 additions & 2 deletions src/user_flow/consts.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub const REGISTRATION_URL: &str = "/dbconnections/signup";
pub const LOGIN_URL: &str = "/oauth/token";
pub const REGISTRATION_URL: &str = "dbconnections/signup";
pub const LOGIN_URL: &str = "oauth/token";
2 changes: 2 additions & 0 deletions src/user_flow/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
pub mod auth0;
pub mod consts;
mod models;
pub mod requests;
pub mod utils;
8 changes: 8 additions & 0 deletions src/user_flow/models.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct Claims {
pub sub: String,
pub email: String,
pub username: String,
}
23 changes: 21 additions & 2 deletions src/user_flow/requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ use crate::actors::messages::{CheckIfRegisteredUser, CheckUser, CreateUser};
use crate::db::postgres_db::DbService;
use crate::models::{RegisteredUserData, UserData};
use crate::user_flow::auth0::{get_jwt_user_token, register_user};
use crate::user_flow::utils::fetch_jwks;
use actix::Addr;
use actix_web::web::{Data, Json};
use actix_web::HttpResponse;
use actix_web::{HttpRequest, HttpResponse};
use alcoholic_jwt::{token_kid, validate, Validation};
use uuid::Uuid;

pub async fn register(
Expand Down Expand Up @@ -52,7 +54,24 @@ pub async fn login(
}
}

pub async fn check_token(_db: Data<DbService>) -> crate::errors::Result<HttpResponse> {
pub async fn check_token(req: HttpRequest) -> crate::errors::Result<HttpResponse> {
log::info!("Getting request for checking token!");
let token = req
.headers()
.get("Authorization")
.expect("Cannot find Auth header")
.to_str()?;
let authority = std::env::var("CLIENT").expect("AUTHORITY must be set");
let uri = &format!("{}{}", authority.as_str(), ".well-known/jwks.json");
log::info!("Fetching JWKS from: {}", uri);
let jwks = fetch_jwks(uri).await?;
let validations = vec![Validation::Issuer(authority), Validation::SubjectPresent];
let kid = match token_kid(token) {
Ok(res) => res.expect("failed to decode kid"),
Err(e) => return Err(crate::errors::Error::AlcoholicJwtValidationError(e)),
};
let jwk = jwks.find(&kid).expect("Specified key not found in set");
let res = validate(token, jwk, validations)?;
log::info!("Token: {:?}", res.claims);
Ok(HttpResponse::Ok().finish())
}
17 changes: 17 additions & 0 deletions src/user_flow/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use crate::errors::Result;
use alcoholic_jwt::JWKS;
use std::fs::File;
use std::io::Read;

pub fn load_pem_cert(file_path: &str) -> Result<Vec<u8>> {
let mut file = File::open(file_path)?;
let mut pem_cert = Vec::new();
file.read_to_end(&mut pem_cert)?;
Ok(pem_cert)
}

pub async fn fetch_jwks(uri: &str) -> Result<JWKS> {
let res = reqwest::get(uri).await?;
let val = res.json::<JWKS>().await?;
Ok(val)
}

0 comments on commit 5da0318

Please sign in to comment.