Skip to content

Commit

Permalink
venter lige på db migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
sabotack committed Nov 13, 2023
1 parent c4447fe commit ad27cba
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 8 deletions.
52 changes: 47 additions & 5 deletions src/api/ecdar_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ use std::sync::Arc;

use crate::api::ecdar_api::helpers::helpers::{setup_db_with_entities, AnyEntity};
use crate::api::server::server::get_auth_token_request::user_credentials;
use crate::entities::access;

Check warning on line 6 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused import: `crate::entities::access`

warning: unused import: `crate::entities::access` --> src/api/ecdar_api.rs:6:5 | 6 | use crate::entities::access; | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default

Check warning on line 6 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

unused import: `crate::entities::access`

warning: unused import: `crate::entities::access` --> src/api/ecdar_api.rs:6:5 | 6 | use crate::entities::access; | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default

Check warning on line 6 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/Ecdar-API/Ecdar-API/src/api/ecdar_api.rs
use crate::entities::session::Model;
use regex::Regex;
use sea_orm::SqlErr;
use sea_orm::prelude::Uuid;
use tonic::{Code, Request, Response, Status};

use crate::api::server::server::{
Expand Down Expand Up @@ -212,10 +215,12 @@ impl EcdarApiAuth for ConcreteEcdarApi {
let message = request.get_ref().clone();
let uid: String;
let user_from_db: User;
let is_new_session: bool;

if let Some(user_credentials) = message.user_credentials {
if let Some(user) = user_credentials.user {
user_from_db = match user {
// Get user from database by username given in request
user_credentials::User::Username(username) => {
match self.user_context.get_by_username(username).await {
Ok(Some(user)) => user,
Expand All @@ -228,6 +233,7 @@ impl EcdarApiAuth for ConcreteEcdarApi {
Err(err) => return Err(Status::new(Code::Internal, err.to_string())),
}
}
// Get user from database by email given in request
user_credentials::User::Email(email) => {
match self.user_context.get_by_email(email).await {
Ok(Some(user)) => user,
Expand All @@ -241,29 +247,65 @@ impl EcdarApiAuth for ConcreteEcdarApi {
}
}
};

uid = user_from_db.id.to_string();

// Check if password in request matches users password
if user_credentials.password != user_from_db.password {
return Err(Status::new(Code::Unauthenticated, "Wrong password"));
}

uid = user_from_db.id.to_string();

Check warning on line 255 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/Ecdar-API/Ecdar-API/src/api/ecdar_api.rs

is_new_session = true;

} else {
return Err(Status::new(Code::Internal, "No user provided"));
}
} else {
let refresh_token = auth::get_token_from_request(&request)?;
let token_data = auth::validate_token(refresh_token, true)?;
uid = token_data.claims.sub;

is_new_session = false;
}

let access_token = match auth::create_access_token(&uid) {
Ok(token) => token,
Ok(token) => token.to_owned(),
Err(e) => return Err(Status::new(Code::Internal, e.to_string())),
};
let refresh_token = match auth::create_refresh_token(&uid) {
Ok(token) => token,
Ok(token) => token.to_owned(),
Err(e) => return Err(Status::new(Code::Internal, e.to_string())),
};

Check warning on line 277 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/Ecdar-API/Ecdar-API/src/api/ecdar_api.rs

if is_new_session {
self.session_context.create(Model {
id: Default::default(),
access_token: Uuid::parse_str(&access_token).unwrap(),
refresh_token: Uuid::parse_str(&refresh_token).unwrap(),
updated_at: Default::default(),
user_id: uid.parse().unwrap(),
}).await.unwrap();
} else {
let mut session = match self.session_context.get_by_refresh_token(Uuid::parse_str(&refresh_token).unwrap()).await {
Ok(Some(session)) => session,
Ok(None) => {
return Err(Status::new(
Code::Internal,
"No session found with given refresh token",
))
}
Err(err) => return Err(Status::new(Code::Internal, err.to_string())),
};

session.access_token = Uuid::parse_str(&access_token).unwrap();
session.refresh_token = Uuid::parse_str(&refresh_token).unwrap();
session.updated_at = Default::default();

match self.session_context.update(session).await {
Ok(_) => (),
Err(err) => return Err(Status::new(Code::Internal, err.to_string())),
};
}

Ok(Response::new(GetAuthTokenResponse {
access_token,
refresh_token,
Expand Down
24 changes: 21 additions & 3 deletions src/database/session_context.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,40 @@
use std::fmt::Debug;

Check warning on line 1 in src/database/session_context.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/Ecdar-API/Ecdar-API/src/database/session_context.rs

use sea_orm::prelude::Uuid;
use sea_orm::prelude::async_trait::async_trait;
use sea_orm::ActiveValue::{Set, Unchanged};
use sea_orm::{ActiveModelTrait, DbErr, EntityTrait};
use sea_orm::{ActiveModelTrait, DbErr, EntityTrait, QueryFilter, ColumnTrait};

use crate::database::database_context::DatabaseContextTrait;
use crate::database::entity_context::EntityContextTrait;
use crate::entities::prelude::Session as SessionEntity;

Check warning on line 10 in src/database/session_context.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/Ecdar-API/Ecdar-API/src/database/session_context.rs
use crate::entities::session::{ActiveModel, Model as Session};
use crate::entities::session::Column as SessionColumn;

#[derive(Debug)]
pub struct SessionContext {
db_context: Box<dyn DatabaseContextTrait>,
}

pub trait SessionContextTrait: EntityContextTrait<Session> {}
#[async_trait]
pub trait SessionContextTrait: EntityContextTrait<Session> {
async fn get_by_refresh_token(&self, refresh_token: Uuid) -> Result<Option<Session>, DbErr>;
}

impl SessionContextTrait for SessionContext {}
#[async_trait]
impl SessionContextTrait for SessionContext {
/// Returns a session by searching for its refresh_token.
/// # Example
/// ```rust
/// let session: Result<Option<Model>, DbErr> = session_context.get_by_refresh_token(refresh_token).await;
/// ```
async fn get_by_refresh_token(&self, refresh_token: Uuid) -> Result<Option<Session>, DbErr> {
SessionEntity::find()
.filter(SessionColumn::RefreshToken.eq(refresh_token))
.one(&self.db_context.get_connection())
.await
}
}

#[async_trait]
impl EntityContextTrait<Session> for SessionContext {
Expand Down

0 comments on commit ad27cba

Please sign in to comment.