Skip to content

Commit

Permalink
fix: async trait for impl block
Browse files Browse the repository at this point in the history
  • Loading branch information
zainen committed Nov 2, 2024
1 parent fbf72ba commit 7259a51
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 35 deletions.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,14 @@ docker compose build
docker compose up
```

visit http://localhost:8000 and http://localhost:3000
visit http://localhost:8000 and http://localhost:3000

# Run servers locally Docker
```bash
./dockersh.sh
```

## Generate secret
```bash
openssl rand -base64 64
```
21 changes: 11 additions & 10 deletions auth-service/src/domain/data_stores.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
use super::{Email, Password, User};

#[async_trait::async_trait]
pub trait BannedTokenStore: Send + Sync {
fn add_token(&mut self, token: String) -> Result<(), BannedTokenStoreError>;
fn verify_token_exists(&self, token: &str) -> Result<bool, BannedTokenStoreError>;
}

#[async_trait::async_trait]
pub trait UserStore: Send + Sync {
fn add_user(&mut self, user: User) -> Result<(), UserStoreError>;
fn get_user(&self, email: Email) -> Result<&User, UserStoreError>;
fn verify_user(&self, email: &Email, password: &Password) -> Result<(), UserStoreError>;
pub trait UserStore {
async fn add_user(&mut self, user: User) -> Result<(), UserStoreError>;
async fn get_user(&self, email: Email) -> Result<&User, UserStoreError>;
async fn verify_user(&self, email: &Email, password: &Password) -> Result<(), UserStoreError>;
}

#[derive(Debug, PartialEq)]
Expand All @@ -21,6 +15,13 @@ pub enum UserStoreError {
UnexpectedError,
}


#[async_trait::async_trait]
pub trait BannedTokenStore {
async fn add_token(&mut self, token: String) -> Result<(), BannedTokenStoreError>;
async fn verify_token_exists(&self, token: &str) -> Result<bool, BannedTokenStoreError>;
}

#[derive(Debug, PartialEq)]
pub enum BannedTokenStoreError {
TokenAlreadyExists,
Expand Down
4 changes: 2 additions & 2 deletions auth-service/src/routes/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ pub async fn login(
let user_store = state.user_store.read().await;

if user_store
.verify_user(&email, &password)
.verify_user(&email, &password).await
.is_err()
{
return (jar, Err(AuthAPIError::IncorrectCredentials));
}

match user_store.get_user(email) {
match user_store.get_user(email).await{
Ok(user) => {
let response = Json(LoginResponse {
message: "User Login Successful!".to_string(),
Expand Down
2 changes: 1 addition & 1 deletion auth-service/src/routes/logout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub async fn logout(
Err(e) => return (jar, Err(AuthAPIError::InvalidToken)),
};

match state.banned_tokens_store.write().await.add_token(token) {
match state.banned_tokens_store.write().await.add_token(token).await {
Err(_) => (jar, Err(AuthAPIError::UnexpectedError)),
Ok(_) => {
let jar = jar.remove(JWT_COOKIE_NAME);
Expand Down
4 changes: 2 additions & 2 deletions auth-service/src/routes/signup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ pub async fn signup(

let mut user_store = state.user_store.write().await;

match user_store.get_user(user.email.clone()) {
match user_store.get_user(user.email.clone()).await {
Err(_) => {}
Ok(_) => return Err(AuthAPIError::UserAlreadyExists),
};

let result = user_store.add_user(user);
let result = user_store.add_user(user).await;

match result {
Err(_) => return Err(AuthAPIError::UnexpectedError),
Expand Down
1 change: 0 additions & 1 deletion auth-service/src/routes/verify_token.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use axum_extra::extract::CookieJar;
use serde::Deserialize;

use crate::{store::AppState, utils::auth::validate_token};
Expand Down
12 changes: 6 additions & 6 deletions auth-service/src/services/hashmap_banned_token_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub struct HashmapBannedTokenStore {

#[async_trait::async_trait]
impl BannedTokenStore for HashmapBannedTokenStore {
fn add_token(&mut self, token: String) -> Result<(), crate::domain::BannedTokenStoreError> {
async fn add_token(&mut self, token: String) -> Result<(), crate::domain::BannedTokenStoreError> {
if token.is_empty() {
return Err(BannedTokenStoreError::TokenNotFound);
}
Expand All @@ -21,7 +21,7 @@ impl BannedTokenStore for HashmapBannedTokenStore {
Ok(())
}

fn verify_token_exists(&self, token: &str) -> Result<bool, crate::domain::BannedTokenStoreError> {
async fn verify_token_exists(&self, token: &str) -> Result<bool, crate::domain::BannedTokenStoreError> {
if token.is_empty() {
return Err(BannedTokenStoreError::TokenNotFound);
}
Expand Down Expand Up @@ -51,7 +51,7 @@ mod tests {
.expect("Token gen failed");

let result = store
.add_token(token.value().to_string())
.add_token(token.value().to_string()).await
.expect("Token failed");

assert_eq!(result, ())
Expand All @@ -63,7 +63,7 @@ mod tests {
tokens: HashMap::new(),
};

let result = store.add_token("".to_string());
let result = store.add_token("".to_string()).await;

assert_eq!(result, Err(BannedTokenStoreError::TokenNotFound))
}
Expand All @@ -79,12 +79,12 @@ mod tests {
.expect("Token gen failed");

let result = store
.add_token(token.value().to_string())
.add_token(token.value().to_string()).await
.expect("Token failed");

assert_eq!(result, ());

let result = store.add_token(token.value().to_string());
let result = store.add_token(token.value().to_string()).await;

assert_eq!(result, Err(BannedTokenStoreError::TokenAlreadyExists))
}
Expand Down
19 changes: 10 additions & 9 deletions auth-service/src/services/hashmap_user_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ pub struct HashmapUserStore {
pub users: HashMap<Email, User>,
}

#[async_trait::async_trait]
impl UserStore for HashmapUserStore {
fn add_user(&mut self, user: User) -> Result<(), UserStoreError> {
async fn add_user(&mut self, user: User) -> Result<(), UserStoreError> {
if let Some(_) = self.users.get(&user.email) {
Err(UserStoreError::UserAlreadyExists)
} else {
Expand All @@ -18,15 +19,15 @@ impl UserStore for HashmapUserStore {
}
}

fn get_user(&self, email: Email) -> Result<&User, UserStoreError> {
async fn get_user(&self, email: Email) -> Result<&User, UserStoreError> {
if let Some(found_user) = self.users.get(&email) {
Ok(found_user)
} else {
Err(UserStoreError::UserNotFound)
}
}

fn verify_user(&self, email: &Email, password: &Password) -> Result<(), UserStoreError> {
async fn verify_user(&self, email: &Email, password: &Password) -> Result<(), UserStoreError> {
match self.users.get(email) {
Some(user) => {
if &user.password == password {
Expand Down Expand Up @@ -58,7 +59,7 @@ mod tests {
requires_2fa: false,
};

let result = store.add_user(user);
let result = store.add_user(user).await;

assert_eq!(result.unwrap(), ());
}
Expand All @@ -75,7 +76,7 @@ mod tests {
};
let inserted_user_result = store.add_user(user);

assert_eq!(inserted_user_result.unwrap(), ());
assert_eq!(inserted_user_result.await.unwrap(), ());

// keep clone off of the User Struct
let user = User {
Expand All @@ -92,7 +93,7 @@ mod tests {
requires_2fa: false,
};

assert_eq!(found_user.unwrap().email, user.email)
assert_eq!(found_user.await.unwrap().email, user.email)
}

#[tokio::test]
Expand All @@ -107,7 +108,7 @@ mod tests {
requires_2fa: false,
};

let _inserted_user_result = store.add_user(user).unwrap();
let _inserted_user_result = store.add_user(user).await.unwrap();

let user = User {
email: Email::parse("ok@email.com".to_owned()).unwrap(),
Expand All @@ -121,13 +122,13 @@ mod tests {
password: Password::parse("longenough".to_owned()).unwrap(),
requires_2fa: false,
};
let found_user = found_user.unwrap();
let found_user = found_user.await.unwrap();

assert_eq!(found_user.email, user.email);
assert_eq!(found_user.password, user.password);

let results = store.verify_user(&user.email, &user.password);

assert_eq!(results.unwrap(), ());
assert_eq!(results.await.unwrap(), ());
}
}
6 changes: 3 additions & 3 deletions auth-service/src/utils/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ fn generate_auth_token(email: &Email) -> Result<String, GenerateTokenError> {
}

pub async fn validate_token(banned_tokens: &BannedTokenStoreType ,token: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
match banned_tokens.read().await.verify_token_exists(token) {
match banned_tokens.read().await.verify_token_exists(token).await {
Err(_) => return Err(jsonwebtoken::errors::Error::from(jsonwebtoken::errors::ErrorKind::InvalidToken)),
Ok(value) => {
if value {
Expand Down Expand Up @@ -146,9 +146,9 @@ mod tests {
let email = Email::parse("test@test.com".to_owned()).unwrap();
let token = generate_auth_token(&email).unwrap();

store.add_token(token.clone()).expect("Failed to add token");
store.add_token(token.clone()).await.expect("Failed to add token");

let result = store.add_token(token);
let result = store.add_token(token).await;

assert_eq!(result, Err(crate::domain::BannedTokenStoreError::TokenAlreadyExists))
}
Expand Down

0 comments on commit 7259a51

Please sign in to comment.