Skip to content

Commit

Permalink
merge main
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderManich committed Nov 29, 2023
2 parents 8216dff + bacc6ce commit a52319e
Show file tree
Hide file tree
Showing 18 changed files with 357 additions and 32 deletions.
6 changes: 4 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
POSTGRES_TEST_IP=localhost
POSTGRES_DEV_IP=localhost
POSTGRES_TEST_PORT=5433
POSTGRES_DEV_PORT=5432

POSTGRES_DB=ecdar_api
POSTGRES_PASSWORD=1234

DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@localhost:${POSTGRES_DEV_PORT}/${POSTGRES_DB}
TEST_DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@localhost:${POSTGRES_TEST_PORT}/${POSTGRES_DB}
DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@${POSTGRES_DEV_IP}:${POSTGRES_DEV_PORT}/${POSTGRES_DB}
TEST_DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@${POSTGRES_TEST_IP}:${POSTGRES_TEST_PORT}/${POSTGRES_DB}
# TEST_DATABASE_URL=sqlite::memory:

REVEAAL_ADDRESS=http://{IP}:{PORT}
Expand Down
2 changes: 1 addition & 1 deletion Ecdar-ProtoBuf
Submodule Ecdar-ProtoBuf updated 2 files
+14 −8 api.proto
+2 −2 services.proto
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ Prerequisites:

Set up docker postgresql db:
- `docker-compose up -d`
- `DATABASE_URL=postgresql://postgres:{POSTGRES_PASSWORD}@localhost:{POSTGRES_DEV_PORT}/{POSTGRES_DB} sea-orm-cli migrate up`
- `DATABASE_URL=postgresql://postgres:{POSTGRES_PASSWORD}@localhost:{POSTGRES_TEST_PORT}/{POSTGRES_DB} sea-orm-cli migrate up`
- `DATABASE_URL=postgresql://postgres:{POSTGRES_PASSWORD}@{POSTGRES_DEV_IP}:{POSTGRES_DEV_PORT}/{POSTGRES_DB} sea-orm-cli migrate up`
- `DATABASE_URL=postgresql://postgres:{POSTGRES_PASSWORD}@{POSTGRES_TEST_IP}:{POSTGRES_TEST_PORT}/{POSTGRES_DB} sea-orm-cli migrate up`

After modifying DB:
- `sea-orm-cli migrate fresh`
Expand Down
99 changes: 92 additions & 7 deletions src/api/ecdar_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use super::server::server::{
CreateAccessRequest, CreateModelRequest, CreateModelResponse, CreateQueryRequest,
CreateUserRequest, DeleteAccessRequest, DeleteModelRequest, DeleteQueryRequest,
GetAuthTokenRequest, GetAuthTokenResponse, GetModelRequest, GetModelResponse,
ListAccessInfoResponse, Query, QueryRequest, QueryResponse, SimulationStartRequest,
ListModelsInfoResponse, QueryRequest, QueryResponse, SimulationStartRequest,
SimulationStepRequest, SimulationStepResponse, UpdateAccessRequest, UpdateQueryRequest,
UpdateUserRequest, UserTokenResponse,
};
Expand Down Expand Up @@ -241,18 +241,99 @@ impl EcdarApi for ConcreteEcdarApi {
todo!()
}

/// Deletes a Model from the database.
///
/// # Errors
/// This function will return an error if the model does not exist in the database
/// or if the user is not the model owner.
async fn delete_model(
&self,
_request: Request<DeleteModelRequest>,
request: Request<DeleteModelRequest>,
) -> Result<Response<()>, Status> {
todo!()
let uid = request
.uid()
.ok_or(Status::internal("Could not get uid from request metadata"))?;
let model_id = request.get_ref().id;

let model = match self.contexts.model_context.get_by_id(model_id).await {
Ok(Some(model)) => model,
Ok(None) => return Err(Status::new(Code::NotFound, "No model found with given id")),
Err(err) => return Err(Status::new(Code::Internal, err.to_string())),
};

// Check if user is owner and thereby has permission to delete model
if model.owner_id != uid {
return Err(Status::new(
Code::PermissionDenied,
"You do not have permission to delete this model",
));
}

match self.contexts.model_context.delete(model_id).await {
Ok(_) => Ok(Response::new(())),
Err(error) => match error {
sea_orm::DbErr::RecordNotFound(message) => {
Err(Status::new(Code::NotFound, message))
}
_ => Err(Status::new(Code::Internal, error.to_string())),
},
}
}

