13 Commits

Author SHA1 Message Date
64019e5fba feat: with rhai
Some checks failed
continuous-integration/drone/push Build is failing
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-07-02 17:32:51 +02:00
3e5309e1e6 feat: update scripts to use new cuddle
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-06-10 14:35:03 +02:00
88c7acd439 feat: add deploy
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-06-04 14:55:22 +02:00
f9dcc59f3c chore: fix
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-06-04 14:43:36 +02:00
2604c5e301 feat: with updated deps
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-06-04 14:42:38 +02:00
534b2e4a23 feat: with items
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-06-04 11:02:51 +02:00
12c7c8f6ee feat: working projects and items
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-05-28 17:17:22 +02:00
6dc0c24443 feat: with create project
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-05-28 16:25:25 +02:00
c81a988061 chore: fmt all
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-05-28 15:43:29 +02:00
b3af0be6b5 feat: with persistent state
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-05-28 15:37:46 +02:00
746fb68684 feat: with persistent session state
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-05-28 15:34:36 +02:00
1e38b2838c feat: with zitadel login
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-05-28 15:05:16 +02:00
e991caef73 feat: with authorization
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-05-27 13:12:29 +02:00
60 changed files with 3507 additions and 1468 deletions

11
.env
View File

@@ -1,11 +0,0 @@
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

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/target /target
.cuddle/ .cuddle/
node_modules/ node_modules/
.env

2960
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,3 +7,47 @@ members = [
"como_gql", "como_gql",
"como_api", "como_api",
] ]
resolver = "2"
[workspace.dependencies]
como_bin = { path = "./como_bin/" }
como_core = { path = "./como_core/" }
como_domain = { path = "./como_domain/" }
como_infrastructure = { path = "./como_infrastructure/" }
como_gql = { path = "./como_gql/" }
como_api = { path = "./como_api/" }
async-trait = "0.1.68"
async-graphql = { version = "5.0.9", features = ["uuid"] }
async-graphql-axum = "5.0.9"
axum = { version = "0.6.18", features = ["headers", "macros"] }
axum-extra = { version = "0.7.4", features = ["cookie", "cookie-private"] }
axum-sessions = { version = "0.5.0" }
async-sqlx-session = { version = "0.4.0", features = ["pg"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.68"
sqlx = { version = "0.6.2", features = [
"runtime-tokio-rustls",
"postgres",
"migrate",
"uuid",
"offline",
"time",
"chrono",
] }
chrono = { version = "0.4.26", features = ["serde"] }
tokio = { version = "1.28.2", features = ["full"] }
uuid = { version = "1.3.3", features = ["v4", "fast-rng", "serde"] }
anyhow = "1.0.71"
dotenv = "0.15.0"
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
clap = { version = "4.3.0", features = ["derive", "env"] }
argon2 = { version = "0.5.0" }
rand_core = { version = "0.6.4" }

View File

@@ -1 +1,3 @@
# Cibus Backend # Cibus Backend
Some text

View File

@@ -6,34 +6,27 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
como_gql = { path = "../como_gql" } como_gql.workspace = true
como_core = { path = "../como_core" } como_core.workspace = true
como_domain = { path = "../como_domain" } como_domain.workspace = true
como_infrastructure = { path = "../como_infrastructure" } como_infrastructure.workspace = true
async-graphql = "4.0.6" async-graphql.workspace = true
async-graphql-axum = "*" async-graphql-axum.workspace = true
axum = "0.5.13" axum.workspace = true
axum-extra = { version = "*", features = ["cookie", "cookie-private"] } axum-extra.workspace = true
axum-sessions = { version = "*" } axum-sessions.workspace = true
serde = { version = "1.0", features = ["derive"] } serde.workspace = true
serde_json = "1.0.68" serde_json.workspace = true
tokio.workspace = true
uuid.workspace = true
sqlx.workspace = true
anyhow.workspace = true
tracing.workspace = true
async-sqlx-session.workspace = true
tokio = { version = "1.20.1", features = ["full"] } zitadel = { version = "3.3.1", features = ["axum"] }
uuid = { version = "1.1.2", features = ["v4", "fast-rng"] } tower = "0.4.13"
sqlx = { version = "0.6", features = [ tower-http = { version = "0.4.0", features = ["cors", "trace"] }
"runtime-tokio-rustls", oauth2 = "4.4.0"
"postgres", openidconnect = "3.0.0"
"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"] }

View File

@@ -0,0 +1,186 @@
use std::borrow::Cow;
use crate::router::AppState;
use crate::zitadel::{IntrospectionConfig, IntrospectionState};
use async_sqlx_session::PostgresSessionStore;
use axum::extract::{FromRef, FromRequestParts, Query, State};
use axum::headers::authorization::Basic;
use axum::headers::{Authorization, Cookie};
use axum::http::request::Parts;
use axum::http::StatusCode;
use axum::http::{header::SET_COOKIE, HeaderMap};
use axum::response::{IntoResponse, Redirect};
use axum::routing::get;
use axum::{async_trait, RequestPartsExt, Router, TypedHeader};
use axum_sessions::async_session::{Session, SessionStore};
use como_domain::users::User;
use como_infrastructure::register::ServiceRegister;
use oauth2::basic::BasicClient;
use oauth2::{reqwest::async_http_client, AuthorizationCode, CsrfToken, Scope, TokenResponse};
use oauth2::{RedirectUrl, TokenIntrospectionResponse};
use serde::Deserialize;
use zitadel::oidc::introspection::introspect;
#[derive(Debug, Deserialize)]
pub struct ZitadelAuthParams {
return_url: Option<String>,
}
pub async fn zitadel_auth(State(client): State<BasicClient>) -> impl IntoResponse {
let (auth_url, _csrf_token) = client
.authorize_url(CsrfToken::new_random)
.add_scope(Scope::new("identify".to_string()))
.add_scope(Scope::new("openid".to_string()))
.url();
Redirect::to(auth_url.as_ref())
}
pub static COOKIE_NAME: &str = "SESSION";
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct AuthRequest {
code: String,
state: String,
}
pub async fn login_authorized(
Query(query): Query<AuthRequest>,
State(store): State<PostgresSessionStore>,
State(oauth_client): State<BasicClient>,
State(introspection_state): State<IntrospectionState>,
) -> impl IntoResponse {
let token = oauth_client
.exchange_code(AuthorizationCode::new(query.code.clone()))
.request_async(async_http_client)
.await
.unwrap();
let config = IntrospectionConfig::from_ref(&introspection_state);
let res = introspect(
&config.introspection_uri,
&config.authority,
&config.authentication,
token.access_token().secret(),
)
.await
.unwrap();
let mut session = Session::new();
session
.insert(
"user",
User {
id: res.sub().unwrap().into(),
},
)
.unwrap();
let cookie = store.store_session(session).await.unwrap().unwrap();
let cookie = format!("{}={}; SameSite=Lax; Path=/", COOKIE_NAME, cookie);
let mut headers = HeaderMap::new();
headers.insert(SET_COOKIE, cookie.parse().unwrap());
(headers, Redirect::to("http://localhost:3000/dash/home"))
}
pub struct AuthController;
impl AuthController {
pub async fn new_router(
_service_register: ServiceRegister,
app_state: AppState,
) -> anyhow::Result<Router> {
Ok(Router::new()
.route("/zitadel", get(zitadel_auth))
.route("/authorized", get(login_authorized))
.with_state(app_state))
}
}
pub struct UserFromSession {
pub user: User,
}
#[async_trait]
impl<S> FromRequestParts<S> for UserFromSession
where
PostgresSessionStore: FromRef<S>,
BasicClient: FromRef<S>,
IntrospectionState: FromRef<S>,
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let store = PostgresSessionStore::from_ref(state);
let cookie: Option<TypedHeader<Cookie>> = parts.extract().await.unwrap();
let session_cookie = cookie.as_ref().and_then(|cookie| cookie.get(COOKIE_NAME));
if let None = session_cookie {
let introspection_state = IntrospectionState::from_ref(state);
let basic: Option<TypedHeader<Authorization<Basic>>> = parts.extract().await.unwrap();
if let Some(basic) = basic {
let config = IntrospectionConfig::from_ref(&introspection_state);
let res = introspect(
&config.introspection_uri,
&config.authority,
&config.authentication,
basic.password(),
)
.await
.unwrap();
return Ok(UserFromSession {
user: User {
id: res.sub().unwrap().into(),
},
});
}
return Err((StatusCode::UNAUTHORIZED, "No session was found"));
}
let session_cookie = session_cookie.unwrap();
tracing::debug!(
"UserFromSession: got session cookie from user agent, {}={}",
COOKIE_NAME,
session_cookie
);
// continue to decode the session cookie
let user =
if let Some(session) = store.load_session(session_cookie.to_owned()).await.unwrap() {
if let Some(user) = session.get::<User>("user") {
tracing::debug!(
"UserFromSession: session decoded success, user_id={:?}",
user.id
);
user
} else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"No `user_id` found in session",
));
}
} else {
tracing::debug!(
"UserIdFromSession: err session not exists in store, {}={}",
COOKIE_NAME,
session_cookie
);
return Err((StatusCode::BAD_REQUEST, "No session found for cookie"));
};
Ok(UserFromSession { user })
}
}

