Compare commits
8 Commits
8c51b68523
...
v0.1.0
Author | SHA1 | Date | |
---|---|---|---|
c58c888725
|
|||
78b9732ca1
|
|||
1d4cda7c48
|
|||
c7f8dc6198
|
|||
5e9001b998
|
|||
ae74f66c3a
|
|||
6234cf18e8
|
|||
b01b33f7d1
|
7
.env
7
.env
@@ -1,4 +1,11 @@
|
||||
POSTGRES_DB=como
|
||||
POSTGRES_USER=como
|
||||
POSTGRES_PASSWORD=somenotverysecurepassword
|
||||
|
||||
DATABASE_URL="postgres://como:somenotverysecurepassword@localhost:5432/como"
|
||||
RUST_LOG=como_api=info,como_bin=info,como_core=info,como_domain=info,como_gql=info,como_infrastructure=info,sqlx=debug,tower_http=debug
|
||||
TOKEN_SECRET=something
|
||||
API_PORT=3001
|
||||
CORS_ORIGIN=http://localhost:3000
|
||||
RUN_MIGRATIONS=true
|
||||
SEED=true
|
||||
|
789
Cargo.lock
generated
789
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,9 @@
|
||||
[workspace]
|
||||
members = ["como_bin", "como_core", "como_domain"]
|
||||
members = [
|
||||
"como_bin",
|
||||
"como_core",
|
||||
"como_domain",
|
||||
"como_infrastructure",
|
||||
"como_gql",
|
||||
"como_api",
|
||||
]
|
||||
|
39
como_api/Cargo.toml
Normal file
39
como_api/Cargo.toml
Normal file
@@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "como_api"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
como_gql = { path = "../como_gql" }
|
||||
como_core = { path = "../como_core" }
|
||||
como_domain = { path = "../como_domain" }
|
||||
como_infrastructure = { path = "../como_infrastructure" }
|
||||
|
||||
async-graphql = "4.0.6"
|
||||
async-graphql-axum = "*"
|
||||
axum = "0.5.13"
|
||||
axum-extra = { version = "*", features = ["cookie", "cookie-private"] }
|
||||
axum-sessions = { version = "*" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0.68"
|
||||
|
||||
tokio = { version = "1.20.1", features = ["full"] }
|
||||
uuid = { version = "1.1.2", features = ["v4", "fast-rng"] }
|
||||
sqlx = { version = "0.6", features = [
|
||||
"runtime-tokio-rustls",
|
||||
"postgres",
|
||||
"migrate",
|
||||
"uuid",
|
||||
"offline",
|
||||
] }
|
||||
anyhow = "1.0.60"
|
||||
dotenv = "0.15.0"
|
||||
tracing = "0.1.36"
|
||||
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
|
||||
argon2 = "0.4"
|
||||
rand_core = { version = "0.6", features = ["std"] }
|
||||
cookie = { version = "0.16", features = ["secure", "percent-encode"] }
|
||||
tower = { version = "0.4", features = ["timeout"] }
|
||||
tower-http = { version = "0.3", features = ["trace", "cors"] }
|
21
como_api/src/controllers/graphql.rs
Normal file
21
como_api/src/controllers/graphql.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use async_graphql::{EmptySubscription, Schema};
|
||||
use axum::{routing::get, Extension, Router};
|
||||
use como_gql::{
|
||||
graphql::{MutationRoot, QueryRoot},
|
||||
graphql_handler, graphql_playground,
|
||||
};
|
||||
use como_infrastructure::register::ServiceRegister;
|
||||
|
||||
pub struct GraphQLController;
|
||||
|
||||
impl GraphQLController {
|
||||
pub fn new_router(service_register: ServiceRegister) -> Router {
|
||||
let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription)
|
||||
.data(service_register)
|
||||
.finish();
|
||||
|
||||
Router::new()
|
||||
.route("/", get(graphql_playground).post(graphql_handler))
|
||||
.layer(Extension(schema))
|
||||
}
|
||||
}
|
1
como_api/src/controllers/mod.rs
Normal file
1
como_api/src/controllers/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod graphql;
|
2
como_api/src/lib.rs
Normal file
2
como_api/src/lib.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
mod controllers;
|
||||
pub mod router;
|
44
como_api/src/router.rs
Normal file
44
como_api/src/router.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use anyhow::Context;
|
||||
use axum::{
|
||||
http::{HeaderValue, Method},
|
||||
Router,
|
||||
};
|
||||
use como_infrastructure::register::ServiceRegister;
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::{cors::CorsLayer, trace::TraceLayer};
|
||||
|
||||
use crate::controllers::graphql::GraphQLController;
|
||||
|
||||
pub struct Api;
|
||||
|
||||
impl Api {
|
||||
pub async fn run_api(
|
||||
port: u32,
|
||||
cors_origin: &str,
|
||||
service_register: ServiceRegister,
|
||||
) -> anyhow::Result<()> {
|
||||
let router = Router::new()
|
||||
.nest(
|
||||
"/graphql",
|
||||
GraphQLController::new_router(service_register.clone()),
|
||||
)
|
||||
.layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))
|
||||
.layer(
|
||||
CorsLayer::new()
|
||||
.allow_origin(
|
||||
cors_origin
|
||||
.parse::<HeaderValue>()
|
||||
.context("could not parse cors origin as header")?,
|
||||
)
|
||||
.allow_headers([axum::http::header::CONTENT_TYPE])
|
||||
.allow_methods([Method::GET, Method::POST, Method::OPTIONS]),
|
||||
);
|
||||
|
||||
axum::Server::bind(&format!("0.0.0.0:{}", port).parse().unwrap())
|
||||
.serve(router.into_make_service())
|
||||
.await
|
||||
.context("error while starting API")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
@@ -6,6 +6,12 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
como_gql = { path = "../como_gql" }
|
||||
como_core = { path = "../como_core" }
|
||||
como_domain = { path = "../como_domain" }
|
||||
como_infrastructure = { path = "../como_infrastructure" }
|
||||
como_api = { path = "../como_api" }
|
||||
|
||||
async-graphql = "4.0.6"
|
||||
async-graphql-axum = "*"
|
||||
axum = "0.5.13"
|
||||
@@ -30,3 +36,4 @@ tower-http = { version = "0.3.4", features = ["full"] }
|
||||
argon2 = "0.4"
|
||||
rand_core = { version = "0.6", features = ["std"] }
|
||||
cookie = { version = "0.16", features = ["secure", "percent-encode"] }
|
||||
clap = { version = "3", features = ["derive", "env"] }
|
||||
|
@@ -1,6 +0,0 @@
|
||||
// generated by `sqlx migrate build-script`
|
||||
fn main() {
|
||||
// trigger recompilation when a new migration is added
|
||||
println!("cargo:rerun-if-changed=migrations");
|
||||
}
|
||||
|
@@ -1,56 +0,0 @@
|
||||
{
|
||||
"db": "PostgreSQL",
|
||||
"3b4484c5ccfd4dcb887c4e978fe6e45d4c9ecc2a73909be207dced79ddf17d87": {
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"nullable": [
|
||||
false
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Varchar",
|
||||
"Varchar"
|
||||
]
|
||||
}
|
||||
},
|
||||
"query": "\n INSERT INTO users (username, password_hash) \n VALUES ( $1, $2 ) \n RETURNING id\n "
|
||||
},
|
||||
"d3f222cf6c3d9816705426fdbed3b13cb575bb432eb1f33676c0b414e67aecaf": {
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"name": "username",
|
||||
"ordinal": 1,
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"name": "password_hash",
|
||||
"ordinal": 2,
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
}
|
||||
},
|
||||
"query": "\n SELECT * from users\n where username=$1\n "
|
||||
}
|
||||
}
|
@@ -1,6 +1,7 @@
|
||||
use axum::{http::StatusCode, response::IntoResponse, Json};
|
||||
use serde_json::json;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum AppError {
|
||||
WrongCredentials,
|
||||
|
@@ -1,2 +0,0 @@
|
||||
pub mod users;
|
||||
|
@@ -1,106 +0,0 @@
|
||||
use async_graphql::{Context, EmptySubscription, Object, Schema, SimpleObject};
|
||||
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::services::users_service::UserService;
|
||||
|
||||
pub type CibusSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>;
|
||||
|
||||
pub struct MutationRoot;
|
||||
|
||||
#[Object]
|
||||
impl MutationRoot {
|
||||
async fn login(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<bool> {
|
||||
let user_service = ctx.data_unchecked::<UserService>();
|
||||
|
||||
let valid = user_service.validate_user(username, password).await?;
|
||||
let returnvalid = match valid {
|
||||
Some(..) => true,
|
||||
None => false,
|
||||
};
|
||||
|
||||
Ok(returnvalid)
|
||||
}
|
||||
|
||||
async fn register(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<String> {
|
||||
let user_service = ctx.data_unchecked::<UserService>();
|
||||
|
||||
let user_id = user_service.add_user(username, password).await?;
|
||||
|
||||
Ok(user_id)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct QueryRoot;
|
||||
|
||||
#[Object]
|
||||
impl QueryRoot {
|
||||
async fn get_upcoming(&self, _ctx: &Context<'_>) -> Vec<Event> {
|
||||
vec![Event::new(
|
||||
None,
|
||||
"Some-name".into(),
|
||||
None,
|
||||
None,
|
||||
EventDate::new(2022, 08, 08, 23, 51),
|
||||
)]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(SimpleObject)]
|
||||
pub struct Event {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub date: EventDate,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn new(
|
||||
id: Option<String>,
|
||||
name: String,
|
||||
description: Option<Vec<String>>,
|
||||
location: Option<String>,
|
||||
date: EventDate,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: id.unwrap_or_else(|| Uuid::new_v4().to_string()),
|
||||
name,
|
||||
description,
|
||||
location,
|
||||
date,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(SimpleObject)]
|
||||
pub struct EventDate {
|
||||
pub year: u32,
|
||||
pub month: u32,
|
||||
pub day: u32,
|
||||
pub hour: u32,
|
||||
pub minute: u32,
|
||||
}
|
||||
|
||||
impl EventDate {
|
||||
pub fn new(year: u32, month: u32, day: u32, hour: u32, minute: u32) -> Self {
|
||||
Self {
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,175 +1,41 @@
|
||||
use std::env::{self, current_dir};
|
||||
use std::sync::Arc;
|
||||
|
||||
mod error;
|
||||
mod gqlx;
|
||||
mod graphql;
|
||||
mod services;
|
||||
|
||||
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
|
||||
use axum::{
|
||||
extract::Extension,
|
||||
http::{Method, StatusCode},
|
||||
response::{Html, IntoResponse},
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use axum_extra::extract::cookie::Key;
|
||||
use clap::Parser;
|
||||
|
||||
use async_graphql::{
|
||||
http::{playground_source, GraphQLPlaygroundConfig},
|
||||
EmptySubscription, Schema,
|
||||
use anyhow::Context;
|
||||
|
||||
use como_api::router::Api;
|
||||
use como_infrastructure::{
|
||||
configs::AppConfig, database::ConnectionPoolManager, register::ServiceRegister,
|
||||
};
|
||||
use axum_sessions::{
|
||||
async_session::MemoryStore,
|
||||
extractors::{ReadableSession, WritableSession},
|
||||
SessionLayer,
|
||||
};
|
||||
use error::AppError;
|
||||
use graphql::CibusSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use services::users_service;
|
||||
use sqlx::PgPool;
|
||||
use tower_http::{cors::CorsLayer, trace::TraceLayer};
|
||||
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
use crate::graphql::{MutationRoot, QueryRoot};
|
||||
|
||||
async fn graphql_handler(
|
||||
schema: Extension<CibusSchema>,
|
||||
session: ReadableSession,
|
||||
req: GraphQLRequest,
|
||||
) -> Result<GraphQLResponse, StatusCode> {
|
||||
let req = req.into_inner();
|
||||
//if let Some(user_id) = session.get::<String>("userId") {
|
||||
// req = req.data(user_id);
|
||||
return Ok(schema.execute(req).await.into());
|
||||
//} else if let Some(on) = &req.operation_name {
|
||||
// if on == "IntrospectionQuery" {
|
||||
// return Ok(schema.execute(req).await.into());
|
||||
// }
|
||||
//}
|
||||
|
||||
//Err(StatusCode::FORBIDDEN)
|
||||
}
|
||||
|
||||
async fn graphql_playground() -> impl IntoResponse {
|
||||
Html(playground_source(GraphQLPlaygroundConfig::new("/")))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
// Environment
|
||||
tracing::info!("Loading dotenv");
|
||||
dotenv::dotenv()?;
|
||||
|
||||
// Logging
|
||||
let config = Arc::new(AppConfig::parse());
|
||||
|
||||
tracing_subscriber::registry()
|
||||
.with(tracing_subscriber::EnvFilter::new(
|
||||
std::env::var("RUST_LOG").unwrap_or_else(|_| {
|
||||
"como_bin=debug,tower_http=debug,axum_extra=debug,hyper=info,mio=info,sqlx=info,async_graphql=debug"
|
||||
.into()
|
||||
}),
|
||||
))
|
||||
.with(tracing_subscriber::EnvFilter::new(&config.rust_log))
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
.init();
|
||||
|
||||
// Database
|
||||
tracing::info!("Creating pool");
|
||||
let db_url = env::var("DATABASE_URL")?;
|
||||
let pool = PgPool::connect(&db_url).await?;
|
||||
let pool = ConnectionPoolManager::new_pool(&config.database_url, true).await?;
|
||||
|
||||
// Database Migrate
|
||||
tracing::info!("Migrating db");
|
||||
sqlx::migrate!("db/migrations").run(&pool).await?;
|
||||
let service_register = ServiceRegister::new(pool, config.clone());
|
||||
|
||||
tracing::info!("current path: {}", current_dir()?.to_string_lossy());
|
||||
|
||||
// Schema
|
||||
println!("Building schema");
|
||||
let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription)
|
||||
.data(users_service::UserService::new(pool.clone()))
|
||||
.finish();
|
||||
|
||||
// CORS
|
||||
let cors = vec!["http://localhost:3000".parse().unwrap()];
|
||||
|
||||
// Key
|
||||
let key = Key::generate();
|
||||
|
||||
let store = MemoryStore::new();
|
||||
let session_layer = SessionLayer::new(store, key.master());
|
||||
|
||||
// Webserver
|
||||
tracing::info!("Building router");
|
||||
let app = Router::new()
|
||||
.route("/", get(graphql_playground).post(graphql_handler))
|
||||
.route("/auth/login", post(login))
|
||||
.route("/auth/register", post(register))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(Extension(schema))
|
||||
.layer(Extension(key))
|
||||
.layer(Extension(pool))
|
||||
.layer(session_layer)
|
||||
.layer(
|
||||
CorsLayer::new()
|
||||
.allow_origin(cors)
|
||||
.allow_headers([axum::http::header::CONTENT_TYPE])
|
||||
.allow_methods([Method::GET, Method::POST, Method::OPTIONS]),
|
||||
);
|
||||
|
||||
tracing::info!("Starting webserver");
|
||||
axum::Server::bind(&"0.0.0.0:3001".parse().unwrap())
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
Api::run_api(
|
||||
config.api_port,
|
||||
&config.cors_origin,
|
||||
service_register.clone(),
|
||||
)
|
||||
.await
|
||||
.context("could not initialize API")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Credentials {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
async fn login(
|
||||
Json(credentials): Json<Credentials>,
|
||||
Extension(pool): Extension<PgPool>,
|
||||
mut session: WritableSession,
|
||||
) -> Result<Json<Value>, error::AppError> {
|
||||
let us = users_service::UserService::new(pool);
|
||||
match us
|
||||
.validate_user(credentials.username, credentials.password)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("could not validate user: {}", e);
|
||||
|
||||
AppError::InternalServerError
|
||||
})? {
|
||||
Some(user_id) => {
|
||||
if let Err(e) = session.insert("userId", user_id.clone()) {
|
||||
tracing::error!("could not insert session: {}", e);
|
||||
return Err(AppError::InternalServerError);
|
||||
}
|
||||
|
||||
Ok(Json(json!({ "userId": user_id })))
|
||||
}
|
||||
None => Err(AppError::WrongCredentials),
|
||||
}
|
||||
}
|
||||
async fn register(
|
||||
Json(credentials): Json<Credentials>,
|
||||
Extension(pool): Extension<PgPool>,
|
||||
) -> Result<Json<Value>, error::AppError> {
|
||||
let us = users_service::UserService::new(pool)
|
||||
.add_user(credentials.username, credentials.password)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("could not add user: {}", e);
|
||||
|
||||
AppError::InternalServerError
|
||||
})?;
|
||||
|
||||
Ok(Json(json!({ "userId": us })))
|
||||
}
|
||||
|
@@ -1 +0,0 @@
|
||||
pub mod users_service;
|
@@ -6,3 +6,26 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
como_domain = { path = "../como_domain" }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
axum = "0.5.1"
|
||||
|
||||
# utilty crates
|
||||
serde = { version = "1.0.136", features = ["derive"] }
|
||||
sqlx = { version = "0.5", features = [
|
||||
"runtime-tokio-rustls",
|
||||
"postgres",
|
||||
"time",
|
||||
] }
|
||||
serde_json = "1.0.81"
|
||||
dotenv = "0.15.0"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
anyhow = "1"
|
||||
validator = { version = "0.15", features = ["derive"] }
|
||||
async-trait = "0.1"
|
||||
thiserror = "1"
|
||||
rust-argon2 = "1.0"
|
||||
clap = { version = "3", features = ["derive", "env"] }
|
||||
mockall = "0.11.1"
|
||||
time = "0.2"
|
||||
|
18
como_core/src/items/mod.rs
Normal file
18
como_core/src/items/mod.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use como_domain::item::{
|
||||
queries::{GetItemQuery, GetItemsQuery},
|
||||
requests::CreateItemDto,
|
||||
responses::CreatedItemDto,
|
||||
ItemDto,
|
||||
};
|
||||
|
||||
pub type DynItemService = Arc<dyn ItemService + Send + Sync>;
|
||||
|
||||
#[async_trait]
|
||||
pub trait ItemService {
|
||||
async fn add_item(&self, item: CreateItemDto) -> anyhow::Result<CreatedItemDto>;
|
||||
async fn get_item(&self, query: GetItemQuery) -> anyhow::Result<ItemDto>;
|
||||
async fn get_items(&self, query: GetItemsQuery) -> anyhow::Result<Vec<ItemDto>>;
|
||||
}
|
@@ -1,2 +1,3 @@
|
||||
|
||||
|
||||
pub mod items;
|
||||
pub mod projects;
|
||||
pub mod users;
|
||||
|
15
como_core/src/projects/mod.rs
Normal file
15
como_core/src/projects/mod.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use como_domain::projects::{
|
||||
queries::{GetProjectQuery, GetProjectsQuery},
|
||||
ProjectDto,
|
||||
};
|
||||
|
||||
pub type DynProjectService = Arc<dyn ProjectService + Send + Sync>;
|
||||
|
||||
#[async_trait]
|
||||
pub trait ProjectService {
|
||||
async fn get_project(&self, query: GetProjectQuery) -> anyhow::Result<ProjectDto>;
|
||||
async fn get_projects(&self, query: GetProjectsQuery) -> anyhow::Result<Vec<ProjectDto>>;
|
||||
}
|
15
como_core/src/users/mod.rs
Normal file
15
como_core/src/users/mod.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
pub type DynUserService = Arc<dyn UserService + Send + Sync>;
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserService {
|
||||
async fn add_user(&self, username: String, password: String) -> anyhow::Result<String>;
|
||||
async fn validate_user(
|
||||
&self,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<Option<String>>;
|
||||
}
|
@@ -6,7 +6,8 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
async-graphql = { version = "4.0.6", features = ["uuid"] }
|
||||
anyhow = "1.0.60"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0.68"
|
||||
uuid = { version = "1.1.2", features = ["v4", "fast-rng"] }
|
||||
uuid = { version = "1.1.2", features = ["v4", "fast-rng", "serde"] }
|
||||
|
23
como_domain/src/item/mod.rs
Normal file
23
como_domain/src/item/mod.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
pub mod queries;
|
||||
pub mod requests;
|
||||
pub mod responses;
|
||||
|
||||
use async_graphql::{Enum, InputObject};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Enum, Copy)]
|
||||
pub enum ItemState {
|
||||
Created,
|
||||
Done,
|
||||
Archived,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
|
||||
pub struct ItemDto {
|
||||
pub id: Uuid,
|
||||
pub title: String,
|
||||
pub description: Option<String>,
|
||||
pub state: ItemState,
|
||||
}
|
13
como_domain/src/item/queries.rs
Normal file
13
como_domain/src/item/queries.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use async_graphql::InputObject;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
|
||||
pub struct GetItemQuery {
|
||||
pub item_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
|
||||
pub struct GetItemsQuery {
|
||||
pub user_id: Uuid,
|
||||
}
|
7
como_domain/src/item/requests.rs
Normal file
7
como_domain/src/item/requests.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
use async_graphql::InputObject;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
|
||||
pub struct CreateItemDto {
|
||||
pub name: String,
|
||||
}
|
3
como_domain/src/item/responses.rs
Normal file
3
como_domain/src/item/responses.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
use super::ItemDto;
|
||||
|
||||
pub type CreatedItemDto = ItemDto;
|
@@ -1 +1,3 @@
|
||||
pub mod item;
|
||||
pub mod projects;
|
||||
pub mod users;
|
||||
|
@@ -0,0 +1,13 @@
|
||||
pub mod queries;
|
||||
pub mod requests;
|
||||
pub mod responses;
|
||||
|
||||
use async_graphql::{InputObject, SimpleObject};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject, SimpleObject)]
|
||||
pub struct ProjectDto {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
14
como_domain/src/projects/queries.rs
Normal file
14
como_domain/src/projects/queries.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use async_graphql::InputObject;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
|
||||
pub struct GetProjectQuery {
|
||||
pub project_id: Option<Uuid>,
|
||||
pub item_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
|
||||
pub struct GetProjectsQuery {
|
||||
pub user_id: Uuid,
|
||||
}
|
6
como_domain/src/projects/requests.rs
Normal file
6
como_domain/src/projects/requests.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct CreateProjectDto {
|
||||
pub name: String,
|
||||
}
|
3
como_domain/src/projects/responses.rs
Normal file
3
como_domain/src/projects/responses.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
use super::ProjectDto;
|
||||
|
||||
pub type CreatedProjectDto = ProjectDto;
|
@@ -1,11 +1,11 @@
|
||||
pub mod requests;
|
||||
pub mod responses;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UserDto {
|
||||
#[serde(skip_serializing, skip_deserializing)]
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
pub email: String,
|
||||
|
@@ -0,0 +1,3 @@
|
||||
use super::UserDto;
|
||||
|
||||
pub type UserCreatedDto = UserDto;
|
||||
|
36
como_gql/Cargo.toml
Normal file
36
como_gql/Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "como_gql"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
como_core = { path = "../como_core" }
|
||||
como_domain = { path = "../como_domain" }
|
||||
como_infrastructure = { path = "../como_infrastructure" }
|
||||
|
||||
async-graphql = "4.0.6"
|
||||
async-graphql-axum = "*"
|
||||
axum = "0.5.13"
|
||||
axum-extra = { version = "*", features = ["cookie", "cookie-private"] }
|
||||
axum-sessions = { version = "*" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0.68"
|
||||
tokio = { version = "1.20.1", features = ["full"] }
|
||||
uuid = { version = "1.1.2", features = ["v4", "fast-rng"] }
|
||||
sqlx = { version = "0.6", features = [
|
||||
"runtime-tokio-rustls",
|
||||
"postgres",
|
||||
"migrate",
|
||||
"uuid",
|
||||
"offline",
|
||||
] }
|
||||
anyhow = "1.0.60"
|
||||
dotenv = "0.15.0"
|
||||
tracing = "0.1.36"
|
||||
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
|
||||
tower-http = { version = "0.3.4", features = ["full"] }
|
||||
argon2 = "0.4"
|
||||
rand_core = { version = "0.6", features = ["std"] }
|
||||
cookie = { version = "0.16", features = ["secure", "percent-encode"] }
|
125
como_gql/src/graphql.rs
Normal file
125
como_gql/src/graphql.rs
Normal file
@@ -0,0 +1,125 @@
|
||||
use async_graphql::{Context, EmptySubscription, Object, Schema};
|
||||
|
||||
use como_domain::{
|
||||
item::{
|
||||
queries::{GetItemQuery, GetItemsQuery},
|
||||
requests::CreateItemDto,
|
||||
},
|
||||
projects::{
|
||||
queries::{GetProjectQuery, GetProjectsQuery},
|
||||
ProjectDto,
|
||||
},
|
||||
};
|
||||
use como_infrastructure::register::ServiceRegister;
|
||||
|
||||
use crate::items::{CreatedItem, Item};
|
||||
|
||||
pub type ComoSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>;
|
||||
|
||||
pub struct MutationRoot;
|
||||
|
||||
#[Object]
|
||||
impl MutationRoot {
|
||||
async fn login(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<bool> {
|
||||
let service_register = ctx.data_unchecked::<ServiceRegister>();
|
||||
|
||||
let valid = service_register
|
||||
.user_service
|
||||
.validate_user(username, password)
|
||||
.await?;
|
||||
let returnvalid = match valid {
|
||||
Some(..) => true,
|
||||
None => false,
|
||||
};
|
||||
|
||||
Ok(returnvalid)
|
||||
}
|
||||
|
||||
async fn register(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
username: String,
|
||||
password: String,
|
||||
) -> anyhow::Result<String> {
|
||||
let service_register = ctx.data_unchecked::<ServiceRegister>();
|
||||
|
||||
let user_id = service_register
|
||||
.user_service
|
||||
.add_user(username, password)
|
||||
.await?;
|
||||
|
||||
Ok(user_id)
|
||||
}
|
||||
|
||||
async fn create_item(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
item: CreateItemDto,
|
||||
) -> anyhow::Result<CreatedItem> {
|
||||
let services_register = ctx.data_unchecked::<ServiceRegister>();
|
||||
|
||||
let created_item = services_register.item_service.add_item(item).await?;
|
||||
|
||||
Ok(CreatedItem {
|
||||
id: created_item.id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct QueryRoot;
|
||||
|
||||
#[Object]
|
||||
impl QueryRoot {
|
||||
// Items
|
||||
async fn get_item(&self, ctx: &Context<'_>, query: GetItemQuery) -> anyhow::Result<Item> {
|
||||
let item = ctx
|
||||
.data_unchecked::<ServiceRegister>()
|
||||
.item_service
|
||||
.get_item(query)
|
||||
.await?;
|
||||
|
||||
Ok(Item::from(item))
|
||||
}
|
||||
|
||||
async fn get_items(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
query: GetItemsQuery,
|
||||
) -> anyhow::Result<Vec<Item>> {
|
||||
let items = ctx
|
||||
.data_unchecked::<ServiceRegister>()
|
||||
.item_service
|
||||
.get_items(query)
|
||||
.await?;
|
||||
|
||||
Ok(items.iter().map(|i| Item::from(i.clone())).collect())
|
||||
}
|
||||
|
||||
// Projects
|
||||
async fn get_project(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
query: GetProjectQuery,
|
||||
) -> anyhow::Result<ProjectDto> {
|
||||
ctx.data_unchecked::<ServiceRegister>()
|
||||
.project_service
|
||||
.get_project(query)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_projects(
|
||||
&self,
|
||||
ctx: &Context<'_>,
|
||||
query: GetProjectsQuery,
|
||||
) -> anyhow::Result<Vec<ProjectDto>> {
|
||||
ctx.data_unchecked::<ServiceRegister>()
|
||||
.project_service
|
||||
.get_projects(query)
|
||||
.await
|
||||
}
|
||||
}
|
76
como_gql/src/items.rs
Normal file
76
como_gql/src/items.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use async_graphql::{Context, Object};
|
||||
use como_domain::{
|
||||
item::{queries::GetItemQuery, ItemDto, ItemState},
|
||||
projects::queries::GetProjectQuery,
|
||||
};
|
||||
use como_infrastructure::register::ServiceRegister;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::projects::Project;
|
||||
|
||||
pub struct CreatedItem {
|
||||
pub id: Uuid,
|
||||
}
|
||||
|
||||
#[Object]
|
||||
impl CreatedItem {
|
||||
pub async fn item(&self, ctx: &Context<'_>) -> anyhow::Result<Item> {
|
||||
let item = ctx
|
||||
.data_unchecked::<ServiceRegister>()
|
||||
.item_service
|
||||
.get_item(GetItemQuery { item_id: self.id })
|
||||
.await?;
|
||||
|
||||
Ok(item.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Item {
|
||||
pub id: Uuid,
|
||||
pub title: String,
|
||||
pub description: Option<String>,
|
||||
pub state: ItemState,
|
||||
}
|
||||
|
||||
#[Object]
|
||||
impl Item {
|
||||
pub async fn id(&self, _ctx: &Context<'_>) -> anyhow::Result<Uuid> {
|
||||
Ok(self.id)
|
||||
}
|
||||
|
||||
pub async fn title(&self, _ctx: &Context<'_>) -> anyhow::Result<String> {
|
||||
Ok(self.title.clone())
|
||||
}
|
||||
|
||||
pub async fn description(&self, _ctx: &Context<'_>) -> anyhow::Result<Option<String>> {
|
||||
Ok(self.description.clone())
|
||||
}
|
||||
|
||||
pub async fn state(&self, _ctx: &Context<'_>) -> anyhow::Result<ItemState> {
|
||||
Ok(self.state)
|
||||
}
|
||||
|
||||
pub async fn project(&self, ctx: &Context<'_>) -> anyhow::Result<Project> {
|
||||
let project = ctx
|
||||
.data_unchecked::<ServiceRegister>()
|
||||
.project_service
|
||||
.get_project(GetProjectQuery {
|
||||
item_id: Some(self.id),
|
||||
project_id: None,
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(project.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ItemDto> for Item {
|
||||
fn from(dto: ItemDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
title: dto.title,
|
||||
description: dto.description,
|
||||
state: dto.state,
|
||||
}
|
||||
}
|
||||
}
|
26
como_gql/src/lib.rs
Normal file
26
como_gql/src/lib.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
|
||||
use axum::{
|
||||
extract::Extension,
|
||||
http::StatusCode,
|
||||
response::{Html, IntoResponse},
|
||||
};
|
||||
|
||||
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
|
||||
use graphql::ComoSchema;
|
||||
|
||||
pub mod graphql;
|
||||
mod items;
|
||||
mod projects;
|
||||
|
||||
pub async fn graphql_handler(
|
||||
schema: Extension<ComoSchema>,
|
||||
req: GraphQLRequest,
|
||||
) -> Result<GraphQLResponse, StatusCode> {
|
||||
let req = req.into_inner();
|
||||
|
||||
Ok(schema.execute(req).await.into())
|
||||
}
|
||||
|
||||
pub async fn graphql_playground() -> impl IntoResponse {
|
||||
Html(playground_source(GraphQLPlaygroundConfig::new("/graphql")))
|
||||
}
|
18
como_gql/src/projects.rs
Normal file
18
como_gql/src/projects.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use async_graphql::SimpleObject;
|
||||
use como_domain::projects::ProjectDto;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(SimpleObject)]
|
||||
pub struct Project {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl From<ProjectDto> for Project {
|
||||
fn from(dto: ProjectDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
}
|
||||
}
|
||||
}
|
36
como_infrastructure/Cargo.toml
Normal file
36
como_infrastructure/Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "como_infrastructure"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
como_core = { path = "../como_core" }
|
||||
como_domain = { path = "../como_domain" }
|
||||
|
||||
async-graphql = "4.0.6"
|
||||
async-graphql-axum = "*"
|
||||
axum = "0.5.13"
|
||||
axum-extra = { version = "*", features = ["cookie", "cookie-private"] }
|
||||
axum-sessions = { version = "*" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0.68"
|
||||
tokio = { version = "1.20.1", features = ["full"] }
|
||||
uuid = { version = "1.1.2", features = ["v4", "fast-rng"] }
|
||||
sqlx = { version = "0.6", features = [
|
||||
"runtime-tokio-rustls",
|
||||
"postgres",
|
||||
"migrate",
|
||||
"uuid",
|
||||
"offline",
|
||||
] }
|
||||
anyhow = "1.0.60"
|
||||
dotenv = "0.15.0"
|
||||
tracing = "0.1.36"
|
||||
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
|
||||
tower-http = { version = "0.3.4", features = ["full"] }
|
||||
argon2 = "0.4"
|
||||
rand_core = { version = "0.6", features = ["std"] }
|
||||
cookie = { version = "0.16", features = ["secure", "percent-encode"] }
|
||||
clap = { version = "3", features = ["derive", "env"] }
|
17
como_infrastructure/src/configs/mod.rs
Normal file
17
como_infrastructure/src/configs/mod.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
#[derive(clap::Parser)]
|
||||
pub struct AppConfig {
|
||||
#[clap(long, env)]
|
||||
pub database_url: String,
|
||||
#[clap(long, env)]
|
||||
pub rust_log: String,
|
||||
#[clap(long, env)]
|
||||
pub token_secret: String,
|
||||
#[clap(long, env)]
|
||||
pub api_port: u32,
|
||||
#[clap(long, env)]
|
||||
pub run_migrations: bool,
|
||||
#[clap(long, env)]
|
||||
pub seed: bool,
|
||||
#[clap(long, env)]
|
||||
pub cors_origin: String,
|
||||
}
|
33
como_infrastructure/src/database/mod.rs
Normal file
33
como_infrastructure/src/database/mod.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use anyhow::Context;
|
||||
use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
|
||||
use tracing::log::info;
|
||||
|
||||
pub type ConnectionPool = Pool<Postgres>;
|
||||
|
||||
pub struct ConnectionPoolManager;
|
||||
|
||||
impl ConnectionPoolManager {
|
||||
pub async fn new_pool(
|
||||
connection_string: &str,
|
||||
run_migrations: bool,
|
||||
) -> anyhow::Result<ConnectionPool> {
|
||||
info!("initializing the database connection pool");
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(connection_string)
|
||||
.await
|
||||
.context("error while initializing the database connection pool")?;
|
||||
|
||||
if run_migrations {
|
||||
info!("migrations enabled");
|
||||
info!("migrating database");
|
||||
|
||||
sqlx::migrate!()
|
||||
.run(&pool)
|
||||
.await
|
||||
.context("error while running database migrations")?;
|
||||
}
|
||||
|
||||
Ok(pool)
|
||||
}
|
||||
}
|
5
como_infrastructure/src/lib.rs
Normal file
5
como_infrastructure/src/lib.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub mod configs;
|
||||
pub mod database;
|
||||
pub mod register;
|
||||
pub mod repositories;
|
||||
pub mod services;
|
38
como_infrastructure/src/register.rs
Normal file
38
como_infrastructure/src/register.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use como_core::{items::DynItemService, projects::DynProjectService, users::DynUserService};
|
||||
use tracing::log::info;
|
||||
|
||||
use crate::{
|
||||
configs::AppConfig,
|
||||
database::ConnectionPool,
|
||||
services::{
|
||||
item_service::MemoryItemService, project_service::MemoryProjectService,
|
||||
user_service::DefaultUserService,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ServiceRegister {
|
||||
pub item_service: DynItemService,
|
||||
pub project_service: DynProjectService,
|
||||
pub user_service: DynUserService,
|
||||
}
|
||||
|
||||
impl ServiceRegister {
|
||||
pub fn new(pool: ConnectionPool, _config: Arc<AppConfig>) -> 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)) as DynUserService;
|
||||
|
||||
info!("services created succesfully");
|
||||
|
||||
Self {
|
||||
item_service,
|
||||
user_service,
|
||||
project_service,
|
||||
}
|
||||
}
|
||||
}
|
97
como_infrastructure/src/services/item_service.rs
Normal file
97
como_infrastructure/src/services/item_service.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use axum::async_trait;
|
||||
use como_core::items::ItemService;
|
||||
use como_domain::item::{
|
||||
queries::{GetItemQuery, GetItemsQuery},
|
||||
requests::CreateItemDto,
|
||||
responses::CreatedItemDto,
|
||||
ItemDto,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct DefaultItemService {}
|
||||
|
||||
impl DefaultItemService {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DefaultItemService {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ItemService for DefaultItemService {
|
||||
async fn add_item(&self, _item: CreateItemDto) -> anyhow::Result<CreatedItemDto> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn get_item(&self, _query: GetItemQuery) -> anyhow::Result<ItemDto> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn get_items(&self, _query: GetItemsQuery) -> anyhow::Result<Vec<ItemDto>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MemoryItemService {
|
||||
item_store: Arc<Mutex<HashMap<String, ItemDto>>>,
|
||||
}
|
||||
|
||||
impl MemoryItemService {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
item_store: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for MemoryItemService {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ItemService for MemoryItemService {
|
||||
async fn add_item(&self, create_item: CreateItemDto) -> anyhow::Result<CreatedItemDto> {
|
||||
if let Ok(mut item_store) = self.item_store.lock() {
|
||||
let item = ItemDto {
|
||||
id: Uuid::new_v4(),
|
||||
title: create_item.name,
|
||||
description: None,
|
||||
state: como_domain::item::ItemState::Created,
|
||||
};
|
||||
|
||||
item_store.insert(item.id.to_string(), item.clone());
|
||||
|
||||
return Ok(item);
|
||||
} else {
|
||||
Err(anyhow::anyhow!("could not unlock item_store"))
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_item(&self, query: GetItemQuery) -> anyhow::Result<ItemDto> {
|
||||
if let Ok(item_store) = self.item_store.lock() {
|
||||
let item = item_store
|
||||
.get(&query.item_id.to_string())
|
||||
.context("could not find item")?;
|
||||
return Ok(item.clone());
|
||||
} else {
|
||||
Err(anyhow::anyhow!("could not unlock item_store"))
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_items(&self, _query: GetItemsQuery) -> anyhow::Result<Vec<ItemDto>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
3
como_infrastructure/src/services/mod.rs
Normal file
3
como_infrastructure/src/services/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod item_service;
|
||||
pub mod project_service;
|
||||
pub mod user_service;
|
70
como_infrastructure/src/services/project_service.rs
Normal file
70
como_infrastructure/src/services/project_service.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use anyhow::Context;
|
||||
use axum::async_trait;
|
||||
use como_core::projects::ProjectService;
|
||||
use como_domain::projects::{
|
||||
queries::{GetProjectQuery, GetProjectsQuery},
|
||||
ProjectDto,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub struct DefaultProjectService {}
|
||||
|
||||
impl DefaultProjectService {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DefaultProjectService {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ProjectService for DefaultProjectService {
|
||||
async fn get_project(&self, _query: GetProjectQuery) -> anyhow::Result<ProjectDto> {
|
||||
todo!()
|
||||
}
|
||||
async fn get_projects(&self, _query: GetProjectsQuery) -> anyhow::Result<Vec<ProjectDto>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MemoryProjectService {
|
||||
project_store: Arc<Mutex<HashMap<String, ProjectDto>>>,
|
||||
}
|
||||
|
||||
impl MemoryProjectService {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
project_store: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for MemoryProjectService {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ProjectService for MemoryProjectService {
|
||||
async fn get_project(&self, query: GetProjectQuery) -> anyhow::Result<ProjectDto> {
|
||||
let ps = self.project_store.lock().await;
|
||||
if let Some(item_id) = query.item_id {
|
||||
Ok(ps
|
||||
.get(&item_id.to_string())
|
||||
.context("could not find project")?
|
||||
.clone())
|
||||
} else {
|
||||
Err(anyhow::anyhow!("could not find project"))
|
||||
}
|
||||
}
|
||||
async fn get_projects(&self, _query: GetProjectsQuery) -> anyhow::Result<Vec<ProjectDto>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
@@ -1,18 +1,45 @@
|
||||
use anyhow::anyhow;
|
||||
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
|
||||
use axum::async_trait;
|
||||
use como_core::users::UserService;
|
||||
use rand_core::OsRng;
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
pub struct UserService {
|
||||
pgx: Pool<Postgres>,
|
||||
use crate::database::ConnectionPool;
|
||||
|
||||
pub struct DefaultUserService {
|
||||
pool: ConnectionPool,
|
||||
}
|
||||
|
||||
impl UserService {
|
||||
pub fn new(pgx: Pool<Postgres>) -> Self {
|
||||
Self { pgx }
|
||||
impl DefaultUserService {
|
||||
pub fn new(pool: ConnectionPool) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
pub async fn add_user(&self, username: String, password: String) -> anyhow::Result<String> {
|
||||
fn hash_password(&self, password: String) -> anyhow::Result<String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
let password_hash = argon2
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map_err(|e| anyhow::anyhow!(e))?
|
||||
.to_string();
|
||||
|
||||
Ok(password_hash)
|
||||
}
|
||||
|
||||
fn validate_password(&self, 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))?;
|
||||
match argon2.verify_password(password.as_bytes(), &parsed_hash) {
|
||||
Ok(..) => Ok(true),
|
||||
Err(..) => Ok(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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)?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
@@ -24,13 +51,13 @@ impl UserService {
|
||||
username,
|
||||
hashed_password
|
||||
)
|
||||
.fetch_one(&self.pgx)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(rec.id.to_string())
|
||||
}
|
||||
|
||||
pub async fn validate_user(
|
||||
async fn validate_user(
|
||||
&self,
|
||||
username: String,
|
||||
password: String,
|
||||
@@ -42,7 +69,7 @@ impl UserService {
|
||||
"#,
|
||||
username,
|
||||
)
|
||||
.fetch_optional(&self.pgx)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
match rec {
|
||||
@@ -53,26 +80,4 @@ impl UserService {
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_password(&self, password: String) -> anyhow::Result<String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
let password_hash = argon2
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map_err(|e| anyhow!(e))?
|
||||
.to_string();
|
||||
|
||||
Ok(password_hash)
|
||||
}
|
||||
|
||||
fn validate_password(&self, password: String, hashed_password: String) -> anyhow::Result<bool> {
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
let parsed_hash = PasswordHash::new(&hashed_password).map_err(|e| anyhow!(e))?;
|
||||
match argon2.verify_password(password.as_bytes(), &parsed_hash) {
|
||||
Ok(..) => Ok(true),
|
||||
Err(..) => Ok(false),
|
||||
}
|
||||
}
|
||||
}
|
@@ -2,5 +2,5 @@
|
||||
|
||||
export $(cat .env | xargs)
|
||||
|
||||
cargo sqlx migrate run --source como_bin/db/migrations --database-url=$DATABASE_URL
|
||||
cargo sqlx migrate run --source como_infrastructure/migrations --database-url=$DATABASE_URL
|
||||
|
||||
|
@@ -2,4 +2,4 @@
|
||||
|
||||
set -e
|
||||
|
||||
cargo run como_bin/
|
||||
(cd como_bin; cargo watch -x run)
|
||||
|
Reference in New Issue
Block a user