Compare commits
No commits in common. "c7f8dc6198704205361add9134bee2d3b83299c2" and "6234cf18e89ff82b32e092ab87ec88cbd71e41fb" have entirely different histories.
c7f8dc6198
...
6234cf18e8
7
.env
7
.env
@ -1,11 +1,4 @@
|
|||||||
POSTGRES_DB=como
|
POSTGRES_DB=como
|
||||||
POSTGRES_USER=como
|
POSTGRES_USER=como
|
||||||
POSTGRES_PASSWORD=somenotverysecurepassword
|
POSTGRES_PASSWORD=somenotverysecurepassword
|
||||||
|
|
||||||
DATABASE_URL="postgres://como:somenotverysecurepassword@localhost:5432/como"
|
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
|
|
||||||
|
62
Cargo.lock
generated
62
Cargo.lock
generated
@ -189,7 +189,6 @@ dependencies = [
|
|||||||
"static_assertions",
|
"static_assertions",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"uuid",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -640,35 +639,6 @@ dependencies = [
|
|||||||
"os_str_bytes",
|
"os_str_bytes",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "como_api"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"anyhow",
|
|
||||||
"argon2",
|
|
||||||
"async-graphql",
|
|
||||||
"async-graphql-axum",
|
|
||||||
"axum",
|
|
||||||
"axum-extra",
|
|
||||||
"axum-sessions",
|
|
||||||
"como_core",
|
|
||||||
"como_domain",
|
|
||||||
"como_gql",
|
|
||||||
"como_infrastructure",
|
|
||||||
"cookie",
|
|
||||||
"dotenv",
|
|
||||||
"rand_core",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"sqlx 0.6.1",
|
|
||||||
"tokio",
|
|
||||||
"tower",
|
|
||||||
"tower-http",
|
|
||||||
"tracing",
|
|
||||||
"tracing-subscriber",
|
|
||||||
"uuid",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "como_bin"
|
name = "como_bin"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@ -680,11 +650,8 @@ dependencies = [
|
|||||||
"axum",
|
"axum",
|
||||||
"axum-extra",
|
"axum-extra",
|
||||||
"axum-sessions",
|
"axum-sessions",
|
||||||
"clap",
|
|
||||||
"como_api",
|
|
||||||
"como_core",
|
"como_core",
|
||||||
"como_domain",
|
"como_domain",
|
||||||
"como_gql",
|
|
||||||
"como_infrastructure",
|
"como_infrastructure",
|
||||||
"cookie",
|
"cookie",
|
||||||
"dotenv",
|
"dotenv",
|
||||||
@ -707,7 +674,6 @@ dependencies = [
|
|||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
"clap",
|
"clap",
|
||||||
"como_domain",
|
|
||||||
"dotenv",
|
"dotenv",
|
||||||
"mockall",
|
"mockall",
|
||||||
"rust-argon2",
|
"rust-argon2",
|
||||||
@ -727,39 +693,11 @@ name = "como_domain"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"async-graphql",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "como_gql"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"anyhow",
|
|
||||||
"argon2",
|
|
||||||
"async-graphql",
|
|
||||||
"async-graphql-axum",
|
|
||||||
"axum",
|
|
||||||
"axum-extra",
|
|
||||||
"axum-sessions",
|
|
||||||
"como_core",
|
|
||||||
"como_domain",
|
|
||||||
"como_infrastructure",
|
|
||||||
"cookie",
|
|
||||||
"dotenv",
|
|
||||||
"rand_core",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"sqlx 0.6.1",
|
|
||||||
"tokio",
|
|
||||||
"tower-http",
|
|
||||||
"tracing",
|
|
||||||
"tracing-subscriber",
|
|
||||||
"uuid",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "como_infrastructure"
|
name = "como_infrastructure"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
@ -1,9 +1,2 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = ["como_bin", "como_core", "como_domain", "como_infrastructure"]
|
||||||
"como_bin",
|
|
||||||
"como_core",
|
|
||||||
"como_domain",
|
|
||||||
"como_infrastructure",
|
|
||||||
"como_gql",
|
|
||||||
"como_api",
|
|
||||||
]
|
|
||||||
|
@ -1,39 +0,0 @@
|
|||||||
[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"] }
|
|
@ -1,21 +0,0 @@
|
|||||||
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 +0,0 @@
|
|||||||
pub mod graphql;
|
|
@ -1,2 +0,0 @@
|
|||||||
mod controllers;
|
|
||||||
pub mod router;
|
|
@ -1,44 +0,0 @@
|
|||||||
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 new(
|
|
||||||
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,11 +6,9 @@ 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_core = { path = "../como_core" }
|
como_core = { path = "../como_core" }
|
||||||
como_domain = { path = "../como_domain" }
|
como_domain = { path = "../como_domain" }
|
||||||
como_infrastructure = { path = "../como_infrastructure" }
|
como_infrastructure = { path = "../como_infrastructure" }
|
||||||
como_api = { path = "../como_api" }
|
|
||||||
|
|
||||||
async-graphql = "4.0.6"
|
async-graphql = "4.0.6"
|
||||||
async-graphql-axum = "*"
|
async-graphql-axum = "*"
|
||||||
@ -36,4 +34,3 @@ tower-http = { version = "0.3.4", features = ["full"] }
|
|||||||
argon2 = "0.4"
|
argon2 = "0.4"
|
||||||
rand_core = { version = "0.6", features = ["std"] }
|
rand_core = { version = "0.6", features = ["std"] }
|
||||||
cookie = { version = "0.16", features = ["secure", "percent-encode"] }
|
cookie = { version = "0.16", features = ["secure", "percent-encode"] }
|
||||||
clap = { version = "3", features = ["derive", "env"] }
|
|
||||||
|
6
como_bin/build.rs
Normal file
6
como_bin/build.rs
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
// generated by `sqlx migrate build-script`
|
||||||
|
fn main() {
|
||||||
|
// trigger recompilation when a new migration is added
|
||||||
|
println!("cargo:rerun-if-changed=migrations");
|
||||||
|
}
|
||||||
|
|
56
como_bin/sqlx-data.json
Normal file
56
como_bin/sqlx-data.json
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"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 "
|
||||||
|
}
|
||||||
|
}
|
2
como_bin/src/gqlx/mod.rs
Normal file
2
como_bin/src/gqlx/mod.rs
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
pub mod users;
|
||||||
|
|
0
como_bin/src/gqlx/users.rs
Normal file
0
como_bin/src/gqlx/users.rs
Normal file
@ -1,9 +1,10 @@
|
|||||||
use async_graphql::{Context, EmptySubscription, Object, Schema};
|
use async_graphql::{Context, EmptySubscription, Object, Schema};
|
||||||
|
|
||||||
use como_domain::item::{requests::CreateItemDto, responses::CreatedItemDto};
|
use como_domain::item::{requests::CreateItemDto, responses::CreatedItemDto};
|
||||||
use como_infrastructure::register::ServiceRegister;
|
|
||||||
|
|
||||||
pub type ComoSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>;
|
use crate::services::users_service::UserService;
|
||||||
|
|
||||||
|
pub type CibusSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>;
|
||||||
|
|
||||||
pub struct MutationRoot;
|
pub struct MutationRoot;
|
||||||
|
|
||||||
@ -15,12 +16,9 @@ impl MutationRoot {
|
|||||||
username: String,
|
username: String,
|
||||||
password: String,
|
password: String,
|
||||||
) -> anyhow::Result<bool> {
|
) -> anyhow::Result<bool> {
|
||||||
let service_register = ctx.data_unchecked::<ServiceRegister>();
|
let user_service = ctx.data_unchecked::<UserService>();
|
||||||
|
|
||||||
let valid = service_register
|
let valid = user_service.validate_user(username, password).await?;
|
||||||
.user_service
|
|
||||||
.validate_user(username, password)
|
|
||||||
.await?;
|
|
||||||
let returnvalid = match valid {
|
let returnvalid = match valid {
|
||||||
Some(..) => true,
|
Some(..) => true,
|
||||||
None => false,
|
None => false,
|
||||||
@ -35,12 +33,9 @@ impl MutationRoot {
|
|||||||
username: String,
|
username: String,
|
||||||
password: String,
|
password: String,
|
||||||
) -> anyhow::Result<String> {
|
) -> anyhow::Result<String> {
|
||||||
let service_register = ctx.data_unchecked::<ServiceRegister>();
|
let user_service = ctx.data_unchecked::<UserService>();
|
||||||
|
|
||||||
let user_id = service_register
|
let user_id = user_service.add_user(username, password).await?;
|
||||||
.user_service
|
|
||||||
.add_user(username, password)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(user_id)
|
Ok(user_id)
|
||||||
}
|
}
|
||||||
@ -50,11 +45,7 @@ impl MutationRoot {
|
|||||||
ctx: &Context<'_>,
|
ctx: &Context<'_>,
|
||||||
item: CreateItemDto,
|
item: CreateItemDto,
|
||||||
) -> anyhow::Result<CreatedItemDto> {
|
) -> anyhow::Result<CreatedItemDto> {
|
||||||
let services_register = ctx.data_unchecked::<ServiceRegister>();
|
let services_register = ctx.data_unchecked::<ServiceRegister>()
|
||||||
|
|
||||||
let created_item = services_register.item_service.add_item(item).await?;
|
|
||||||
|
|
||||||
Ok(created_item)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -62,7 +53,5 @@ pub struct QueryRoot;
|
|||||||
|
|
||||||
#[Object]
|
#[Object]
|
||||||
impl QueryRoot {
|
impl QueryRoot {
|
||||||
async fn hello(&self, _ctx: &Context<'_>) -> String {
|
async fn get_upcoming(&self, _ctx: &Context<'_>) -> Vec<Event> {}
|
||||||
"hello".into()
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -1,41 +1,176 @@
|
|||||||
use std::sync::Arc;
|
use std::env::{self, current_dir};
|
||||||
|
|
||||||
mod error;
|
mod error;
|
||||||
|
mod gqlx;
|
||||||
|
mod graphql;
|
||||||
|
mod services;
|
||||||
|
|
||||||
use clap::Parser;
|
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
|
||||||
|
use axum::{
|
||||||
use anyhow::Context;
|
extract::Extension,
|
||||||
|
http::{Method, StatusCode},
|
||||||
use como_api::router::Api;
|
response::{Html, IntoResponse},
|
||||||
use como_infrastructure::{
|
routing::{get, post},
|
||||||
configs::AppConfig, database::ConnectionPoolManager, register::ServiceRegister,
|
Json, Router,
|
||||||
};
|
};
|
||||||
|
use axum_extra::extract::cookie::Key;
|
||||||
|
|
||||||
|
use async_graphql::{
|
||||||
|
http::{playground_source, GraphQLPlaygroundConfig},
|
||||||
|
EmptySubscription, Schema,
|
||||||
|
};
|
||||||
|
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 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]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
// Environment
|
||||||
tracing::info!("Loading dotenv");
|
tracing::info!("Loading dotenv");
|
||||||
dotenv::dotenv()?;
|
dotenv::dotenv()?;
|
||||||
|
|
||||||
let config = Arc::new(AppConfig::parse());
|
// Logging
|
||||||
|
|
||||||
tracing_subscriber::registry()
|
tracing_subscriber::registry()
|
||||||
.with(tracing_subscriber::EnvFilter::new(&config.rust_log))
|
.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::fmt::layer())
|
.with(tracing_subscriber::fmt::layer())
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
let pool = ConnectionPoolManager::new_pool(&config.database_url, true).await?;
|
// Database
|
||||||
|
tracing::info!("Creating pool");
|
||||||
|
let db_url = env::var("DATABASE_URL")?;
|
||||||
|
let pool = PgPool::connect(&db_url).await?;
|
||||||
|
|
||||||
let service_register = ServiceRegister::new(pool, config.clone());
|
// Database Migrate
|
||||||
|
tracing::info!("Migrating db");
|
||||||
|
sqlx::migrate!("db/migrations").run(&pool).await?;
|
||||||
|
|
||||||
Api::new(
|
tracing::info!("current path: {}", current_dir()?.to_string_lossy());
|
||||||
config.api_port,
|
|
||||||
&config.cors_origin,
|
// Schema
|
||||||
service_register.clone(),
|
println!("Building schema");
|
||||||
)
|
let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription)
|
||||||
.await
|
.data(users_service::UserService::new(pool.clone()))
|
||||||
.context("could not initialize API")?;
|
.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();
|
||||||
|
|
||||||
Ok(())
|
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
como_bin/src/services/mod.rs
Normal file
1
como_bin/src/services/mod.rs
Normal file
@ -0,0 +1 @@
|
|||||||
|
pub mod users_service;
|
78
como_bin/src/services/users_service.rs
Normal file
78
como_bin/src/services/users_service.rs
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
use anyhow::anyhow;
|
||||||
|
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
|
||||||
|
use rand_core::OsRng;
|
||||||
|
use sqlx::{Pool, Postgres};
|
||||||
|
|
||||||
|
pub struct UserService {
|
||||||
|
pgx: Pool<Postgres>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserService {
|
||||||
|
pub fn new(pgx: Pool<Postgres>) -> Self {
|
||||||
|
Self { pgx }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn add_user(&self, username: String, password: String) -> anyhow::Result<String> {
|
||||||
|
let hashed_password = self.hash_password(password)?;
|
||||||
|
|
||||||
|
let rec = sqlx::query!(
|
||||||
|
r#"
|
||||||
|
INSERT INTO users (username, password_hash)
|
||||||
|
VALUES ( $1, $2 )
|
||||||
|
RETURNING id
|
||||||
|
"#,
|
||||||
|
username,
|
||||||
|
hashed_password
|
||||||
|
)
|
||||||
|
.fetch_one(&self.pgx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(rec.id.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn validate_user(
|
||||||
|
&self,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
) -> anyhow::Result<Option<String>> {
|
||||||
|
let rec = sqlx::query!(
|
||||||
|
r#"
|
||||||
|
SELECT * from users
|
||||||
|
where username=$1
|
||||||
|
"#,
|
||||||
|
username,
|
||||||
|
)
|
||||||
|
.fetch_optional(&self.pgx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
match rec {
|
||||||
|
Some(user) => match self.validate_password(password, user.password_hash)? {
|
||||||
|
true => Ok(Some(user.id.to_string())),
|
||||||
|
false => Ok(None),
|
||||||
|
},
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -6,7 +6,6 @@ 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" }
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
axum = "0.5.1"
|
axum = "0.5.1"
|
||||||
|
|
||||||
|
@ -1,11 +1,8 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use como_domain::item::{requests::CreateItemDto, responses::CreatedItemDto};
|
|
||||||
|
|
||||||
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>;
|
|
||||||
}
|
|
||||||
|
@ -5,11 +5,4 @@ use async_trait::async_trait;
|
|||||||
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 validate_user(
|
|
||||||
&self,
|
|
||||||
username: String,
|
|
||||||
password: String,
|
|
||||||
) -> anyhow::Result<Option<String>>;
|
|
||||||
}
|
|
||||||
|
@ -6,7 +6,6 @@ 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"] }
|
|
||||||
anyhow = "1.0.60"
|
anyhow = "1.0.60"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0.68"
|
serde_json = "1.0.68"
|
||||||
|
@ -1,11 +1,10 @@
|
|||||||
pub mod requests;
|
pub mod requests;
|
||||||
pub mod responses;
|
pub mod responses;
|
||||||
|
|
||||||
use async_graphql::{Enum, InputObject, SimpleObject};
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Enum, Copy)]
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
pub enum ItemState {
|
pub enum ItemState {
|
||||||
Created,
|
Created,
|
||||||
Done,
|
Done,
|
||||||
@ -13,7 +12,7 @@ pub enum ItemState {
|
|||||||
Deleted,
|
Deleted,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject, SimpleObject)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
pub struct ItemDto {
|
pub struct ItemDto {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
use async_graphql::InputObject;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, InputObject)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
pub struct CreateItemDto {
|
pub struct CreateItemDto {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
|
@ -1,36 +0,0 @@
|
|||||||
[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"] }
|
|
@ -1,24 +0,0 @@
|
|||||||
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 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")))
|
|
||||||
}
|
|
@ -7,7 +7,7 @@ pub struct AppConfig {
|
|||||||
#[clap(long, env)]
|
#[clap(long, env)]
|
||||||
pub token_secret: String,
|
pub token_secret: String,
|
||||||
#[clap(long, env)]
|
#[clap(long, env)]
|
||||||
pub api_port: u32,
|
pub port: u32,
|
||||||
#[clap(long, env)]
|
#[clap(long, env)]
|
||||||
pub run_migrations: bool,
|
pub run_migrations: bool,
|
||||||
#[clap(long, env)]
|
#[clap(long, env)]
|
||||||
@ -15,3 +15,4 @@ pub struct AppConfig {
|
|||||||
#[clap(long, env)]
|
#[clap(long, env)]
|
||||||
pub cors_origin: String,
|
pub cors_origin: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -25,7 +25,7 @@ impl ConnectionPoolManager {
|
|||||||
sqlx::migrate!()
|
sqlx::migrate!()
|
||||||
.run(&pool)
|
.run(&pool)
|
||||||
.await
|
.await
|
||||||
.context("error while running database migrations")?;
|
.context("error while running database migrations");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(pool)
|
Ok(pool)
|
||||||
|
@ -20,12 +20,12 @@ pub struct ServiceRegister {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ServiceRegister {
|
impl ServiceRegister {
|
||||||
pub fn new(pool: ConnectionPool, _config: Arc<AppConfig>) -> Self {
|
pub fn new(_pool: ConnectionPool, _config: AppConfig) -> Self {
|
||||||
info!("creating services");
|
info!("creating services");
|
||||||
|
|
||||||
let item_service = Arc::new(DefaultItemService::new()) as DynItemService;
|
let item_service = Arc::new(DefaultItemService::new()) as DynItemService;
|
||||||
let project_service = Arc::new(DefaultProjectService::new()) as DynProjectService;
|
let project_service = Arc::new(DefaultProjectService::new()) as DynProjectService;
|
||||||
let user_service = Arc::new(DefaultUserService::new(pool.clone())) as DynUserService;
|
let user_service = Arc::new(DefaultUserService::new()) as DynUserService;
|
||||||
|
|
||||||
info!("services created succesfully");
|
info!("services created succesfully");
|
||||||
|
|
||||||
|
@ -1,6 +1,4 @@
|
|||||||
use axum::async_trait;
|
|
||||||
use como_core::items::ItemService;
|
use como_core::items::ItemService;
|
||||||
use como_domain::item::{requests::CreateItemDto, responses::CreatedItemDto};
|
|
||||||
|
|
||||||
pub struct DefaultItemService {}
|
pub struct DefaultItemService {}
|
||||||
|
|
||||||
@ -10,9 +8,4 @@ impl DefaultItemService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
impl ItemService for DefaultItemService {}
|
||||||
impl ItemService for DefaultItemService {
|
|
||||||
async fn add_item(&self, _item: CreateItemDto) -> anyhow::Result<CreatedItemDto> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,83 +1,11 @@
|
|||||||
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
|
|
||||||
use axum::async_trait;
|
|
||||||
use como_core::users::UserService;
|
use como_core::users::UserService;
|
||||||
use rand_core::OsRng;
|
|
||||||
|
|
||||||
use crate::database::ConnectionPool;
|
pub struct DefaultUserService {}
|
||||||
|
|
||||||
pub struct DefaultUserService {
|
|
||||||
pool: ConnectionPool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DefaultUserService {
|
impl DefaultUserService {
|
||||||
pub fn new(pool: ConnectionPool) -> Self {
|
pub fn new() -> Self {
|
||||||
Self { pool }
|
Self {}
|
||||||
}
|
|
||||||
|
|
||||||
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 {}
|
||||||
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!(
|
|
||||||
r#"
|
|
||||||
INSERT INTO users (username, password_hash)
|
|
||||||
VALUES ( $1, $2 )
|
|
||||||
RETURNING id
|
|
||||||
"#,
|
|
||||||
username,
|
|
||||||
hashed_password
|
|
||||||
)
|
|
||||||
.fetch_one(&self.pool)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(rec.id.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn validate_user(
|
|
||||||
&self,
|
|
||||||
username: String,
|
|
||||||
password: String,
|
|
||||||
) -> anyhow::Result<Option<String>> {
|
|
||||||
let rec = sqlx::query!(
|
|
||||||
r#"
|
|
||||||
SELECT * from users
|
|
||||||
where username=$1
|
|
||||||
"#,
|
|
||||||
username,
|
|
||||||
)
|
|
||||||
.fetch_optional(&self.pool)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
match rec {
|
|
||||||
Some(user) => match self.validate_password(password, user.password_hash)? {
|
|
||||||
true => Ok(Some(user.id.to_string())),
|
|
||||||
false => Ok(None),
|
|
||||||
},
|
|
||||||
None => Ok(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -2,4 +2,4 @@
|
|||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
(cd como_bin; cargo watch -x run)
|
cargo run como_bin/
|
||||||
|
Loading…
Reference in New Issue
Block a user