View File

@@ -1,21 +1,48 @@
use super::auth::UserFromSession;
use crate::router::AppState;
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptySubscription, Schema}; use async_graphql::{EmptySubscription, Schema};
use axum::{routing::get, Extension, Router}; use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use como_gql::{ use axum::response::Html;
graphql::{MutationRoot, QueryRoot}, use axum::{http::StatusCode, response::IntoResponse, routing::get, Extension, Router};
graphql_handler, graphql_playground,
}; use como_domain::user::ContextUserExt;
use como_domain::Context;
use como_gql::graphql::{ComoSchema, MutationRoot, QueryRoot};
use como_infrastructure::register::ServiceRegister; use como_infrastructure::register::ServiceRegister;
use tower::ServiceBuilder;
pub struct GraphQLController; pub struct GraphQLController;
impl GraphQLController { impl GraphQLController {
pub fn new_router(service_register: ServiceRegister) -> Router { pub fn new_router(service_register: ServiceRegister, state: AppState) -> Router {
let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription) let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription)
.data(service_register) .data(service_register)
.finish(); .finish();
Router::new() Router::new()
.route("/", get(graphql_playground).post(graphql_handler)) .route("/", get(graphql_playground).post(graphql_handler))
.layer(Extension(schema)) .layer(ServiceBuilder::new().layer(Extension(schema)))
.with_state(state)
} }
} }
pub async fn graphql_handler(
user: UserFromSession,
schema: Extension<ComoSchema>,
req: GraphQLRequest,
) -> Result<GraphQLResponse, StatusCode> {
let req = req.into_inner();
let req = req.data(user.user.clone());
let context = Context::new();
let context = context.set_user_id(user.user.id.clone());
let req = req.data(context);
Ok(schema.execute(req).await.into())
}
pub async fn graphql_playground() -> impl IntoResponse {
Html(playground_source(GraphQLPlaygroundConfig::new("/graphql")))
}

View File

@@ -1 +1,2 @@
pub mod auth;
pub mod graphql; pub mod graphql;

View File

@@ -1,2 +1,3 @@
mod controllers; mod controllers;
pub mod router; pub mod router;
pub mod zitadel;

View File

@@ -1,40 +1,74 @@
use std::env;
use anyhow::Context; use anyhow::Context;
use axum::{ use async_sqlx_session::PostgresSessionStore;
http::{HeaderValue, Method}, use axum::extract::FromRef;
Router, use axum::http::{HeaderValue, Method};
}; use axum::Router;
use como_infrastructure::register::ServiceRegister; use como_infrastructure::register::ServiceRegister;
use oauth2::basic::BasicClient;
use tower::ServiceBuilder; use tower::ServiceBuilder;
use tower_http::{cors::CorsLayer, trace::TraceLayer}; use tower_http::{cors::CorsLayer, trace::TraceLayer};
use crate::controllers::auth::AuthController;
use crate::controllers::graphql::GraphQLController; use crate::controllers::graphql::GraphQLController;
use crate::zitadel::client::oauth_client;
use crate::zitadel::{IntrospectionState, IntrospectionStateBuilder};
pub struct Api; pub struct Api;
impl Api { impl Api {
pub async fn run_api( pub async fn new(
port: u32, port: u32,
cors_origin: &str, cors_origin: &str,
service_register: ServiceRegister, service_register: ServiceRegister,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let client_id = env::var("CLIENT_ID").expect("Missing CLIENT_ID!");
let client_secret = env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET!");
let zitadel_url = env::var("ZITADEL_URL").expect("missing ZITADEL_URL");
let is = IntrospectionStateBuilder::new(&zitadel_url)
.with_basic_auth(&client_id, &client_secret)
.build()
.await?;
let oauth_client = oauth_client();
let app_state = AppState {
oauth_client,
store: service_register.session_store.clone(),
introspection_state: is,
};
let router = Router::new() let router = Router::new()
.nest( .nest(
"/graphql", "/auth",
GraphQLController::new_router(service_register.clone()), AuthController::new_router(service_register.clone(), app_state.clone()).await?,
)
.nest(
"/graphql",
GraphQLController::new_router(service_register.clone(), app_state.clone()),
) )
.layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))
.layer( .layer(
CorsLayer::new() ServiceBuilder::new()
.allow_origin( .layer(TraceLayer::new_for_http())
cors_origin .layer(
.parse::<HeaderValue>() CorsLayer::new()
.context("could not parse cors origin as header")?, .allow_origin(
) cors_origin
.allow_headers([axum::http::header::CONTENT_TYPE]) .parse::<HeaderValue>()
.allow_methods([Method::GET, Method::POST, Method::OPTIONS]), .context("could not parse cors origin as header")?,
)
.allow_headers([axum::http::header::CONTENT_TYPE])
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
.allow_credentials(true),
),
); );
axum::Server::bind(&format!("0.0.0.0:{}", port).parse().unwrap()) let host = env::var("HOST").unwrap_or("0.0.0.0".to_string());
tracing::info!("running on: {host}:{}", port);
axum::Server::bind(&format!("{host}:{}", port).parse().unwrap())
.serve(router.into_make_service()) .serve(router.into_make_service())
.await .await
.context("error while starting API")?; .context("error while starting API")?;
@@ -42,3 +76,28 @@ impl Api {
Ok(()) Ok(())
} }
} }
#[derive(Clone)]
pub struct AppState {
oauth_client: BasicClient,
introspection_state: IntrospectionState,
store: PostgresSessionStore,
}
impl FromRef<AppState> for BasicClient {
fn from_ref(state: &AppState) -> Self {
state.oauth_client.clone()
}
}
impl FromRef<AppState> for PostgresSessionStore {
fn from_ref(state: &AppState) -> Self {
state.store.clone()
}
}
impl FromRef<AppState> for IntrospectionState {
fn from_ref(input: &AppState) -> Self {
input.introspection_state.clone()
}
}

