Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
mobergmann committed Nov 26, 2023
1 parent a72b6ab commit 9b475a6
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 47 deletions.
36 changes: 18 additions & 18 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use sqlx::sqlite::{SqliteConnectOptions};
use sqlx::{ConnectOptions, Executor, SqlitePool};
use sqlx::{Executor, SqlitePool};
use std::str::FromStr;

/// Path to the SQLite database
Expand All @@ -20,9 +20,9 @@ impl From<sqlx::Error> for Error {

/// Initialize the database.
/// If the SQLite-File does not exist create it and create the tables.
pub async fn init() -> Result<SqlitePool, Error> {
let pool_options = SqliteConnectOptions::new()
.filename(DB_URI)
pub async fn init() -> Result<SqlitePool, sqlx::Error> {
let pool_options = SqliteConnectOptions::from_str(DB_URI)?
//.filename(DB_URI)
.create_if_missing(true);

let pool = SqlitePool::connect_with(pool_options).await?;
Expand Down Expand Up @@ -65,7 +65,7 @@ pub mod account {
use sqlx::SqlitePool;

/// Returns an account by id
pub async fn get_id(pool: &SqlitePool, id: i64) -> Result<Account, Error> {
pub async fn get_id(pool: SqlitePool, id: i64) -> Result<Account, Error> {
let mut connection = pool.acquire().await?;

let user: Account = sqlx::query_as("select * from users where id = $1")
Expand All @@ -77,7 +77,7 @@ pub mod account {
}

/// Returns an account by name
pub async fn get(pool: &SqlitePool, username: &String) -> Result<Account, Error> {
pub async fn get(pool: SqlitePool, username: &String) -> Result<Account, Error> {
let mut connection = pool.acquire().await?;

let user: Account = sqlx::query_as("select * from users where name = $1")
Expand All @@ -89,7 +89,7 @@ pub mod account {
}

/// Inserts an Account and returns the inserted account
pub async fn insert(pool: &SqlitePool, account: &BareAccount) -> Result<Account, Error> {
pub async fn insert(pool: SqlitePool, account: &BareAccount) -> Result<Account, Error> {
let password_hash = hasher::hash(&account.password);

let mut connection = pool.acquire().await?;
Expand All @@ -107,7 +107,7 @@ pub mod account {

/// Updates an account and returns the updated account
pub async fn update(
pool: &SqlitePool,
pool: SqlitePool,
id: i64,
account: &EditAccount,
) -> Result<Account, Error> {
Expand All @@ -116,7 +116,7 @@ pub mod account {
}

/// Deletes an Account and returns the deleted account
pub async fn delete(pool: &SqlitePool, id: i64) -> Result<Account, Error> {
pub async fn delete(pool: SqlitePool, id: i64) -> Result<Account, Error> {
let mut connection = pool.acquire().await?;
Err(Error::NotImplemented)
}
Expand All @@ -128,7 +128,7 @@ pub mod user {
use sqlx::SqlitePool;

/// Returns a user by username
pub async fn get(pool: &SqlitePool, username: &String) -> Result<User, Error> {
pub async fn get(pool: SqlitePool, username: &String) -> Result<User, Error> {
let mut connection = pool.acquire().await?;

let user: Account = sqlx::query_as("select * from users where name = $1")
Expand All @@ -140,7 +140,7 @@ pub mod user {
}

/// Returns a user by id
pub async fn get_id(pool: &SqlitePool, id: i64) -> Result<User, Error> {
pub async fn get_id(pool: SqlitePool, id: i64) -> Result<User, Error> {
let mut connection = pool.acquire().await?;

let user: Account = sqlx::query_as("select * from users where id = $1")
Expand All @@ -151,15 +151,15 @@ pub mod user {
Ok(From::from(user))
}

pub async fn exists(pool: &SqlitePool, name: &String) -> bool {
pub async fn exists(pool: SqlitePool, name: &String) -> bool {
let user = get(pool, name).await;
match user {
Ok(_) => true,
Err(_) => false,
}
}

pub async fn exists_id(pool: &SqlitePool, id: i64) -> bool {
pub async fn exists_id(pool: SqlitePool, id: i64) -> bool {
let user = get_id(pool, id).await;
match user {
Ok(_) => true,
Expand All @@ -175,7 +175,7 @@ pub mod activity {
use sqlx::SqlitePool;

/// Returns an activity
pub async fn get(pool: &SqlitePool, id: i64) -> Result<Activity, Error> {
pub async fn get(pool: SqlitePool, id: i64) -> Result<Activity, Error> {
let mut connection = pool.acquire().await?;

let activity: Activity = sqlx::query_as("select * from activities where id = $1")
Expand All @@ -188,7 +188,7 @@ pub mod activity {

/// Returns a list of Activities which took place in the time interval from :from to :to
pub async fn get_interval(
pool: &SqlitePool,
pool: SqlitePool,
from: &DateTime<Utc>,
to: &DateTime<Utc>,
) -> Result<Vec<Activity>, Error> {
Expand All @@ -206,7 +206,7 @@ pub mod activity {

/// Inserts an activity into the database and returns the newly inserted activity
pub async fn insert(
pool: &SqlitePool,
pool: SqlitePool,
author_id: i64,
activity: &BareActivity,
) -> Result<Activity, Error> {
Expand All @@ -226,7 +226,7 @@ pub mod activity {

/// Updates an activity and returns the updated activity
pub async fn update(
pool: &SqlitePool,
pool: SqlitePool,
id: i64,
activity: &BareActivity,
) -> Result<Activity, Error> {
Expand All @@ -235,7 +235,7 @@ pub mod activity {
}

/// Deletes an activity and returns the deleted activity
pub async fn delete(pool: &SqlitePool, id: i64) -> Result<Activity, Error> {
pub async fn delete(pool: SqlitePool, id: i64) -> Result<Activity, Error> {
let mut connection = pool.acquire().await?;

let activity: Activity = sqlx::query_as("delete from activities where id = $1 returning *")
Expand Down
16 changes: 8 additions & 8 deletions src/logic/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ pub async fn get_account(auth: AuthContext) -> impl IntoResponse {

/// Creates a new account and returns the just created account object
pub async fn post_account(
State(pool): State<&SqlitePool>,
State(pool): State<SqlitePool>,
Json(payload): Json<BareAccount>,
) -> impl IntoResponse {
// if username already exists, return with error
if database::user::exists(pool, &payload.name).await {
if database::user::exists(pool.clone(), &payload.name).await {
return (StatusCode::CONFLICT).into_response();
}

Expand All @@ -36,8 +36,8 @@ pub async fn post_account(

/// Edit the current logged in account
pub async fn edit_account(
State(pool): State<&SqlitePool>,
mut auth: AuthContext,
State(pool): State<SqlitePool>,
auth: AuthContext,
Json(payload): Json<EditAccount>,
) -> impl IntoResponse {
// todo ask for another password validation
Expand All @@ -55,8 +55,8 @@ pub async fn edit_account(

/// Permanently delete the current logged in account
pub async fn delete_account(
State(pool): State<&SqlitePool>,
mut auth: AuthContext,
State(pool): State<SqlitePool>,
auth: AuthContext,
) -> impl IntoResponse {
// todo ask for a password validation

Expand All @@ -76,8 +76,8 @@ pub async fn delete_account(

/// Change the password of the current logged in account
pub async fn edit_account_password(
State(pool): State<&SqlitePool>,
mut auth: AuthContext,
State(pool): State<SqlitePool>,
auth: AuthContext,
) -> impl IntoResponse {
(StatusCode::NOT_IMPLEMENTED).into_response()
}
25 changes: 12 additions & 13 deletions src/logic/activities.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::activity::{BareActivity, StringBareActivity};
use crate::database;
use crate::database::Error;
use crate::logic::AuthContext;

use axum::extract::{Path, State};
Expand All @@ -12,7 +11,7 @@ use sqlx::SqlitePool;

/// Returns a single `Activity` by id
pub async fn get_activity(
State(pool): State<&SqlitePool>,
State(pool): State<SqlitePool>,
Path(activity_id): Path<i64>,
) -> impl IntoResponse {
let activity = match database::activity::get(pool, activity_id).await {
Expand All @@ -26,7 +25,7 @@ pub async fn get_activity(

/// Returns a list of `Activity` which were started in an time intervall of [:from, :to]
pub async fn get_activities_from_to(
State(pool): State<&SqlitePool>,
State(pool): State<SqlitePool>,
Path((from, to)): Path<(String, String)>,
) -> impl IntoResponse {
// parse the :from parameter as a RFC-3339 DateTime String
Expand Down Expand Up @@ -75,8 +74,8 @@ pub async fn get_activities_from_to(

/// Creates a new `Activity` object
pub async fn post_activity(
State(pool): State<&SqlitePool>,
mut auth: AuthContext,
State(pool): State<SqlitePool>,
auth: AuthContext,
Json(payload): Json<StringBareActivity>,
) -> impl IntoResponse {
let start_time = match DateTime::parse_from_rfc3339(&payload.start_time) {
Expand Down Expand Up @@ -130,13 +129,13 @@ pub async fn post_activity(

/// Edits the information of an `Activity` object
pub async fn edit_activity(
State(pool): State<&SqlitePool>,
mut auth: AuthContext,
Path(activity_id): Path<(i64)>,
State(pool): State<SqlitePool>,
auth: AuthContext,
Path(activity_id): Path<i64>,
Json(payload): Json<BareActivity>, // todo string bare activity
) -> impl IntoResponse {
// get the referenced activity from the database
let activity = match database::activity::get(pool, activity_id).await {
let activity = match database::activity::get(pool.clone(), activity_id).await {
Ok(activity) => activity,
// Err(Error::ElementNotFound) => return (StatusCode::NOT_FOUND).into_response(),
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR).into_response(),
Expand All @@ -161,12 +160,12 @@ pub async fn edit_activity(

/// Deletes an `Activity` object
pub async fn delete_activity(
State(pool): State<&SqlitePool>,
mut auth: AuthContext,
Path(activity_id): Path<(i64)>,
State(pool): State<SqlitePool>,
auth: AuthContext,
Path(activity_id): Path<i64>,
) -> impl IntoResponse {
// get the referenced activity from the database
let activity = match database::activity::get(pool, activity_id).await {
let activity = match database::activity::get(pool.clone(), activity_id).await {
Ok(activity) => activity,
// Err(Error::ElementNotFound) => return (StatusCode::NOT_FOUND).into_response(),
// todo catch additional errors
Expand Down
2 changes: 1 addition & 1 deletion src/logic/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use sqlx::SqlitePool;
type AuthContext = axum_login::extractors::AuthContext<i64, Account, SqliteStore<Account>>;

pub async fn login(
State(pool): State<&SqlitePool>,
State(pool): State<SqlitePool>,
mut auth: AuthContext,
Json(payload): Json<BareAccount>,
) -> impl IntoResponse {
Expand Down
5 changes: 2 additions & 3 deletions src/logic/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ use axum::response::IntoResponse;
use axum::Json;
use http::StatusCode;
use sqlx::SqlitePool;
use crate::database::Error;

pub async fn get_user(
State(pool): State<&SqlitePool>,
State(pool): State<SqlitePool>,
Path(username): Path<String>,
) -> impl IntoResponse {
let user = match database::user::get(pool, &username).await {
Expand All @@ -21,7 +20,7 @@ pub async fn get_user(
}

pub async fn get_user_id(
State(pool): State<&SqlitePool>,
State(pool): State<SqlitePool>,
Path(user_id): Path<i64>,
) -> impl IntoResponse {
let user = match database::user::get_id(pool, user_id).await {
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async fn main() {
.expect("Error while initializing the database.");

let app = Router::new()
.merge(routes::backend_router(&pool).await)
.merge(routes::backend_router(pool).await)
.merge(routes::frontend_router().await);

axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
Expand Down
4 changes: 1 addition & 3 deletions src/routes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::account::Account;
use crate::database::DB_URI;
use crate::logic::account::{
delete_account, edit_account, edit_account_password, get_account, post_account,
};
Expand All @@ -17,7 +16,6 @@ use axum_login::axum_sessions::async_session::MemoryStore;
use axum_login::axum_sessions::{SameSite, SessionLayer};
use axum_login::{AuthLayer, RequireAuthorizationLayer, SqliteStore};
use rand::Rng;
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::SqlitePool;
use tower_http::services::ServeDir;

Expand All @@ -30,7 +28,7 @@ pub async fn frontend_router() -> Router {
Router::new().nest_service("/", ServeDir::new("public"))
}

pub async fn backend_router(pool: &SqlitePool) -> Router {
pub async fn backend_router(pool: SqlitePool) -> Router {
let secret = rand::thread_rng().gen::<[u8; 64]>(); // todo use secret from environment variable

let session_store = MemoryStore::new();
Expand Down

0 comments on commit 9b475a6

Please sign in to comment.