Added apis

This commit is contained in:
2022-10-04 11:06:48 +02:00
parent 6234cf18e8
commit ae74f66c3a
28 changed files with 392 additions and 300 deletions

View File

@@ -6,9 +6,11 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
como_gql = { path = "../como_gql" }
como_core = { path = "../como_core" }
como_domain = { path = "../como_domain" }
como_infrastructure = { path = "../como_infrastructure" }
como_api = { path = "../como_api" }
async-graphql = "4.0.6"
async-graphql-axum = "*"
@@ -34,3 +36,4 @@ tower-http = { version = "0.3.4", features = ["full"] }
argon2 = "0.4"
rand_core = { version = "0.6", features = ["std"] }
cookie = { version = "0.16", features = ["secure", "percent-encode"] }
clap = { version = "3", features = ["derive", "env"] }

View File

@@ -1,6 +0,0 @@
// generated by `sqlx migrate build-script`
fn main() {
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed=migrations");
}

View File

@@ -1,56 +0,0 @@
{
"db": "PostgreSQL",
"3b4484c5ccfd4dcb887c4e978fe6e45d4c9ecc2a73909be207dced79ddf17d87": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
}
],
"nullable": [
false
],
"parameters": {
"Left": [
"Varchar",
"Varchar"
]
}
},
"query": "\n INSERT INTO users (username, password_hash) \n VALUES ( $1, $2 ) \n RETURNING id\n "
},
"d3f222cf6c3d9816705426fdbed3b13cb575bb432eb1f33676c0b414e67aecaf": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Uuid"
},
{
"name": "username",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "password_hash",
"ordinal": 2,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "\n SELECT * from users\n where username=$1\n "
}
}

View File

@@ -1,2 +0,0 @@
pub mod users;

View File

@@ -1,57 +0,0 @@
use async_graphql::{Context, EmptySubscription, Object, Schema};
use como_domain::item::{requests::CreateItemDto, responses::CreatedItemDto};
use crate::services::users_service::UserService;
pub type CibusSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>;
pub struct MutationRoot;
#[Object]
impl MutationRoot {
async fn login(
&self,
ctx: &Context<'_>,
username: String,
password: String,
) -> anyhow::Result<bool> {
let user_service = ctx.data_unchecked::<UserService>();
let valid = user_service.validate_user(username, password).await?;
let returnvalid = match valid {
Some(..) => true,
None => false,
};
Ok(returnvalid)
}
async fn register(
&self,
ctx: &Context<'_>,
username: String,
password: String,
) -> anyhow::Result<String> {
let user_service = ctx.data_unchecked::<UserService>();
let user_id = user_service.add_user(username, password).await?;
Ok(user_id)
}
async fn create_item(
&self,
ctx: &Context<'_>,
item: CreateItemDto,
) -> anyhow::Result<CreatedItemDto> {
let services_register = ctx.data_unchecked::<ServiceRegister>()
}
}
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn get_upcoming(&self, _ctx: &Context<'_>) -> Vec<Event> {}
}

View File