View File

@@ -0,0 +1,20 @@
use oauth2::{basic::BasicClient, AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl};
use std::env;
pub fn oauth_client() -> BasicClient {
let client_id = env::var("CLIENT_ID").expect("Missing CLIENT_ID!");
let client_secret = env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET!");
let redirect_url = env::var("REDIRECT_URL").expect("missing REDIRECT_URL");
let auth_url = env::var("AUTH_URL").expect("missing AUTH_URL");
let token_url = env::var("TOKEN_URL").expect("missing TOKEN_URL");
BasicClient::new(
ClientId::new(client_id),
Some(ClientSecret::new(client_secret)),
AuthUrl::new(auth_url).unwrap(),
Some(TokenUrl::new(token_url).unwrap()),
)
.set_redirect_uri(RedirectUrl::new(redirect_url).unwrap())
}

View File

@@ -0,0 +1,90 @@
pub mod client;
use axum::extract::FromRef;
use openidconnect::IntrospectionUrl;
use zitadel::{
axum::introspection::IntrospectionStateBuilderError,
credentials::Application,
oidc::{discovery::discover, introspection::AuthorityAuthentication},
};
#[derive(Clone, Debug)]
pub struct IntrospectionState {
pub(crate) config: IntrospectionConfig,
}
/// Configuration that must be inject into the axum application state. Used by the
/// [IntrospectionStateBuilder](super::IntrospectionStateBuilder). This struct is also used to create the [IntrospectionState](IntrospectionState)
#[derive(Debug, Clone)]
pub struct IntrospectionConfig {
pub(crate) authority: String,
pub(crate) authentication: AuthorityAuthentication,
pub(crate) introspection_uri: IntrospectionUrl,
}
impl FromRef<IntrospectionState> for IntrospectionConfig {
fn from_ref(input: &IntrospectionState) -> Self {
input.config.clone()
}
}
pub struct IntrospectionStateBuilder {
authority: String,
authentication: Option<AuthorityAuthentication>,
}
/// Builder for [IntrospectionConfig]
impl IntrospectionStateBuilder {
pub fn new(authority: &str) -> Self {
Self {
authority: authority.to_string(),
authentication: None,
}
}
pub fn with_basic_auth(
&mut self,
client_id: &str,
client_secret: &str,
) -> &mut IntrospectionStateBuilder {
self.authentication = Some(AuthorityAuthentication::Basic {
client_id: client_id.to_string(),
client_secret: client_secret.to_string(),
});
self
}
pub fn with_jwt_profile(&mut self, application: Application) -> &mut IntrospectionStateBuilder {
self.authentication = Some(AuthorityAuthentication::JWTProfile { application });
self
}
pub async fn build(&mut self) -> Result<IntrospectionState, IntrospectionStateBuilderError> {
if self.authentication.is_none() {
return Err(IntrospectionStateBuilderError::NoAuthSchema);
}
let metadata = discover(&self.authority)
.await
.map_err(|source| IntrospectionStateBuilderError::Discovery { source })?;
let introspection_uri = metadata
.additional_metadata()
.introspection_endpoint
.clone();
if introspection_uri.is_none() {
return Err(IntrospectionStateBuilderError::NoIntrospectionUrl);
}
Ok(IntrospectionState {
config: IntrospectionConfig {
authority: self.authority.clone(),
introspection_uri: introspection_uri.unwrap(),
authentication: self.authentication.as_ref().unwrap().clone(),
},
})
}
}

View File

@@ -6,34 +6,18 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
como_gql = { path = "../como_gql" } como_gql.workspace = true
como_core = { path = "../como_core" } como_core.workspace = true
como_domain = { path = "../como_domain" } como_domain.workspace = true
como_infrastructure = { path = "../como_infrastructure" } como_infrastructure.workspace = true
como_api = { path = "../como_api" } como_api.workspace = true
async-graphql = "4.0.6"
async-graphql-axum = "*" axum.workspace = true
axum = "0.5.13" serde_json.workspace = true
axum-extra = { version = "*", features = ["cookie", "cookie-private"] } tokio.workspace = true
axum-sessions = { version = "*" } anyhow.workspace = true
serde = { version = "1.0", features = ["derive"] } dotenv.workspace = true
serde_json = "1.0.68" tracing.workspace = true
tokio = { version = "1.20.1", features = ["full"] } tracing-subscriber.workspace = true
uuid = { version = "1.1.2", features = ["v4", "fast-rng"] } clap.workspace = true
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"] }

View File

@@ -1,7 +1,6 @@
use axum::{http::StatusCode, response::IntoResponse, Json}; use axum::{http::StatusCode, response::IntoResponse, Json};
use serde_json::json; use serde_json::json;
#[allow(dead_code)]
#[derive(Debug)] #[derive(Debug)]
pub enum AppError { pub enum AppError {
WrongCredentials, WrongCredentials,

View File

@@ -27,9 +27,9 @@ async fn main() -> anyhow::Result<()> {
let pool = ConnectionPoolManager::new_pool(&config.database_url, true).await?; let pool = ConnectionPoolManager::new_pool(&config.database_url, true).await?;
let service_register = ServiceRegister::new(pool, config.clone()); let service_register = ServiceRegister::new(pool, config.clone()).await?;
Api::run_api( Api::new(
config.api_port, config.api_port,
&config.cors_origin, &config.cors_origin,
service_register.clone(), service_register.clone(),

View File

@@ -6,26 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
como_domain = { path = "../como_domain" } como_domain.workspace = true
tokio = { version = "1", features = ["full"] }
axum = "0.5.1"
# utilty crates async-trait.workspace = true
serde = { version = "1.0.136", features = ["derive"] } anyhow.workspace = true
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"

5
como_core/report.json Normal file
View File

@@ -0,0 +1,5 @@
{
"version": 0,
"root_name": "Workspace",
"workspace_crates": {}
}

View File

@@ -1,18 +1,31 @@
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use como_domain::item::{ use como_domain::{
queries::{GetItemQuery, GetItemsQuery}, item::{
requests::CreateItemDto, queries::{GetItemQuery, GetItemsQuery},
responses::CreatedItemDto, requests::{CreateItemDto, UpdateItemDto},
ItemDto, responses::CreatedItemDto,
ItemDto,
},
Context,
}; };
pub type DynItemService = Arc<dyn ItemService + Send + Sync>; pub type DynItemService = Arc<dyn ItemService + Send + Sync>;
#[async_trait] #[async_trait]
pub trait ItemService { pub trait ItemService {
async fn add_item(&self, item: CreateItemDto) -> anyhow::Result<CreatedItemDto>; async fn add_item(
async fn get_item(&self, query: GetItemQuery) -> anyhow::Result<ItemDto>; &self,
async fn get_items(&self, query: GetItemsQuery) -> anyhow::Result<Vec<ItemDto>>; context: &Context,
item: CreateItemDto,
) -> anyhow::Result<CreatedItemDto>;
async fn get_item(&self, context: &Context, query: GetItemQuery) -> anyhow::Result<ItemDto>;
async fn get_items(
&self,
context: &Context,
query: GetItemsQuery,
) -> anyhow::Result<Vec<ItemDto>>;
async fn update_item(&self, context: &Context, item: UpdateItemDto) -> anyhow::Result<ItemDto>;
} }

View File

@@ -1,15 +1,24 @@
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use como_domain::projects::{ use como_domain::{
queries::{GetProjectQuery, GetProjectsQuery}, projects::{mutation::CreateProjectMutation, queries::GetProjectQuery, ProjectDto},
ProjectDto, Context,
}; };
pub type DynProjectService = Arc<dyn ProjectService + Send + Sync>; pub type DynProjectService = Arc<dyn ProjectService + Send + Sync>;
#[async_trait] #[async_trait]
pub trait ProjectService { pub trait ProjectService {
async fn get_project(&self, query: GetProjectQuery) -> anyhow::Result<ProjectDto>; async fn get_project(
async fn get_projects(&self, query: GetProjectsQuery) -> anyhow::Result<Vec<ProjectDto>>; &self,
context: &Context,
query: GetProjectQuery,
) -> anyhow::Result<ProjectDto>;
async fn get_projects(&self, context: &Context) -> anyhow::Result<Vec<ProjectDto>>;
async fn create_project(
&self,
context: &Context,
name: CreateProjectMutation,
) -> anyhow::Result<ProjectDto>;
} }

View File

@@ -1,14 +1,21 @@
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use como_domain::Context;
pub type DynUserService = Arc<dyn UserService + Send + Sync>; pub type DynUserService = Arc<dyn UserService + Send + Sync>;
#[async_trait] #[async_trait]
pub trait UserService { pub trait UserService {
async fn add_user(&self, username: String, password: String) -> anyhow::Result<String>; async fn add_user(
&self,
context: &Context,
username: String,
password: String,
) -> anyhow::Result<String>;
async fn validate_user( async fn validate_user(
&self, &self,
context: &Context,
username: String, username: String,
password: String, password: String,
) -> anyhow::Result<Option<String>>; ) -> anyhow::Result<Option<String>>;

View File

@@ -6,8 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
async-graphql = { version = "4.0.6", features = ["uuid"] } async-graphql.workspace = true
anyhow = "1.0.60" serde.workspace = true
serde = { version = "1.0", features = ["derive"] } serde_json.workspace = true
serde_json = "1.0.68" uuid.workspace = true
uuid = { version = "1.1.2", features = ["v4", "fast-rng", "serde"] }

View File

@@ -0,0 +1,37 @@
pub mod user;
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub struct Context {
values: BTreeMap<String, String>,
}
impl Context {
pub fn new() -> Self {
Self {
values: Default::default(),
}
}
pub fn with_value(&self, key: impl Into<String>, value: impl Into<String>) -> Self {
let mut values = self.values.clone();
let _ = values.insert(key.into(), value.into());
Self { values }
}
pub fn with_value_mut(
&mut self,
key: impl Into<String>,
value: impl Into<String>,
) -> &mut Self {
self.values.insert(key.into(), value.into());
self
}
pub fn get(&self, key: impl AsRef<str>) -> Option<&str> {
self.values.get(key.as_ref()).map(|s| s.as_str())
}
}

View File

@@ -0,0 +1,23 @@
use crate::Context;
pub trait ContextUserExt {
fn set_user_id(&self, user_id: impl Into<String>) -> Context;
fn set_user_id_mut(&mut self, user_id: impl Into<String>) -> &mut Context;
fn get_user_id(&self) -> Option<String>;
}
const USER_ID_KEY: &str = "user_id";
impl ContextUserExt for Context {
fn set_user_id(&self, user_id: impl Into<String>) -> Context {
self.with_value(USER_ID_KEY, user_id)
}
fn set_user_id_mut(&mut self, user_id: impl Into<String>) -> &mut Context {
self.with_value_mut(USER_ID_KEY, user_id)
}
fn get_user_id(&self) -> Option<String> {
self.get(USER_ID_KEY).map(|s| s.to_string())
}
}

View File

@@ -20,4 +20,5 @@ pub struct ItemDto {
pub title: String, pub title: String,
pub description: Option<String>, pub description: Option<String>,
pub state: ItemState, pub state: ItemState,
pub project_id: Uuid,
} }

View File

@@ -9,5 +9,5 @@ pub struct GetItemQuery {
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)] #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
pub struct GetItemsQuery { pub struct GetItemsQuery {
pub user_id: Uuid, pub project_id: Uuid,
} }

View File

@@ -1,7 +1,21 @@
use async_graphql::InputObject; use async_graphql::InputObject;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use uuid::Uuid;
use super::ItemState;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)] #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
pub struct CreateItemDto { pub struct CreateItemDto {
pub name: String, pub title: String,
pub description: Option<String>,
pub project_id: Uuid,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
pub struct UpdateItemDto {
pub id: Uuid,
pub title: Option<String>,
pub description: Option<String>,
pub state: Option<ItemState>,
pub project_id: Option<Uuid>,
} }

View File

@@ -1,3 +1,6 @@
pub mod common;
pub mod item; pub mod item;
pub mod projects; pub mod projects;
pub mod users; pub mod users;
pub use common::*;

View File

@@ -1,3 +1,4 @@
pub mod mutation;
pub mod queries; pub mod queries;
pub mod requests; pub mod requests;
pub mod responses; pub mod responses;
@@ -10,4 +11,7 @@ use uuid::Uuid;
pub struct ProjectDto { pub struct ProjectDto {
pub id: Uuid, pub id: Uuid,
pub name: String, pub name: String,
pub description: Option<String>,
pub user_id: String,
} }

View File

@@ -0,0 +1,8 @@
use async_graphql::InputObject;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
pub struct CreateProjectMutation {
pub name: String,
pub description: Option<String>,
}

View File

@@ -4,11 +4,5 @@ use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)] #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
pub struct GetProjectQuery { pub struct GetProjectQuery {
pub project_id: Option<Uuid>, pub project_id: Uuid,
pub item_id: Option<Uuid>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
pub struct GetProjectsQuery {
pub user_id: Uuid,
} }

View File

@@ -10,3 +10,8 @@ pub struct UserDto {
pub username: String, pub username: String,
pub email: String, pub email: String,
} }
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct User {
pub id: String,
}

View File

@@ -6,31 +6,11 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
como_core = { path = "../como_core" } como_core.workspace = true
como_domain = { path = "../como_domain" } como_domain.workspace = true
como_infrastructure = { path = "../como_infrastructure" } como_infrastructure.workspace = true
async-graphql = "4.0.6" anyhow.workspace = true
async-graphql-axum = "*" async-trait.workspace = true
axum = "0.5.13" async-graphql.workspace = true
axum-extra = { version = "*", features = ["cookie", "cookie-private"] } uuid.workspace = true
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"] }

View File

@@ -1,18 +1,12 @@
use async_graphql::{Context, EmptySubscription, Object, Schema}; use crate::common::*;
use como_domain::{
item::{
queries::{GetItemQuery, GetItemsQuery},
requests::CreateItemDto,
},
projects::{
queries::{GetProjectQuery, GetProjectsQuery},
ProjectDto,
},
};
use como_infrastructure::register::ServiceRegister;
use crate::items::{CreatedItem, Item}; use crate::items::{CreatedItem, Item};
use crate::projects::Project;
use async_graphql::{Context, EmptySubscription, Object, Schema};
use como_domain::item::queries::{GetItemQuery, GetItemsQuery};
use como_domain::item::requests::{CreateItemDto, UpdateItemDto};
use como_domain::projects::mutation::CreateProjectMutation;
use como_domain::projects::queries::GetProjectQuery;
use como_domain::projects::ProjectDto;
pub type ComoSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>; pub type ComoSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>;
@@ -20,67 +14,48 @@ pub struct MutationRoot;
#[Object] #[Object]
impl MutationRoot { 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( async fn create_item(
&self, &self,
ctx: &Context<'_>, ctx: &Context<'_>,
item: CreateItemDto, item: CreateItemDto,
) -> anyhow::Result<CreatedItem> { ) -> anyhow::Result<CreatedItem> {
let services_register = ctx.data_unchecked::<ServiceRegister>(); let created_item = item_service(ctx)
.add_item(get_domain_context(ctx), item)
let created_item = services_register.item_service.add_item(item).await?; .await?;
Ok(CreatedItem { Ok(CreatedItem {
id: created_item.id, id: created_item.id,
}) })
} }
async fn create_project(
&self,
ctx: &Context<'_>,
request: CreateProjectMutation,
) -> anyhow::Result<ProjectDto> {
let project = project_service(ctx)
.create_project(get_domain_context(ctx), request)
.await?;
Ok(project)
}
async fn update_item(&self, ctx: &Context<'_>, item: UpdateItemDto) -> anyhow::Result<Item> {
let updated_item = item_service(ctx)
.update_item(get_domain_context(ctx), item)
.await?;
Ok(updated_item.into())
}
} }
pub struct QueryRoot; pub struct QueryRoot;
#[Object] #[Object]
impl QueryRoot { impl QueryRoot {
// Items
async fn get_item(&self, ctx: &Context<'_>, query: GetItemQuery) -> anyhow::Result<Item> { async fn get_item(&self, ctx: &Context<'_>, query: GetItemQuery) -> anyhow::Result<Item> {
let item = ctx let item = item_service(ctx)
.data_unchecked::<ServiceRegister>() .get_item(get_domain_context(ctx), query)
.item_service
.get_item(query)
.await?; .await?;
Ok(Item::from(item)) Ok(Item::from(item))
@@ -91,10 +66,8 @@ impl QueryRoot {
ctx: &Context<'_>, ctx: &Context<'_>,
query: GetItemsQuery, query: GetItemsQuery,
) -> anyhow::Result<Vec<Item>> { ) -> anyhow::Result<Vec<Item>> {
let items = ctx let items = item_service(ctx)
.data_unchecked::<ServiceRegister>() .get_items(get_domain_context(ctx), query)
.item_service
.get_items(query)
.await?; .await?;
Ok(items.iter().map(|i| Item::from(i.clone())).collect()) Ok(items.iter().map(|i| Item::from(i.clone())).collect())
@@ -105,21 +78,17 @@ impl QueryRoot {
&self, &self,
ctx: &Context<'_>, ctx: &Context<'_>,
query: GetProjectQuery, query: GetProjectQuery,
) -> anyhow::Result<ProjectDto> { ) -> anyhow::Result<Project> {
ctx.data_unchecked::<ServiceRegister>() project_service(ctx)
.project_service .get_project(get_domain_context(ctx), query)
.get_project(query)
.await .await
.map(|p| p.into())
} }
async fn get_projects( async fn get_projects(&self, ctx: &Context<'_>) -> anyhow::Result<Vec<Project>> {
&self, project_service(ctx)
ctx: &Context<'_>, .get_projects(get_domain_context(ctx))
query: GetProjectsQuery,
) -> anyhow::Result<Vec<ProjectDto>> {
ctx.data_unchecked::<ServiceRegister>()
.project_service
.get_projects(query)
.await .await
.map(|p| p.into_iter().map(|p| p.into()).collect())
} }
} }

View File

@@ -1,9 +1,9 @@
use crate::common::*;
use async_graphql::{Context, Object}; use async_graphql::{Context, Object};
use como_domain::{ use como_domain::{
item::{queries::GetItemQuery, ItemDto, ItemState}, item::{queries::GetItemQuery, ItemDto, ItemState},
projects::queries::GetProjectQuery, projects::queries::GetProjectQuery,
}; };
use como_infrastructure::register::ServiceRegister;
use uuid::Uuid; use uuid::Uuid;
use crate::projects::Project; use crate::projects::Project;
@@ -15,10 +15,8 @@ pub struct CreatedItem {
#[Object] #[Object]
impl CreatedItem { impl CreatedItem {
pub async fn item(&self, ctx: &Context<'_>) -> anyhow::Result<Item> { pub async fn item(&self, ctx: &Context<'_>) -> anyhow::Result<Item> {
let item = ctx let item = item_service(ctx)
.data_unchecked::<ServiceRegister>() .get_item(get_domain_context(ctx), GetItemQuery { item_id: self.id })
.item_service
.get_item(GetItemQuery { item_id: self.id })
.await?; .await?;
Ok(item.into()) Ok(item.into())
@@ -30,38 +28,43 @@ pub struct Item {
pub title: String, pub title: String,
pub description: Option<String>, pub description: Option<String>,
pub state: ItemState, pub state: ItemState,
pub project_id: Uuid,
} }
#[Object] #[Object]
impl Item { impl Item {
pub async fn id(&self, _ctx: &Context<'_>) -> anyhow::Result<Uuid> { pub async fn id(&self, _ctx: &Context<'_>) -> anyhow::Result<Uuid> {
Ok(self.id) return Ok(self.id);
} }
pub async fn title(&self, _ctx: &Context<'_>) -> anyhow::Result<String> { pub async fn title(&self, _ctx: &Context<'_>) -> anyhow::Result<String> {
Ok(self.title.clone()) return Ok(self.title.clone());
} }
pub async fn description(&self, _ctx: &Context<'_>) -> anyhow::Result<Option<String>> { pub async fn description(&self, _ctx: &Context<'_>) -> anyhow::Result<Option<String>> {
Ok(self.description.clone()) return Ok(self.description.clone());
} }
pub async fn state(&self, _ctx: &Context<'_>) -> anyhow::Result<ItemState> { pub async fn state(&self, _ctx: &Context<'_>) -> anyhow::Result<ItemState> {
Ok(self.state) return Ok(self.state);
} }
pub async fn project(&self, ctx: &Context<'_>) -> anyhow::Result<Project> { pub async fn project(&self, ctx: &Context<'_>) -> anyhow::Result<Project> {
let project = ctx let project = project_service(ctx)
.data_unchecked::<ServiceRegister>() .get_project(
.project_service get_domain_context(ctx),
.get_project(GetProjectQuery { GetProjectQuery {
item_id: Some(self.id), project_id: self.project_id,
project_id: None, },
}) )
.await?; .await?;
Ok(project.into()) Ok(project.into())
} }
pub async fn project_id(&self, _ctx: &Context<'_>) -> anyhow::Result<Uuid> {
return Ok(self.project_id);
}
} }
impl From<ItemDto> for Item { impl From<ItemDto> for Item {
@@ -71,6 +74,7 @@ impl From<ItemDto> for Item {
title: dto.title, title: dto.title,
description: dto.description, description: dto.description,
state: dto.state, state: dto.state,
project_id: dto.project_id,
} }
} }
} }

View File

@@ -1,26 +1,33 @@
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; pub mod graphql;
mod items; mod items;
mod projects; mod projects;
pub async fn graphql_handler( pub mod common {
schema: Extension<ComoSchema>, use async_graphql::Context;
req: GraphQLRequest, use como_core::items::DynItemService;
) -> Result<GraphQLResponse, StatusCode> { use como_core::projects::DynProjectService;
let req = req.into_inner(); use como_infrastructure::register::ServiceRegister;
Ok(schema.execute(req).await.into()) #[inline(always)]
} pub(crate) fn get_domain_context<'a>(ctx: &Context<'a>) -> &'a como_domain::Context {
ctx.data_unchecked::<como_domain::Context>()
}
pub async fn graphql_playground() -> impl IntoResponse { #[allow(dead_code)]
Html(playground_source(GraphQLPlaygroundConfig::new("/graphql"))) #[inline(always)]
pub(crate) fn get_service_register<'a>(ctx: &Context<'a>) -> &'a ServiceRegister {
ctx.data_unchecked::<ServiceRegister>()
}
#[inline(always)]
pub(crate) fn project_service<'a>(ctx: &Context<'a>) -> DynProjectService {
ctx.data_unchecked::<ServiceRegister>()
.project_service
.clone()
}
#[inline(always)]
pub(crate) fn item_service<'a>(ctx: &Context<'a>) -> DynItemService {
ctx.data_unchecked::<ServiceRegister>().item_service.clone()
}
} }

