Application able to CRUD
This commit is contained in:
commit
d2cb5b3031
19 changed files with 3268 additions and 0 deletions
16
webserver/Cargo.toml
Normal file
16
webserver/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "webserver"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
sqlx = { workspace = true, features = ["runtime-tokio", "sqlite", "chrono"]}
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
axum = { version = "0.6.20", features = ["macros", "headers"] }
|
||||
hyper = "0.14.27"
|
||||
serde_json = "1"
|
||||
accounters = { path = ".." }
|
||||
77
webserver/src/main.rs
Normal file
77
webserver/src/main.rs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use axum::{
|
||||
extract::FromRef,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use hyper::StatusCode;
|
||||
|
||||
mod routes;
|
||||
mod users;
|
||||
|
||||
const DB_URL: &str = "sqlite://sqlite.db";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let db = accounters::create_db(DB_URL).await.unwrap();
|
||||
|
||||
let state = AppState { db: Arc::new(db) };
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(index))
|
||||
.nest(
|
||||
"/api/v1",
|
||||
Router::new()
|
||||
.route("/user", post(routes::create_user))
|
||||
.route("/login", post(routes::login))
|
||||
.route("/accounts", post(routes::accounts::account_create))
|
||||
.route("/accounts", get(routes::accounts::account_list))
|
||||
.route("/accounts/id/:id", get(routes::accounts::account_get))
|
||||
.route(
|
||||
"/accounts/id/:id/transaction",
|
||||
post(routes::transactions::create),
|
||||
)
|
||||
.route(
|
||||
"/accounts/id/:id/transaction",
|
||||
get(routes::transactions::list),
|
||||
)
|
||||
.route(
|
||||
"/accounts/id/:id/update",
|
||||
post(routes::accounts::snapshot_update),
|
||||
)
|
||||
.route(
|
||||
"/accounts/id/:id/recategorize",
|
||||
post(routes::accounts::recategorize),
|
||||
)
|
||||
.route("/categories", post(routes::categories::create))
|
||||
.route("/categories", get(routes::categories::list))
|
||||
.route("/rules", post(routes::rules::create))
|
||||
.route("/rules", get(routes::rules::list)),
|
||||
)
|
||||
.with_state(state);
|
||||
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
db: Arc<SqlitePool>,
|
||||
}
|
||||
|
||||
impl FromRef<AppState> for Arc<SqlitePool> {
|
||||
fn from_ref(state: &AppState) -> Arc<SqlitePool> {
|
||||
state.db.clone()
|
||||
}
|
||||
}
|
||||
|
||||
async fn index() -> (StatusCode, String) {
|
||||
(StatusCode::OK, String::from("Hello, World!"))
|
||||
}
|
||||
43
webserver/src/routes.rs
Normal file
43
webserver/src/routes.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Json, State};
|
||||
use hyper::StatusCode;
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use accounters::models::users::User;
|
||||
|
||||
pub mod accounts;
|
||||
pub mod categories;
|
||||
pub mod rules;
|
||||
pub mod transactions;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateUserRequest {
|
||||
user: String,
|
||||
pass: String,
|
||||
}
|
||||
|
||||
pub async fn create_user(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
Json(user_info): Json<CreateUserRequest>,
|
||||
) -> (StatusCode, String) {
|
||||
let exec = User::create_user(db.as_ref(), &user_info.user, &user_info.pass).await;
|
||||
match exec {
|
||||
Ok(e) => (StatusCode::OK, format!("{}", e.get_id())),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
Json(user_info): Json<CreateUserRequest>,
|
||||
) -> (StatusCode, String) {
|
||||
let user = User::get_user(db.as_ref(), &user_info.user).await.unwrap();
|
||||
|
||||
if user.check_pass(&user_info.pass) {
|
||||
(StatusCode::OK, format!("{}", user.get_id()))
|
||||
} else {
|
||||
(StatusCode::UNAUTHORIZED, String::new())
|
||||
}
|
||||
}
|
||||
87
webserver/src/routes/accounts.rs
Normal file
87
webserver/src/routes/accounts.rs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Json, Path, State};
|
||||
use hyper::StatusCode;
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::users::UserToken;
|
||||
use accounters::models::Account;
|
||||
|
||||
pub async fn account_get(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
uid: UserToken,
|
||||
Path(id): Path<i32>,
|
||||
) -> (StatusCode, String) {
|
||||
match Account::get_by_id(db.as_ref(), id).await {
|
||||
Ok(a) => {
|
||||
if a.get_user() == uid.user_id {
|
||||
(StatusCode::OK, serde_json::to_string(&a).unwrap())
|
||||
} else {
|
||||
(StatusCode::UNAUTHORIZED, String::new())
|
||||
}
|
||||
}
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct AccountRequestCreate {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub async fn account_create(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
uid: UserToken,
|
||||
Json(account): Json<AccountRequestCreate>,
|
||||
) -> (StatusCode, String) {
|
||||
match Account::new(db.as_ref(), uid.user_id, &account.name).await {
|
||||
Ok(a) => (StatusCode::OK, serde_json::to_string(&a).unwrap()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn account_list(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
uid: UserToken,
|
||||
) -> (StatusCode, String) {
|
||||
match Account::list(db.as_ref(), uid.user_id).await {
|
||||
Ok(a) => (StatusCode::OK, serde_json::to_string(&a).unwrap()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn snapshot_update(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
uid: UserToken,
|
||||
Path(account): Path<i32>,
|
||||
) -> (StatusCode, String) {
|
||||
let account = Account::get_by_id(db.as_ref(), account).await.unwrap();
|
||||
if account.get_user() != uid.user_id {
|
||||
return (StatusCode::UNAUTHORIZED, String::new());
|
||||
}
|
||||
|
||||
match account.recalculate_snapshots(db.as_ref(), None).await {
|
||||
Ok(_) => (StatusCode::OK, String::new()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn recategorize(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
uid: UserToken,
|
||||
Path(account): Path<i32>,
|
||||
) -> (StatusCode, String) {
|
||||
let account = Account::get_by_id(db.as_ref(), account).await.unwrap();
|
||||
if account.get_user() != uid.user_id {
|
||||
return (StatusCode::UNAUTHORIZED, String::new());
|
||||
}
|
||||
|
||||
match account
|
||||
.recategorize_transactions(db.as_ref(), None, None)
|
||||
.await
|
||||
{
|
||||
Ok(_) => (StatusCode::OK, String::new()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
|
||||
}
|
||||
}
|
||||
33
webserver/src/routes/categories.rs
Normal file
33
webserver/src/routes/categories.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use axum::{extract::State, Json};
|
||||
use hyper::StatusCode;
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::users::UserToken;
|
||||
use accounters::models::categories::Category;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CategoryCreateRequest {
|
||||
name: String,
|
||||
description: String,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
uid: UserToken,
|
||||
Json(new_category): Json<CategoryCreateRequest>,
|
||||
) -> (StatusCode, String) {
|
||||
match Category::new(db.as_ref(), &new_category.name, &new_category.description).await {
|
||||
Ok(_) => (StatusCode::OK, String::new()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list(State(db): State<Arc<SqlitePool>>, uid: UserToken) -> (StatusCode, String) {
|
||||
match Category::list(db.as_ref()).await {
|
||||
Ok(c) => (StatusCode::OK, serde_json::to_string(&c).unwrap()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
|
||||
}
|
||||
}
|
||||
33
webserver/src/routes/rules.rs
Normal file
33
webserver/src/routes/rules.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Json, State};
|
||||
use hyper::StatusCode;
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::users::UserToken;
|
||||
use accounters::models::rules::Rule;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RuleCreateRequest {
|
||||
regex: String,
|
||||
category: i32,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
uid: UserToken,
|
||||
Json(rule): Json<RuleCreateRequest>,
|
||||
) -> (StatusCode, String) {
|
||||
match Rule::new(db.as_ref(), uid.user_id, rule.regex, rule.category).await {
|
||||
Ok(r) => (StatusCode::OK, serde_json::to_string(&r).unwrap()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list(State(db): State<Arc<SqlitePool>>, uid: UserToken) -> (StatusCode, String) {
|
||||
match Rule::list_by_user(db.as_ref(), uid.user_id).await {
|
||||
Ok(rule_list) => (StatusCode::OK, serde_json::to_string(&rule_list).unwrap()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
|
||||
}
|
||||
}
|
||||
62
webserver/src/routes/transactions.rs
Normal file
62
webserver/src/routes/transactions.rs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Json, Path, Query, State};
|
||||
use chrono::{offset::Utc, DateTime};
|
||||
use hyper::StatusCode;
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use accounters::models::Transaction;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TransactionContent {
|
||||
description: String,
|
||||
timestamp: DateTime<Utc>,
|
||||
category: Option<String>,
|
||||
amount: i32,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
Path(account): Path<i32>,
|
||||
Json(txcnt): Json<TransactionContent>,
|
||||
) -> (StatusCode, String) {
|
||||
match Transaction::new(
|
||||
db.as_ref(),
|
||||
account,
|
||||
&txcnt.description,
|
||||
&txcnt.timestamp,
|
||||
None,
|
||||
txcnt.amount,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(tx) => (StatusCode::OK, serde_json::to_string(&tx).unwrap()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PaginationOptions {
|
||||
pub limit: Option<i32>,
|
||||
pub offset: Option<i32>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(db): State<Arc<SqlitePool>>,
|
||||
Path(account): Path<i32>,
|
||||
Query(pagination): Query<PaginationOptions>,
|
||||
) -> (StatusCode, String) {
|
||||
match Transaction::list(
|
||||
db.as_ref(),
|
||||
account,
|
||||
pagination.limit.unwrap_or(100),
|
||||
pagination.offset.unwrap_or(0),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(txs) => (StatusCode::OK, serde_json::to_string(&txs).unwrap()),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
|
||||
}
|
||||
}
|
||||
42
webserver/src/users.rs
Normal file
42
webserver/src/users.rs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
use axum::{
|
||||
async_trait,
|
||||
extract::FromRequestParts,
|
||||
headers::authorization::Bearer,
|
||||
headers::Authorization,
|
||||
http::request::Parts,
|
||||
response::{IntoResponse, Redirect},
|
||||
RequestPartsExt, TypedHeader,
|
||||
};
|
||||
|
||||
pub struct AuthRedirect;
|
||||
|
||||
impl IntoResponse for AuthRedirect {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
Redirect::temporary("/login").into_response()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UserToken {
|
||||
pub user_id: i32,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<S> FromRequestParts<S> for UserToken
|
||||
where
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AuthRedirect;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let auth = parts
|
||||
.extract::<TypedHeader<Authorization<Bearer>>>()
|
||||
.await
|
||||
.map_err(|e| panic!("Could not get cookies: {e}"))
|
||||
.unwrap();
|
||||
let ut = UserToken {
|
||||
user_id: auth.0 .0.token().parse().unwrap(),
|
||||
};
|
||||
Ok(ut)
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue