@@ -15,6 +15,8 @@ async-trait.workspace = true
|
||||
uuid.workspace = true
|
||||
anyhow.workspace = true
|
||||
sqlx.workspace = true
|
||||
chrono.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
async-sqlx-session.workspace = true
|
||||
|
||||
|
@@ -0,0 +1,10 @@
|
||||
-- Add migration script here
|
||||
|
||||
CREATE TABLE IF NOT EXISTS projects (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name varchar not null,
|
||||
description varchar default null,
|
||||
user_id varchar not null,
|
||||
created_at timestamp not null,
|
||||
updated_at timestamp not null
|
||||
);
|
17
como_infrastructure/migrations/20230603152353_items.sql
Normal file
17
como_infrastructure/migrations/20230603152353_items.sql
Normal file
@@ -0,0 +1,17 @@
|
||||
-- Add migration script here
|
||||
|
||||
create table if not exists items (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title varchar not null,
|
||||
description varchar default null,
|
||||
state integer not null,
|
||||
user_id varchar not null,
|
||||
project_id UUID not null,
|
||||
created_at timestamp not null,
|
||||
updated_at timestamp not null,
|
||||
CONSTRAINT fk_project
|
||||
FOREIGN KEY(project_id)
|
||||
REFERENCES projects(id)
|
||||
ON DELETE CASCADE
|
||||
)
|
||||
|
@@ -0,0 +1,4 @@
|
||||
-- Add migration script here
|
||||
|
||||
ALTER TABLE items ALTER COLUMN state TYPE varchar(255);
|
||||
|
@@ -1,17 +1,27 @@
|
||||
use clap::ValueEnum;
|
||||
|
||||
#[derive(clap::Parser)]
|
||||
pub struct AppConfig {
|
||||
#[clap(long, env)]
|
||||
pub database_url: String,
|
||||
#[clap(long, env, default_value = "postgres")]
|
||||
pub database_type: DatabaseType,
|
||||
#[clap(long, env)]
|
||||
pub rust_log: String,
|
||||
#[clap(long, env)]
|
||||
pub token_secret: String,
|
||||
#[clap(long, env)]
|
||||
#[clap(long, env, default_value = "3001")]
|
||||
pub api_port: u32,
|
||||
#[clap(long, env)]
|
||||
#[clap(long, env, default_value = "true")]
|
||||
pub run_migrations: bool,
|
||||
#[clap(long, env)]
|
||||
#[clap(long, env, default_value = "false")]
|
||||
pub seed: bool,
|
||||
#[clap(long, env)]
|
||||
pub cors_origin: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, ValueEnum)]
|
||||
pub enum DatabaseType {
|
||||
Postgres,
|
||||
InMemory,
|
||||
}
|
||||
|
@@ -5,10 +5,11 @@ use como_core::{items::DynItemService, projects::DynProjectService, users::DynUs
|
||||
use tracing::log::info;
|
||||
|
||||
use crate::{
|
||||
configs::AppConfig,
|
||||
configs::{AppConfig, DatabaseType},
|
||||
database::ConnectionPool,
|
||||
services::{
|
||||
item_service::MemoryItemService, project_service::MemoryProjectService,
|
||||
item_service::{DefaultItemService, MemoryItemService},
|
||||
project_service::{DefaultProjectService, MemoryProjectService},
|
||||
user_service::DefaultUserService,
|
||||
},
|
||||
};
|
||||
@@ -25,20 +26,42 @@ impl ServiceRegister {
|
||||
pub async fn new(pool: ConnectionPool, config: Arc<AppConfig>) -> anyhow::Result<Self> {
|
||||
info!("creating services");
|
||||
|
||||
let item_service = Arc::new(MemoryItemService::new()) as DynItemService;
|
||||
let project_service = Arc::new(MemoryProjectService::new()) as DynProjectService;
|
||||
let user_service = Arc::new(DefaultUserService::new(pool.clone())) as DynUserService;
|
||||
let store = PostgresSessionStore::new(&config.database_url).await?;
|
||||
let s = match config.database_type {
|
||||
DatabaseType::Postgres => {
|
||||
let item_service =
|
||||
Arc::new(DefaultItemService::new(pool.clone())) as DynItemService;
|
||||
let project_service =
|
||||
Arc::new(DefaultProjectService::new(pool.clone())) as DynProjectService;
|
||||
let user_service =
|
||||
Arc::new(DefaultUserService::new(pool.clone())) as DynUserService;
|
||||
let store = PostgresSessionStore::new(&config.database_url).await?;
|
||||
store.migrate().await?;
|
||||
|
||||
store.migrate().await?;
|
||||
Self {
|
||||
item_service,
|
||||
user_service,
|
||||
project_service,
|
||||
session_store: store,
|
||||
}
|
||||
}
|
||||
DatabaseType::InMemory => {
|
||||
let item_service = Arc::new(MemoryItemService::new()) as DynItemService;
|
||||
let project_service = Arc::new(MemoryProjectService::new()) as DynProjectService;
|
||||
let user_service =
|
||||
Arc::new(DefaultUserService::new(pool.clone())) as DynUserService;
|
||||
let store = PostgresSessionStore::new(&config.database_url).await?;
|
||||
store.migrate().await?;
|
||||
|
||||
Self {
|
||||
item_service,
|
||||
user_service,
|
||||
project_service,
|
||||
session_store: store,
|
||||
}
|
||||
}
|
||||
};
|
||||
info!("services created succesfully");
|
||||
|
||||
Ok(Self {
|
||||
item_service,
|
||||
user_service,
|
||||
project_service,
|
||||
session_store: store,
|
||||
})
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
|
@@ -12,30 +12,114 @@ use como_domain::{
|
||||
responses::CreatedItemDto,
|
||||
ItemDto,
|
||||
},
|
||||
users::User,
|
||||
user::ContextUserExt,
|
||||
Context,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct DefaultItemService {}
|
||||
use crate::database::ConnectionPool;
|
||||
|
||||
pub struct DefaultItemService {
|
||||
pool: ConnectionPool,
|
||||
}
|
||||
|
||||
impl DefaultItemService {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
pub fn new(connection_pool: ConnectionPool) -> Self {
|
||||
Self {
|
||||
pool: connection_pool,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ItemService for DefaultItemService {
|
||||
async fn add_item(&self, _item: CreateItemDto, user: &User) -> anyhow::Result<CreatedItemDto> {
|
||||
todo!()
|
||||
async fn add_item(
|
||||
&self,
|
||||
context: &Context,
|
||||
item: CreateItemDto,
|
||||
) -> anyhow::Result<CreatedItemDto> {
|
||||
let state = serde_json::to_string(&como_domain::item::ItemState::Created {})?;
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO items (id, title, description, state, project_id, user_id, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, now(), now())
|
||||
RETURNING id, title, description, state, project_id
|
||||
"#,
|
||||
Uuid::new_v4(),
|
||||
item.name,
|
||||
item.description,
|
||||
state,
|
||||
item.project_id,
|
||||
user_id,
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(CreatedItemDto {
|
||||
id: rec.id,
|
||||
title: rec.title,
|
||||
description: rec.description,
|
||||
state: como_domain::item::ItemState::Created {},
|
||||
project_id: rec.project_id,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_item(&self, _query: GetItemQuery, user: &User) -> anyhow::Result<ItemDto> {
|
||||
todo!()
|
||||
async fn get_item(&self, context: &Context, query: GetItemQuery) -> anyhow::Result<ItemDto> {
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, title, description, state, project_id
|
||||
FROM items
|
||||
WHERE id = $1 AND user_id = $2
|
||||
"#,
|
||||
query.item_id,
|
||||
user_id,
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(ItemDto {
|
||||
id: rec.id,
|
||||
title: rec.title,
|
||||
description: rec.description,
|
||||
state: serde_json::from_str(&rec.state)?,
|
||||
project_id: rec.project_id,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_items(&self, _query: GetItemsQuery, user: &User) -> anyhow::Result<Vec<ItemDto>> {
|
||||
todo!()
|
||||
async fn get_items(
|
||||
&self,
|
||||
context: &Context,
|
||||
query: GetItemsQuery,
|
||||
) -> anyhow::Result<Vec<ItemDto>> {
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
let recs = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, title, description, state, project_id
|
||||
FROM items
|
||||
WHERE user_id = $1 and project_id = $2
|
||||
LIMIT 500
|
||||
"#,
|
||||
user_id,
|
||||
query.project_id,
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(recs
|
||||
.into_iter()
|
||||
.map(|rec| ItemDto {
|
||||
id: rec.id,
|
||||
title: rec.title,
|
||||
description: rec.description,
|
||||
state: serde_json::from_str(&rec.state).unwrap(),
|
||||
project_id: rec.project_id,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,8 +139,8 @@ impl MemoryItemService {
|
||||
impl ItemService for MemoryItemService {
|
||||
async fn add_item(
|
||||
&self,
|
||||
_context: &Context,
|
||||
create_item: CreateItemDto,
|
||||
user: &User,
|
||||
) -> anyhow::Result<CreatedItemDto> {
|
||||
if let Ok(mut item_store) = self.item_store.lock() {
|
||||
let item = ItemDto {
|
||||
@@ -75,7 +159,7 @@ impl ItemService for MemoryItemService {
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_item(&self, query: GetItemQuery, user: &User) -> anyhow::Result<ItemDto> {
|
||||
async fn get_item(&self, _context: &Context, query: GetItemQuery) -> anyhow::Result<ItemDto> {
|
||||
if let Ok(item_store) = self.item_store.lock() {
|
||||
let item = item_store
|
||||
.get(&query.item_id.to_string())
|
||||
@@ -86,7 +170,11 @@ impl ItemService for MemoryItemService {
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_items(&self, _query: GetItemsQuery, user: &User) -> anyhow::Result<Vec<ItemDto>> {
|
||||
async fn get_items(
|
||||
&self,
|
||||
_context: &Context,
|
||||
_query: GetItemsQuery,
|
||||
) -> anyhow::Result<Vec<ItemDto>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
@@ -4,32 +4,107 @@ use axum::async_trait;
|
||||
use como_core::projects::ProjectService;
|
||||
use como_domain::{
|
||||
projects::{mutation::CreateProjectMutation, queries::GetProjectQuery, ProjectDto},
|
||||
users::User,
|
||||
user::ContextUserExt,
|
||||
Context,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub struct DefaultProjectService {}
|
||||
use crate::database::ConnectionPool;
|
||||
|
||||
pub struct DefaultProjectService {
|
||||
pool: ConnectionPool,
|
||||
}
|
||||
|
||||
impl DefaultProjectService {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
pub fn new(connection_pool: ConnectionPool) -> Self {
|
||||
Self {
|
||||
pool: connection_pool,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ProjectService for DefaultProjectService {
|
||||
async fn get_project(&self, _query: GetProjectQuery) -> anyhow::Result<ProjectDto> {
|
||||
todo!()
|
||||
async fn get_project(
|
||||
&self,
|
||||
context: &Context,
|
||||
query: GetProjectQuery,
|
||||
) -> anyhow::Result<ProjectDto> {
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, name, description, user_id
|
||||
FROM projects
|
||||
WHERE id = $1 and user_id = $2
|
||||
"#,
|
||||
query.project_id,
|
||||
&user_id
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(ProjectDto {
|
||||
id: rec.id,
|
||||
name: rec.name,
|
||||
description: rec.description,
|
||||
user_id: rec.user_id,
|
||||
})
|
||||
}
|
||||
async fn get_projects(&self, user: &User) -> anyhow::Result<Vec<ProjectDto>> {
|
||||
todo!()
|
||||
async fn get_projects(&self, context: &Context) -> anyhow::Result<Vec<ProjectDto>> {
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
let recs = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, name, description, user_id
|
||||
FROM projects
|
||||
WHERE user_id = $1
|
||||
LIMIT 500
|
||||
"#,
|
||||
&user_id
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(recs
|
||||
.into_iter()
|
||||
.map(|rec| ProjectDto {
|
||||
id: rec.id,
|
||||
name: rec.name,
|
||||
description: rec.description,
|
||||
user_id: rec.user_id,
|
||||
})
|
||||
.collect::<_>())
|
||||
}
|
||||
async fn create_project(
|
||||
&self,
|
||||
name: CreateProjectMutation,
|
||||
user: &User,
|
||||
context: &Context,
|
||||
request: CreateProjectMutation,
|
||||
) -> anyhow::Result<ProjectDto> {
|
||||
todo!()
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO projects (id, name, description, user_id, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id
|
||||
"#,
|
||||
uuid::Uuid::new_v4(),
|
||||
request.name,
|
||||
request.description,
|
||||
&user_id,
|
||||
chrono::Utc::now().naive_utc(),
|
||||
chrono::Utc::now().naive_utc(),
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(ProjectDto {
|
||||
id: rec.id,
|
||||
name: request.name,
|
||||
description: request.description,
|
||||
user_id: user_id.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,35 +122,43 @@ impl MemoryProjectService {
|
||||
|
||||
#[async_trait]
|
||||
impl ProjectService for MemoryProjectService {
|
||||
async fn get_project(&self, query: GetProjectQuery) -> anyhow::Result<ProjectDto> {
|
||||
async fn get_project(
|
||||
&self,
|
||||
_context: &Context,
|
||||
query: GetProjectQuery,
|
||||
) -> anyhow::Result<ProjectDto> {
|
||||
let ps = self.project_store.lock().await;
|
||||
Ok(ps
|
||||
.get(&query.project_id.to_string())
|
||||
.ok_or(anyhow::anyhow!("could not find project"))?
|
||||
.clone())
|
||||
}
|
||||
async fn get_projects(&self, user: &User) -> anyhow::Result<Vec<ProjectDto>> {
|
||||
async fn get_projects(&self, context: &Context) -> anyhow::Result<Vec<ProjectDto>> {
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
Ok(self
|
||||
.project_store
|
||||
.lock()
|
||||
.await
|
||||
.values()
|
||||
.filter(|p| p.user_id == user.id)
|
||||
.filter(|p| p.user_id == user_id)
|
||||
.cloned()
|
||||
.collect::<_>())
|
||||
}
|
||||
|
||||
async fn create_project(
|
||||
&self,
|
||||
context: &Context,
|
||||
mutation: CreateProjectMutation,
|
||||
user: &User,
|
||||
) -> anyhow::Result<ProjectDto> {
|
||||
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
|
||||
|
||||
let mut ps = self.project_store.lock().await;
|
||||
let project = ProjectDto {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
name: mutation.name,
|
||||
description: None,
|
||||
user_id: user.id.clone(),
|
||||
user_id,
|
||||
};
|
||||
|
||||
ps.insert(project.id.to_string(), project.clone());
|
||||
|
@@ -1,6 +1,7 @@
|
||||
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
|
||||
use axum::async_trait;
|
||||
use como_core::users::UserService;
|
||||
use como_domain::Context;
|
||||
use rand_core::OsRng;
|
||||
|
||||
use crate::database::ConnectionPool;
|
||||
@@ -14,7 +15,7 @@ impl DefaultUserService {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
fn hash_password(&self, password: String) -> anyhow::Result<String> {
|
||||
fn hash_password(&self, _context: &Context, password: String) -> anyhow::Result<String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
@@ -26,7 +27,12 @@ impl DefaultUserService {
|
||||
Ok(password_hash)
|
||||
}
|
||||
|
||||
fn validate_password(&self, password: String, hashed_password: String) -> anyhow::Result<bool> {
|
||||
fn validate_password(
|
||||
&self,
|
||||
_context: &Context,
|
||||
password: String,
|
||||
hashed_password: String,
|
||||
) -> anyhow::Result<bool> {
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
let parsed_hash = PasswordHash::new(&hashed_password).map_err(|e| anyhow::anyhow!(e))?;
|
||||
@@ -39,8 +45,13 @@ impl DefaultUserService {
|
||||
|
||||
#[async_trait]
|
||||
impl UserService for DefaultUserService {
|
||||
async fn add_user(&self, username: String, password: String) -> anyhow::Result<String> {
|
||||
let hashed_password = self.hash_password(password)?;
|
||||
async fn add_user(
|
||||
&self,
|
||||
context: &Context,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<String> {
|
||||
let hashed_password = self.hash_password(context, password)?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
r#"
|
||||
@@ -59,6 +70,7 @@ impl UserService for DefaultUserService {
|
||||
|
||||
async fn validate_user(
|
||||
&self,
|
||||
context: &Context,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
@@ -73,7 +85,7 @@ impl UserService for DefaultUserService {
|
||||
.await?;
|
||||
|
||||
match rec {
|
||||
Some(user) => match self.validate_password(password, user.password_hash)? {
|
||||
Some(user) => match self.validate_password(context, password, user.password_hash)? {
|
||||
true => Ok(Some(user.id.to_string())),
|
||||
false => Ok(None),
|
||||
},
|
||||
|
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"query": "\n SELECT * from users\n where username=$1\n ",
|
||||
"query": "\n SELECT id, title, description, state, project_id\n FROM items\n WHERE user_id = $1 and project_id = $2\n LIMIT 500\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -9,25 +9,38 @@
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "username",
|
||||
"name": "title",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "password_hash",
|
||||
"name": "description",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "state",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "project_id",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
"Text",
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "d3f222cf6c3d9816705426fdbed3b13cb575bb432eb1f33676c0b414e67aecaf"
|
||||
"hash": "bd2407ffb9637afcff3ffe1101e7c1920b8cf0be423ab0313d14acc9c76e0f93"
|
||||
}
|
Reference in New Issue
Block a user