View File

@@ -1,13 +1,43 @@
use async_graphql::SimpleObject; use crate::common::*;
use async_graphql::{Context, Object};
use como_domain::projects::ProjectDto; use como_domain::projects::ProjectDto;
use uuid::Uuid; use uuid::Uuid;
#[derive(SimpleObject)] use crate::items::Item;
pub struct Project { pub struct Project {
pub id: Uuid, pub id: Uuid,
pub name: String, pub name: String,
} }
#[Object]
impl Project {
async fn id(&self) -> &Uuid {
&self.id
}
async fn name(&self) -> &String {
&self.name
}
async fn items(&self, ctx: &Context<'_>) -> anyhow::Result<Vec<Item>> {
let items = item_service(ctx)
.get_items(
get_domain_context(ctx),
como_domain::item::queries::GetItemsQuery {
project_id: self.id,
},
)
.await?
.iter()
.map(|i| Item::from(i.clone()))
.collect::<Vec<_>>();
Ok(items)
}
}
impl From<ProjectDto> for Project { impl From<ProjectDto> for Project {
fn from(dto: ProjectDto) -> Self { fn from(dto: ProjectDto) -> Self {
Self { Self {

View File

View File

@@ -6,31 +6,22 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
como_core = { path = "../como_core" } como_core.workspace = true
como_domain = { path = "../como_domain" } como_domain.workspace = true
async-graphql = "4.0.6"
async-graphql-axum = "*" axum.workspace = true
axum = "0.5.13" async-trait.workspace = true
axum-extra = { version = "*", features = ["cookie", "cookie-private"] } uuid.workspace = true
axum-sessions = { version = "*" } anyhow.workspace = true
serde = { version = "1.0", features = ["derive"] } sqlx.workspace = true
serde_json = "1.0.68" chrono.workspace = true
tokio = { version = "1.20.1", features = ["full"] } serde_json.workspace = true
uuid = { version = "1.1.2", features = ["v4", "fast-rng"] }
sqlx = { version = "0.6", features = [ async-sqlx-session.workspace = true
"runtime-tokio-rustls",
"postgres", tokio.workspace = true
"migrate", clap.workspace = true
"uuid", tracing.workspace = true
"offline", argon2.workspace = true
] } rand_core.workspace = true
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"] }

View File

@@ -0,0 +1,9 @@
fn main() {
println!("cargo:rustc-env=SQLX_OFFLINE_DIR='./.sqlx'");
// When building in docs.rs, we want to set SQLX_OFFLINE mode to true
if std::env::var_os("DOCS_RS").is_some() {
println!("cargo:rustc-env=SQLX_OFFLINE=true");
} else if std::env::var_os("DOCKER_BUILD").is_some() {
println!("cargo:rustc-env=SQLX_OFFLINE=true");
}
}

View File

@@ -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
);

View 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
)

View File

@@ -0,0 +1,4 @@
-- Add migration script here
ALTER TABLE items ALTER COLUMN state TYPE varchar(255);

View File

@@ -0,0 +1,346 @@
{
"db": "PostgreSQL",
"05d0a7901f0481d7443f125655df26eeacd63f2b023723a0c09c662617e0baf5": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
},
{
"name": "title",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "description",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "state",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "project_id",
"ordinal": 4,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
true,
false,
false
],
"parameters": {
"Left": [
"Uuid",
"Text"
]
}
},
"query": "\n SELECT id, title, description, state, project_id\n FROM items\n WHERE id = $1 AND user_id = $2\n "
},
"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 "
},
"4ec32ebd0ee991cec625d9de51de0d3e0ddfc8afda0568327fa9c818bde08e1f": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
}
],
"nullable": [
false
],
"parameters": {
"Left": [
"Uuid",
"Varchar",
"Varchar",
"Varchar",
"Timestamp",
"Timestamp"
]
}
},
"query": "\n INSERT INTO projects (id, name, description, user_id, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id\n "
},
"7901e81b1f1f08f0c7e72a967a8116efb62f40d99f80900f1e56cd13ad4f6bb2": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
},
{
"name": "title",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "description",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "state",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "project_id",
"ordinal": 4,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
true,
false,
false
],
"parameters": {
"Left": [
"Uuid",
"Varchar",
"Varchar",
"Varchar",
"Uuid",
"Varchar"
]
}
},
"query": "\n INSERT INTO items (id, title, description, state, project_id, user_id, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5, $6, now(), now())\n RETURNING id, title, description, state, project_id\n "
},
"a188dc748025cf3311820d16002b111a75f571d18f44f54b730ac14e9b2e10ea": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
},
{
"name": "name",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "description",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "user_id",
"ordinal": 3,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
true,
false
],
"parameters": {
"Left": [
"Uuid",
"Text"
]
}
},
"query": "\n SELECT id, name, description, user_id\n FROM projects\n WHERE id = $1 and user_id = $2\n "
},
"b930a7123d22d543e4d8ed70a1bc10477362127969ceca9653e445f26670003a": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
},
{
"name": "name",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "description",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "user_id",
"ordinal": 3,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
true,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "\n SELECT id, name, description, user_id\n FROM projects\n WHERE user_id = $1\n LIMIT 500\n "
},
"bacf3c8a2f302d50991483fa36a06965c3536c2ef3837c19c6e6361eff312848": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
},
{
"name": "title",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "description",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "state",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "project_id",
"ordinal": 4,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
true,
false,
false
],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Uuid",
"Uuid",
"Text"
]
}
},
"query": "\n UPDATE items\n SET \n title = COALESCE($1, title), \n description = COALESCE($2, description), \n state = COALESCE($3, state), \n project_id = COALESCE($4, project_id), \n updated_at = now()\n WHERE id = $5 AND user_id = $6\n RETURNING id, title, description, state, project_id\n "
},
"bd2407ffb9637afcff3ffe1101e7c1920b8cf0be423ab0313d14acc9c76e0f93": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
},
{
"name": "title",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "description",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "state",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "project_id",
"ordinal": 4,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
true,
false,
false
],
"parameters": {
"Left": [
"Text",
"Uuid"
]
}
},
"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 "
},
"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 "
}
}

View File