@@ -1,11 +1,9 @@
use std::env::{self, current_dir};
use std::{
env::{self, current_dir},
sync::Arc,
};
mod error;
mod gqlx;
mod graphql;
mod services;
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use axum::{
extract::Extension,
http::{Method, StatusCode},
@@ -14,57 +12,31 @@ use axum::{
Json, Router,
};
use axum_extra::extract::cookie::Key;
use clap::Parser;
use async_graphql::{
http::{playground_source, GraphQLPlaygroundConfig},
EmptySubscription, Schema,
};
use anyhow::Context;
use axum_sessions::{
async_session::MemoryStore,
extractors::{ReadableSession, WritableSession},
SessionLayer,
};
use error::AppError;
use graphql::CibusSchema;
use como_api::router::Api;
use como_infrastructure::{
configs::AppConfig, database::ConnectionPoolManager, register::ServiceRegister,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use services::users_service;
use sqlx::PgPool;
use tower_http::{cors::CorsLayer, trace::TraceLayer};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use crate::graphql::{MutationRoot, QueryRoot};
async fn graphql_handler(
schema: Extension<CibusSchema>,
session: ReadableSession,
req: GraphQLRequest,
) -> Result<GraphQLResponse, StatusCode> {
let req = req.into_inner();
//if let Some(user_id) = session.get::<String>("userId") {
// req = req.data(user_id);
return Ok(schema.execute(req).await.into());
//} else if let Some(on) = &req.operation_name {
// if on == "IntrospectionQuery" {
// return Ok(schema.execute(req).await.into());
// }
//}
//Err(StatusCode::FORBIDDEN)
}
async fn graphql_playground() -> impl IntoResponse {
Html(playground_source(GraphQLPlaygroundConfig::new("/")))
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Environment
tracing::info!("Loading dotenv");
dotenv::dotenv()?;
// Logging
let config = Arc::new(AppConfig::parse());
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| {
@@ -75,102 +47,13 @@ async fn main() -> anyhow::Result<()> {
.with(tracing_subscriber::fmt::layer())
.init();
// Database
tracing::info!("Creating pool");
let db_url = env::var("DATABASE_URL")?;
let pool = PgPool::connect(&db_url).await?;
let pool = ConnectionPoolManager::new_pool(&config.database_url, true).await?;
// Database Migrate
tracing::info!("Migrating db");
sqlx::migrate!("db/migrations").run(&pool).await?;
let service_register = ServiceRegister::new(pool, config.clone());
tracing::info!("current path: {}", current_dir()?.to_string_lossy());
// Schema
println!("Building schema");
let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription)
.data(users_service::UserService::new(pool.clone()))
.finish();
// CORS
let cors = vec!["http://localhost:3000".parse().unwrap()];
// Key
let key = Key::generate();
let store = MemoryStore::new();
let session_layer = SessionLayer::new(store, key.master());
// Webserver
tracing::info!("Building router");
let app = Router::new()
.route("/", get(graphql_playground).post(graphql_handler))
.route("/auth/login", post(login))
.route("/auth/register", post(register))
.layer(TraceLayer::new_for_http())
.layer(Extension(schema))
.layer(Extension(key))
.layer(Extension(pool))
.layer(session_layer)
.layer(
CorsLayer::new()
.allow_origin(cors)
.allow_headers([axum::http::header::CONTENT_TYPE])
.allow_methods([Method::GET, Method::POST, Method::OPTIONS]),
);
tracing::info!("Starting webserver");
axum::Server::bind(&"0.0.0.0:3001".parse().unwrap())
.serve(app.into_make_service())
Api::new(3001, &config.cors_origin, service_register.clone())
.await
.unwrap();
.context("could not initialize API")?;
Ok(())
}
#[derive(Serialize, Deserialize)]
pub struct Credentials {
pub username: String,
pub password: String,
}
async fn login(
Json(credentials): Json<Credentials>,
Extension(pool): Extension<PgPool>,
mut session: WritableSession,
) -> Result<Json<Value>, error::AppError> {
let us = users_service::UserService::new(pool);
match us
.validate_user(credentials.username, credentials.password)
.await
.map_err(|e| {
tracing::error!("could not validate user: {}", e);
AppError::InternalServerError
})? {
Some(user_id) => {
if let Err(e) = session.insert("userId", user_id.clone()) {
tracing::error!("could not insert session: {}", e);
return Err(AppError::InternalServerError);
}
Ok(Json(json!({ "userId": user_id })))
}
None => Err(AppError::WrongCredentials),
}
}
async fn register(
Json(credentials): Json<Credentials>,
Extension(pool): Extension<PgPool>,
) -> Result<Json<Value>, error::AppError> {
let us = users_service::UserService::new(pool)
.add_user(credentials.username, credentials.password)
.await
.map_err(|e| {
tracing::error!("could not add user: {}", e);
AppError::InternalServerError
})?;
Ok(Json(json!({ "userId": us })))
}

View File

@@ -1 +0,0 @@
pub mod users_service;

View File

@@ -1,78 +0,0 @@
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),
}
}
}

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"
}