async fn list_access_info(
async fn list_models_info(
&self,
_request: Request<()>,
) -> Result<Response<ListAccessInfoResponse>, Status> {
todo!()
request: Request<()>,
) -> Result<Response<ListModelsInfoResponse>, Status> {
let uid = request
.uid()
.ok_or(Status::internal("Could not get uid from request metadata"))?;

match self
.contexts
.model_context
.get_models_info_by_uid(uid)
.await
{
Ok(model_info_list) => {
if model_info_list.is_empty() {
return Err(Status::new(
Code::NotFound,
"No access found for given user",
));
} else {
Ok(Response::new(ListModelsInfoResponse { model_info_list }))
}
}
Err(error) => Err(Status::new(Code::Internal, error.to_string())),
}
/*let mut model_info_list_vector: Vec<ModelInfo> = Vec::new(); // Initialize the Vec
// Get all the models that the user has access to
match self.model_context.get_model_info_by_uid(uid).await {
Ok(model_info_list) => {
for model_info in model_info_list {
let model_info_test = ModelInfo {
model_id: model_info.model_id,
model_name: model_info.model_name,
model_owner_id: model_info.model_owner_id,
user_role_on_model: model_info.user_role_on_model,
};
model_info_list_vector.push(model_info_test);
}
if model_info_list_vector.is_empty() {
return Err(Status::new(
Code::NotFound,
"No access found for given user",
));
} else {
Ok(Response::new(ListModelInfoResponse {
model_info_list: model_info_list_vector,
}))
}
}
Err(error) => Err(Status::new(Code::Internal, error.to_string())),
}*/
}

/// Creates an access in the database.
Expand Down Expand Up @@ -673,6 +754,10 @@ mod model_logic_tests;
#[path = "../tests/api/user_logic.rs"]
mod user_logic_tests;

#[cfg(test)]
#[path = "../tests/api/model_logic.rs"]
mod model_logic_tests;

Check failure on line 759 in src/api/ecdar_api.rs

View workflow job for this annotation

GitHub Actions / Clippy lint and check

the name `model_logic_tests` is defined multiple times

error[E0428]: the name `model_logic_tests` is defined multiple times --> src/api/ecdar_api.rs:759:1 | 751 | mod model_logic_tests; | ---------------------- previous definition of the module `model_logic_tests` here ... 759 | mod model_logic_tests; | ^^^^^^^^^^^^^^^^^^^^^^ `model_logic_tests` redefined here | = note: `model_logic_tests` must be defined only once in the type namespace of this module

#[cfg(test)]
#[path = "../tests/api/session_logic.rs"]
mod session_logic_tests;
1 change: 1 addition & 0 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ fn main() {
"Component",
"#[derive(serde::Serialize, serde::Deserialize)]",
)
.type_attribute("ModelInfo", "#[derive(sea_orm::FromQueryResult)]")
.enum_attribute("rep", "#[derive(serde::Serialize, serde::Deserialize)]")
.compile(&["Ecdar-ProtoBuf/services.proto"], &["Ecdar-ProtoBuf/"])
.unwrap();
Expand Down
51 changes: 47 additions & 4 deletions src/database/model_context.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,60 @@
use crate::database::database_context::DatabaseContextTrait;
use crate::entities::{model, query};
use crate::entities::{access, model, query};

use crate::api::server::server::ModelInfo;
use crate::EntityContextTrait;
use async_trait::async_trait;
use sea_orm::{ActiveModelTrait, DbErr, EntityTrait, IntoActiveModel, ModelTrait, Set, Unchanged};
use sea_orm::{
ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, IntoActiveModel, JoinType, ModelTrait,
QueryFilter, QuerySelect, RelationTrait, Set, Unchanged,
};
use std::sync::Arc;

pub struct ModelContext {
db_context: Arc<dyn DatabaseContextTrait>,
}

pub trait ModelContextTrait: EntityContextTrait<model::Model> {}
#[async_trait]
pub trait ModelContextTrait: EntityContextTrait<model::Model> {
async fn get_models_info_by_uid(&self, uid: i32) -> Result<Vec<ModelInfo>, DbErr>;
}

#[async_trait]
impl ModelContextTrait for ModelContext {
async fn get_models_info_by_uid(&self, uid: i32) -> Result<Vec<ModelInfo>, DbErr> {
/*let querytest = access::Entity::find()
.select_only()
.column_as(model::Column::Id, "model_id")
.column_as(model::Column::Name, "model_name")
.column_as(model::Column::OwnerId, "model_owner_id")
.column_as(access::Column::Role, "user_role_on_model")
.join(JoinType::InnerJoin, access::Relation::Model.def())
.join(JoinType::InnerJoin, access::Relation::Role.def())
.group_by(model::Column::Id)
.group_by(access::Column::Role)
.filter(access::Column::UserId.eq(uid))
.build(DbBackend::Postgres)
.to_string();
println!("SQL Query: {}", querytest);*/

impl ModelContextTrait for ModelContext {}
//join model, access and role tables
access::Entity::find()
.select_only()
.column_as(model::Column::Id, "model_id")
.column_as(model::Column::Name, "model_name")
.column_as(model::Column::OwnerId, "model_owner_id")
.column_as(access::Column::Role, "user_role_on_model")
.join(JoinType::InnerJoin, access::Relation::Model.def())
.join(JoinType::InnerJoin, access::Relation::Role.def())
.group_by(model::Column::Id)
.group_by(access::Column::Role)
.filter(access::Column::UserId.eq(uid))
.into_model::<ModelInfo>()
.all(&self.db_context.get_connection())
.await
}
}

impl ModelContext {
pub fn new(db_context: Arc<dyn DatabaseContextTrait>) -> ModelContext {
Expand Down
2 changes: 1 addition & 1 deletion src/entities/access.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
use sea_orm::entity::prelude::*;

Expand Down
2 changes: 1 addition & 1 deletion src/entities/in_use.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
use sea_orm::entity::prelude::*;

Expand Down
2 changes: 1 addition & 1 deletion src/entities/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
pub mod prelude;

Expand Down
2 changes: 1 addition & 1 deletion src/entities/model.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
use sea_orm::entity::prelude::*;

Expand Down
2 changes: 1 addition & 1 deletion src/entities/prelude.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
pub use super::access::Entity as Access;
pub use super::in_use::Entity as InUse;
Expand Down
2 changes: 1 addition & 1 deletion src/entities/query.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
use sea_orm::entity::prelude::*;

Expand Down
2 changes: 1 addition & 1 deletion src/entities/role.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
use sea_orm::entity::prelude::*;

Expand Down
2 changes: 1 addition & 1 deletion src/entities/session.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
use sea_orm::entity::prelude::*;

Expand Down
2 changes: 1 addition & 1 deletion src/entities/user.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.4
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.6
use sea_orm::entity::prelude::*;

Expand Down
5 changes: 4 additions & 1 deletion src/tests/api/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::api::context_collection::ContextCollection;
use crate::api::ecdar_api::ConcreteEcdarApi;
use crate::api::hashing_context::HashingContextTrait;
use crate::api::server::server::ecdar_backend_server::EcdarBackend;
use crate::api::server::server::ModelInfo;
use crate::api::server::server::{
QueryRequest, QueryResponse, SimulationStartRequest, SimulationStepRequest,
SimulationStepResponse, UserTokenResponse,
Expand Down Expand Up @@ -115,7 +116,9 @@ mock! {
async fn delete(&self, entity_id: i32) -> Result<model::Model, DbErr>;
}
#[async_trait]
impl ModelContextTrait for ModelContext {}
impl ModelContextTrait for ModelContext {
async fn get_models_info_by_uid(&self, uid: i32) -> Result<Vec<ModelInfo>, DbErr>;
}
}

mock! {
Expand Down
Loading

0 comments on commit a52319e

Please sign in to comment.