@@ -1,17 +1,27 @@
use clap::ValueEnum;
#[derive(clap::Parser)] #[derive(clap::Parser)]
pub struct AppConfig { pub struct AppConfig {
#[clap(long, env)] #[clap(long, env)]
pub database_url: String, pub database_url: String,
#[clap(long, env, default_value = "postgres")]
pub database_type: DatabaseType,
#[clap(long, env)] #[clap(long, env)]
pub rust_log: String, pub rust_log: String,
#[clap(long, env)] #[clap(long, env)]
pub token_secret: String, pub token_secret: String,
#[clap(long, env)] #[clap(long, env, default_value = "3001")]
pub api_port: u32, pub api_port: u32,
#[clap(long, env)] #[clap(long, env, default_value = "true")]
pub run_migrations: bool, pub run_migrations: bool,
#[clap(long, env)] #[clap(long, env, default_value = "false")]
pub seed: bool, pub seed: bool,
#[clap(long, env)] #[clap(long, env)]
pub cors_origin: String, pub cors_origin: String,
} }
#[derive(Clone, Debug, ValueEnum)]
pub enum DatabaseType {
Postgres,
InMemory,
}

View File

@@ -1,13 +1,15 @@
use std::sync::Arc; use std::sync::Arc;
use async_sqlx_session::PostgresSessionStore;
use como_core::{items::DynItemService, projects::DynProjectService, users::DynUserService}; use como_core::{items::DynItemService, projects::DynProjectService, users::DynUserService};
use tracing::log::info; use tracing::log::info;
use crate::{ use crate::{
configs::AppConfig, configs::{AppConfig, DatabaseType},
database::ConnectionPool, database::ConnectionPool,
services::{ services::{
item_service::MemoryItemService, project_service::MemoryProjectService, item_service::{DefaultItemService, MemoryItemService},
project_service::{DefaultProjectService, MemoryProjectService},
user_service::DefaultUserService, user_service::DefaultUserService,
}, },
}; };
@@ -17,22 +19,49 @@ pub struct ServiceRegister {
pub item_service: DynItemService, pub item_service: DynItemService,
pub project_service: DynProjectService, pub project_service: DynProjectService,
pub user_service: DynUserService, pub user_service: DynUserService,
pub session_store: PostgresSessionStore,
} }
impl ServiceRegister { impl ServiceRegister {
pub fn new(pool: ConnectionPool, _config: Arc<AppConfig>) -> Self { pub async fn new(pool: ConnectionPool, config: Arc<AppConfig>) -> anyhow::Result<Self> {
info!("creating services"); info!("creating services");
let item_service = Arc::new(MemoryItemService::new()) as DynItemService; let s = match config.database_type {
let project_service = Arc::new(MemoryProjectService::new()) as DynProjectService; DatabaseType::Postgres => {
let user_service = Arc::new(DefaultUserService::new(pool)) as DynUserService; 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?;
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"); info!("services created succesfully");
Self { Ok(s)
item_service,
user_service,
project_service,
}
} }
} }

View File

@@ -0,0 +1 @@

View File

@@ -1,45 +1,158 @@
use crate::database::ConnectionPool;
use async_trait::async_trait;
use como_core::items::ItemService;
use como_domain::{
item::{
queries::{GetItemQuery, GetItemsQuery},
requests::{CreateItemDto, UpdateItemDto},
responses::CreatedItemDto,
ItemDto,
},
user::ContextUserExt,
Context,
};
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::{Arc, Mutex}, 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; use uuid::Uuid;
pub struct DefaultItemService {} pub struct DefaultItemService {
pool: ConnectionPool,
impl DefaultItemService {
pub fn new() -> Self {
Self {}
}
} }
impl Default for DefaultItemService { impl DefaultItemService {
fn default() -> Self { pub fn new(connection_pool: ConnectionPool) -> Self {
Self::new() Self {
pool: connection_pool,
}
} }
} }
#[async_trait] #[async_trait]
impl ItemService for DefaultItemService { impl ItemService for DefaultItemService {
async fn add_item(&self, _item: CreateItemDto) -> anyhow::Result<CreatedItemDto> { async fn add_item(
todo!() &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.title,
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) -> anyhow::Result<ItemDto> { async fn get_item(&self, context: &Context, query: GetItemQuery) -> anyhow::Result<ItemDto> {
todo!() 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) -> anyhow::Result<Vec<ItemDto>> { async fn get_items(
todo!() &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())
}
async fn update_item(&self, context: &Context, item: UpdateItemDto) -> anyhow::Result<ItemDto> {
let state = item.state.map(|s| serde_json::to_string(&s)).transpose()?;
let user_id = context.get_user_id().ok_or(anyhow::anyhow!("no user id"))?;
let rec = sqlx::query!(
r#"
UPDATE items
SET
title = COALESCE($1, title),
description = COALESCE($2, description),
state = COALESCE($3, state),
project_id = COALESCE($4, project_id),
updated_at = now()
WHERE id = $5 AND user_id = $6
RETURNING id, title, description, state, project_id
"#,
item.title,
item.description,
state,
item.project_id,
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,
})
} }
} }
@@ -55,21 +168,20 @@ impl MemoryItemService {
} }
} }
impl Default for MemoryItemService {
fn default() -> Self {
Self::new()
}
}
#[async_trait] #[async_trait]
impl ItemService for MemoryItemService { impl ItemService for MemoryItemService {
async fn add_item(&self, create_item: CreateItemDto) -> anyhow::Result<CreatedItemDto> { async fn add_item(
&self,
_context: &Context,
create_item: CreateItemDto,
) -> anyhow::Result<CreatedItemDto> {
if let Ok(mut item_store) = self.item_store.lock() { if let Ok(mut item_store) = self.item_store.lock() {
let item = ItemDto { let item = ItemDto {
id: Uuid::new_v4(), id: Uuid::new_v4(),
title: create_item.name, title: create_item.title,
description: None, description: create_item.description,
state: como_domain::item::ItemState::Created, state: como_domain::item::ItemState::Created,
project_id: create_item.project_id,
}; };
item_store.insert(item.id.to_string(), item.clone()); item_store.insert(item.id.to_string(), item.clone());
@@ -80,18 +192,26 @@ impl ItemService for MemoryItemService {
} }
} }
async fn get_item(&self, query: GetItemQuery) -> anyhow::Result<ItemDto> { async fn get_item(&self, _context: &Context, query: GetItemQuery) -> anyhow::Result<ItemDto> {
if let Ok(item_store) = self.item_store.lock() { if let Ok(item_store) = self.item_store.lock() {
let item = item_store let item = item_store
.get(&query.item_id.to_string()) .get(&query.item_id.to_string())
.context("could not find item")?; .ok_or(anyhow::anyhow!("could not find item"))?;
return Ok(item.clone()); return Ok(item.clone());
} else { } else {
Err(anyhow::anyhow!("could not unlock item_store")) Err(anyhow::anyhow!("could not unlock item_store"))
} }
} }
async fn get_items(&self, _query: GetItemsQuery) -> anyhow::Result<Vec<ItemDto>> { async fn get_items(
&self,
_context: &Context,
_query: GetItemsQuery,
) -> anyhow::Result<Vec<ItemDto>> {
todo!()
}
async fn update_item(&self, _context: &Context, _item: UpdateItemDto) -> anyhow::Result<ItemDto> {
todo!() todo!()
} }
} }

View File

@@ -1,35 +1,110 @@
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, sync::Arc};
use anyhow::Context;
use axum::async_trait; use axum::async_trait;
use como_core::projects::ProjectService; use como_core::projects::ProjectService;
use como_domain::projects::{ use como_domain::{
queries::{GetProjectQuery, GetProjectsQuery}, projects::{mutation::CreateProjectMutation, queries::GetProjectQuery, ProjectDto},
ProjectDto, user::ContextUserExt,
Context,
}; };
use tokio::sync::Mutex; use tokio::sync::Mutex;
pub struct DefaultProjectService {} use crate::database::ConnectionPool;
impl DefaultProjectService { pub struct DefaultProjectService {
pub fn new() -> Self { pool: ConnectionPool,
Self {}
}
} }
impl Default for DefaultProjectService { impl DefaultProjectService {
fn default() -> Self { pub fn new(connection_pool: ConnectionPool) -> Self {
Self::new() Self {
pool: connection_pool,
}
} }
} }
#[async_trait] #[async_trait]
impl ProjectService for DefaultProjectService { impl ProjectService for DefaultProjectService {
async fn get_project(&self, _query: GetProjectQuery) -> anyhow::Result<ProjectDto> { async fn get_project(
todo!() &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, _query: GetProjectsQuery) -> anyhow::Result<Vec<ProjectDto>> { async fn get_projects(&self, context: &Context) -> anyhow::Result<Vec<ProjectDto>> {
todo!() 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,
context: &Context,
request: CreateProjectMutation,
) -> anyhow::Result<ProjectDto> {
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(),
})
} }
} }
@@ -45,26 +120,48 @@ impl MemoryProjectService {
} }
} }
impl Default for MemoryProjectService {
fn default() -> Self {
Self::new()
}
}
#[async_trait] #[async_trait]
impl ProjectService for MemoryProjectService { 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; let ps = self.project_store.lock().await;
if let Some(item_id) = query.item_id { Ok(ps
Ok(ps .get(&query.project_id.to_string())
.get(&item_id.to_string()) .ok_or(anyhow::anyhow!("could not find project"))?
.context("could not find project")? .clone())
.clone())
} else {
Err(anyhow::anyhow!("could not find project"))
}
} }
async fn get_projects(&self, _query: GetProjectsQuery) -> anyhow::Result<Vec<ProjectDto>> { async fn get_projects(&self, context: &Context) -> anyhow::Result<Vec<ProjectDto>> {
todo!() 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)
.cloned()
.collect::<_>())
}
async fn create_project(
&self,
context: &Context,
mutation: CreateProjectMutation,
) -> 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,
};
ps.insert(project.id.to_string(), project.clone());
Ok(project)
} }
} }

View File

@@ -1,6 +1,7 @@
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier}; use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use axum::async_trait; use axum::async_trait;
use como_core::users::UserService; use como_core::users::UserService;
use como_domain::Context;
use rand_core::OsRng; use rand_core::OsRng;
use crate::database::ConnectionPool; use crate::database::ConnectionPool;
@@ -14,7 +15,7 @@ impl DefaultUserService {
Self { pool } 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 salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default(); let argon2 = Argon2::default();
@@ -26,7 +27,12 @@ impl DefaultUserService {
Ok(password_hash) 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 argon2 = Argon2::default();
let parsed_hash = PasswordHash::new(&hashed_password).map_err(|e| anyhow::anyhow!(e))?; let parsed_hash = PasswordHash::new(&hashed_password).map_err(|e| anyhow::anyhow!(e))?;
@@ -39,8 +45,13 @@ impl DefaultUserService {
#[async_trait] #[async_trait]
impl UserService for DefaultUserService { impl UserService for DefaultUserService {
async fn add_user(&self, username: String, password: String) -> anyhow::Result<String> { async fn add_user(
let hashed_password = self.hash_password(password)?; &self,
context: &Context,
username: String,
password: String,
) -> anyhow::Result<String> {
let hashed_password = self.hash_password(context, password)?;
let rec = sqlx::query!( let rec = sqlx::query!(
r#" r#"
@@ -59,6 +70,7 @@ impl UserService for DefaultUserService {
async fn validate_user( async fn validate_user(
&self, &self,
context: &Context,
username: String, username: String,
password: String, password: String,
) -> anyhow::Result<Option<String>> { ) -> anyhow::Result<Option<String>> {
@@ -73,7 +85,7 @@ impl UserService for DefaultUserService {
.await?; .await?;
match rec { 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())), true => Ok(Some(user.id.to_string())),
false => Ok(None), false => Ok(None),
}, },

View File

@@ -1,33 +0,0 @@
{
"query": "\n SELECT * from users\n where username=$1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "username",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "password_hash",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false
]
},
"hash": "d3f222cf6c3d9816705426fdbed3b13cb575bb432eb1f33676c0b414e67aecaf"
}

View File

@@ -4,7 +4,8 @@ base: "git@git.front.kjuulh.io:kjuulh/cuddle-rust-plan.git"
vars: vars:
service: "como-backend" service: "como-backend"
deployments: "git@git.front.kjuulh.io:como/deployments.git" deployments: "git@git.front.kjuulh.io:kjuulh/como-deployments.git"
bin_name: como_bin
scripts: scripts:
render_como_templates: render_como_templates:
@@ -17,3 +18,16 @@ scripts:
type: shell type: shell
migrate_como: migrate_como:
type: shell type: shell
new_migration:
type: shell
args:
name:
type: "env"
key: "name"
"sqlx:prepare":
type: shell
"deploy":
type: shell
"test":
type: "rhai"
description: "something"

8
scripts/deploy.sh Executable file
View File

@@ -0,0 +1,8 @@
export $(cat .env | xargs)
cuddle x start_deployment
cuddle x render_templates
cuddle x render_como_templates
cuddle x build_release
cuddle x push_release
cuddle x deploy_release

View File

@@ -2,6 +2,6 @@
set -e set -e
cuddle_cli render_template --template-file $TMP/docker-compose.local_up.yml.tmpl --dest $TMP/docker-compose.local_up.yml cuddle render_template --template-file $TMP/docker-compose.local_up.yml.tmpl --dest $TMP/docker-compose.local_up.yml
docker compose -f $TMP/docker-compose.local_up.yml down -v docker compose -f $TMP/docker-compose.local_up.yml down -v

View File

@@ -2,6 +2,6 @@
set -e set -e
cuddle_cli render_template --template-file $TMP/docker-compose.local_up.yml.tmpl --dest $TMP/docker-compose.local_up.yml cuddle render_template --template-file $TMP/docker-compose.local_up.yml.tmpl --dest $TMP/docker-compose.local_up.yml
docker compose -f $TMP/docker-compose.local_up.yml up -d --remove-orphans --build docker compose -f $TMP/docker-compose.local_up.yml up -d --remove-orphans --build

5
scripts/new_migration.sh Executable file
View File

@@ -0,0 +1,5 @@
#!/bin/bash
export $(cat .env | xargs)
cargo sqlx migrate add --source como_infrastructure/migrations $name

View File

@@ -4,7 +4,7 @@ set -e
deploymentrepo="$TMP/deployments" deploymentrepo="$TMP/deployments"
CUDDLE_FETCH_POLICY=never cuddle_cli render_template \ CUDDLE_FETCH_POLICY=never cuddle render_template \
--template-file "$TMP/.env.example.tmpl" \ --template-file "$TMP/.env.example.tmpl" \
--dest "$deploymentrepo/$SERVICE/env.example" --dest "$deploymentrepo/$SERVICE/env.example"

7
scripts/sqlx:prepare.sh Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
export $(cat .env | xargs)
cd como_infrastructure || return
cargo sqlx prepare -- --all-targets --all-features

1
scripts/test.rhai Normal file
View File

@@ -0,0 +1 @@
print("hello, world!");

View File

@@ -1,4 +1,4 @@
#!/bin/bash #!bin/bash
set -e set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL