Replace Rusqlite by Sqlx and Actix by Axum (A lot of changes)
This commit is contained in:
parent
57d7e7a3ce
commit
980c5884a4
28 changed files with 2860 additions and 2262 deletions
|
|
@ -1,2 +1,2 @@
|
||||||
[target.aarch64-unknown-linux-gnu]
|
[target.aarch64-unknown-linux-gnu]
|
||||||
linker = "aarch64-linux-gnu-gcc.exe"
|
linker = "aarch64-linux-gnu-gcc.exe"
|
||||||
|
|
|
||||||
2813
Cargo.lock
generated
2813
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,10 +1,8 @@
|
||||||
[workspace]
|
[workspace]
|
||||||
|
|
||||||
members = [
|
resolver = "2"
|
||||||
"backend",
|
|
||||||
"frontend",
|
members = ["backend", "frontend", "common"]
|
||||||
"common",
|
|
||||||
]
|
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
strip = true
|
strip = true
|
||||||
|
|
|
||||||
|
|
@ -46,7 +46,6 @@ To launch node run 'npm run start' in 'frontend/www' directory
|
||||||
## Useful URLs
|
## Useful URLs
|
||||||
|
|
||||||
* Rust patterns : https://github.com/rust-unofficial/patterns/tree/master/patterns
|
* Rust patterns : https://github.com/rust-unofficial/patterns/tree/master/patterns
|
||||||
* Rusqlite (SQLite) : https://docs.rs/rusqlite/0.20.0/rusqlite/
|
|
||||||
* Node install: https://nodejs.org/en/download/
|
* Node install: https://nodejs.org/en/download/
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
21
TODO.md
21
TODO.md
|
|
@ -1,20 +1,29 @@
|
||||||
|
* Clean the old code + commit
|
||||||
|
* How to log error to journalctl or elsewhere + debug log?
|
||||||
* Try using WASM for all the client logic (test on editing/creating a recipe)
|
* Try using WASM for all the client logic (test on editing/creating a recipe)
|
||||||
* Understand the example here:
|
* Understand the example here:
|
||||||
* https://github.com/rustwasm/wasm-bindgen/tree/main/examples/todomvc -> https://rustwasm.github.io/wasm-bindgen/exbuild/todomvc/#/
|
* https://github.com/rustwasm/wasm-bindgen/tree/main/examples/todomvc -> https://rustwasm.github.io/wasm-bindgen/exbuild/todomvc/#/
|
||||||
* Describe the use cases.
|
* Add a level of severity for the message template, use error severity in "impl axum::response::IntoResponse for db::DBError"
|
||||||
* Define the UI (mockups).
|
* Review the recipe model (SQL)
|
||||||
* Two CSS: one for desktop and one for mobile
|
* Describe the use cases in details.
|
||||||
* Use CSS flex/grid to define a good design/layout
|
* Define the UI (mockups).
|
||||||
* Define the logic behind each page and action.
|
* Two CSS: one for desktop and one for mobile
|
||||||
|
* Use CSS flex/grid to define a good design/layout
|
||||||
|
* Define the logic behind each page and action.
|
||||||
|
* Implement:
|
||||||
|
.service(services::edit_recipe)
|
||||||
|
.service(services::new_recipe)
|
||||||
|
.service(services::webapi::set_recipe_title)
|
||||||
|
.service(services::webapi::set_recipe_description)
|
||||||
* Add support to translations into db model.
|
* Add support to translations into db model.
|
||||||
|
|
||||||
|
[ok] Reactivate sign up/in/out
|
||||||
[ok] Change all id to i64
|
[ok] Change all id to i64
|
||||||
[ok] Check cookie lifetime -> Session by default
|
[ok] Check cookie lifetime -> Session by default
|
||||||
[ok] Asynchonous email sending and database requests
|
[ok] Asynchonous email sending and database requests
|
||||||
[ok] Try to return Result for async routes (and watch what is printed in log)
|
[ok] Try to return Result for async routes (and watch what is printed in log)
|
||||||
[ok] Then try to make async database calls
|
[ok] Then try to make async database calls
|
||||||
[ok] Set email sending as async and show a waiter when sending email. Handle (and test) a timeout (~10s). -> (timeout put to 60s)
|
[ok] Set email sending as async and show a waiter when sending email. Handle (and test) a timeout (~10s). -> (timeout put to 60s)
|
||||||
[ok] How to log error to journalctl?
|
|
||||||
[ok] Sign out
|
[ok] Sign out
|
||||||
[ok] Read all the askama doc and see if the current approach is good
|
[ok] Read all the askama doc and see if the current approach is good
|
||||||
[ok] Handle 404
|
[ok] Handle 404
|
||||||
|
|
|
||||||
|
|
@ -5,36 +5,48 @@ authors = ["Grégory Burri <greg.burri@gmail.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
common = {path = "../common"}
|
common = { path = "../common" }
|
||||||
|
|
||||||
actix-web = "4"
|
axum = { version = "0.7", features = ["macros"] }
|
||||||
actix-files = "0.6"
|
axum-extra = { version = "0.9", features = ["cookie"] }
|
||||||
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
tower = { version = "0.5", features = ["util"] }
|
||||||
|
tower-http = { version = "0.6", features = ["fs", "trace"] }
|
||||||
|
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
|
||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
|
|
||||||
ron = "0.8" # Rust object notation, to load configuration files.
|
# Rust object notation, to load configuration files.
|
||||||
serde = {version = "1.0", features = ["derive"]}
|
ron = "0.8"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
|
||||||
itertools = "0.10"
|
itertools = "0.13"
|
||||||
clap = {version = "4", features = ["derive"]}
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
|
||||||
log = "0.4"
|
sqlx = { version = "0.8", features = ["sqlite", "runtime-tokio", "chrono"] }
|
||||||
env_logger = "0.10"
|
|
||||||
|
|
||||||
r2d2_sqlite = "0.21" # Connection pool with rusqlite (SQLite access).
|
askama = { version = "0.12", features = [
|
||||||
r2d2 = "0.8"
|
"with-axum",
|
||||||
rusqlite = {version = "0.28", features = ["bundled", "chrono"]}
|
"mime",
|
||||||
|
"mime_guess",
|
||||||
futures = "0.3" # Needed by askam with the feature 'with-actix-web'.
|
"markdown",
|
||||||
|
] }
|
||||||
askama = {version = "0.12", features = ["with-actix-web", "mime", "mime_guess", "markdown"]}
|
askama_axum = "0.4"
|
||||||
askama_actix = "0.14"
|
|
||||||
|
|
||||||
argon2 = {version = "0.5", features = ["default", "std"]}
|
|
||||||
rand_core = {version = "0.6", features = ["std"]}
|
|
||||||
|
|
||||||
|
argon2 = { version = "0.5", features = ["default", "std"] }
|
||||||
|
rand_core = { version = "0.6", features = ["std"] }
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
|
|
||||||
lettre = {version = "0.10", default-features = false, features = ["smtp-transport", "pool", "hostname", "builder", "rustls-tls"]}
|
lettre = { version = "0.11", default-features = false, features = [
|
||||||
|
"smtp-transport",
|
||||||
|
"pool",
|
||||||
|
"hostname",
|
||||||
|
"builder",
|
||||||
|
"tokio1",
|
||||||
|
"tokio1-rustls-tls",
|
||||||
|
] }
|
||||||
|
|
||||||
derive_more = "0.99"
|
derive_more = { version = "1", features = ["full"] }
|
||||||
|
thiserror = "1"
|
||||||
|
|
|
||||||
|
|
@ -1,22 +1,38 @@
|
||||||
use std::{fmt, fs::File};
|
use std::{fmt, fs::File};
|
||||||
|
|
||||||
use ron::de::from_reader;
|
use ron::{
|
||||||
use serde::Deserialize;
|
de::from_reader,
|
||||||
|
ser::{to_writer_pretty, PrettyConfig},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::consts;
|
use crate::consts;
|
||||||
|
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Serialize, Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
|
pub smtp_relay_address: String,
|
||||||
pub smtp_login: String,
|
pub smtp_login: String,
|
||||||
pub smtp_password: String,
|
pub smtp_password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn default() -> Self {
|
||||||
|
Config {
|
||||||
|
port: 8082,
|
||||||
|
smtp_relay_address: "mail.something.com".to_string(),
|
||||||
|
smtp_login: "login".to_string(),
|
||||||
|
smtp_password: "password".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Avoid to print passwords.
|
// Avoid to print passwords.
|
||||||
impl fmt::Debug for Config {
|
impl fmt::Debug for Config {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.debug_struct("Config")
|
f.debug_struct("Config")
|
||||||
.field("port", &self.port)
|
.field("port", &self.port)
|
||||||
|
.field("smtp_relay_address", &self.smtp_relay_address)
|
||||||
.field("smtp_login", &self.smtp_login)
|
.field("smtp_login", &self.smtp_login)
|
||||||
.field("smtp_password", &"*****")
|
.field("smtp_password", &"*****")
|
||||||
.finish()
|
.finish()
|
||||||
|
|
@ -24,10 +40,25 @@ impl fmt::Debug for Config {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load() -> Config {
|
pub fn load() -> Config {
|
||||||
let f = File::open(consts::FILE_CONF)
|
match File::open(consts::FILE_CONF) {
|
||||||
.unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
|
Ok(file) => from_reader(file).expect(&format!(
|
||||||
match from_reader(f) {
|
"Failed to open configuration file {}",
|
||||||
Ok(c) => c,
|
consts::FILE_CONF
|
||||||
Err(e) => panic!("Failed to load config: {}", e),
|
)),
|
||||||
|
Err(_) => {
|
||||||
|
let file = File::create(consts::FILE_CONF).expect(&format!(
|
||||||
|
"Failed to create default configuration file {}",
|
||||||
|
consts::FILE_CONF
|
||||||
|
));
|
||||||
|
|
||||||
|
let default_config = Config::default();
|
||||||
|
|
||||||
|
to_writer_pretty(file, &default_config, PrettyConfig::new()).expect(&format!(
|
||||||
|
"Failed to write default configuration file {}",
|
||||||
|
consts::FILE_CONF
|
||||||
|
));
|
||||||
|
|
||||||
|
default_config
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,13 @@ pub const DB_DIRECTORY: &str = "data";
|
||||||
pub const DB_FILENAME: &str = "recipes.sqlite";
|
pub const DB_FILENAME: &str = "recipes.sqlite";
|
||||||
pub const SQL_FILENAME: &str = "sql/version_{VERSION}.sql";
|
pub const SQL_FILENAME: &str = "sql/version_{VERSION}.sql";
|
||||||
pub const VALIDATION_TOKEN_DURATION: i64 = 1 * 60 * 60; // 1 hour. [s].
|
pub const VALIDATION_TOKEN_DURATION: i64 = 1 * 60 * 60; // 1 hour. [s].
|
||||||
pub const REVERSE_PROXY_IP_HTTP_FIELD: &str = "x-real-ip";
|
|
||||||
pub const COOKIE_AUTH_TOKEN_NAME: &str = "auth_token";
|
pub const COOKIE_AUTH_TOKEN_NAME: &str = "auth_token";
|
||||||
pub const AUTHENTICATION_TOKEN_SIZE: usize = 32; // Number of alphanumeric characters for cookie authentication token.
|
|
||||||
|
// Number of alphanumeric characters for cookie authentication token.
|
||||||
|
pub const AUTHENTICATION_TOKEN_SIZE: usize = 32;
|
||||||
|
|
||||||
pub const SEND_EMAIL_TIMEOUT: Duration = Duration::from_secs(60);
|
pub const SEND_EMAIL_TIMEOUT: Duration = Duration::from_secs(60);
|
||||||
|
|
||||||
|
// HTTP headers, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers.
|
||||||
|
// Common headers can be found in 'axum::http::header' (which is a re-export of the create 'http').
|
||||||
|
pub const REVERSE_PROXY_IP_HTTP_FIELD: &str = "x-real-ip"; // Set by the reverse proxy (Nginx).
|
||||||
|
|
|
||||||
|
|
@ -1,195 +0,0 @@
|
||||||
//! Functions to be called from actix code. They are asynchonrous and won't block worker thread caller.
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
use actix_web::{error::BlockingError, web};
|
|
||||||
use chrono::{prelude::*, Duration};
|
|
||||||
|
|
||||||
use super::db::*;
|
|
||||||
use crate::model;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum DBAsyncError {
|
|
||||||
DBError(DBError),
|
|
||||||
ActixError(BlockingError),
|
|
||||||
Other(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for DBAsyncError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> {
|
|
||||||
write!(f, "{:?}", self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for DBAsyncError {}
|
|
||||||
|
|
||||||
impl From<DBError> for DBAsyncError {
|
|
||||||
fn from(error: DBError) -> Self {
|
|
||||||
DBAsyncError::DBError(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<BlockingError> for DBAsyncError {
|
|
||||||
fn from(error: BlockingError) -> Self {
|
|
||||||
DBAsyncError::ActixError(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DBAsyncError {
|
|
||||||
fn from_dyn_error(error: Box<dyn std::error::Error>) -> Self {
|
|
||||||
DBAsyncError::Other(error.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn combine_errors<T>(
|
|
||||||
error: std::result::Result<std::result::Result<T, DBAsyncError>, BlockingError>,
|
|
||||||
) -> Result<T> {
|
|
||||||
error?
|
|
||||||
}
|
|
||||||
|
|
||||||
type Result<T> = std::result::Result<T, DBAsyncError>;
|
|
||||||
|
|
||||||
impl Connection {
|
|
||||||
pub async fn get_all_recipe_titles_async(&self) -> Result<Vec<(i64, String)>> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
web::block(move || self_copy.get_all_recipe_titles().unwrap_or_default())
|
|
||||||
.await
|
|
||||||
.map_err(DBAsyncError::from)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_recipe_async(&self, id: i64) -> Result<model::Recipe> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || self_copy.get_recipe(id).map_err(DBAsyncError::from)).await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn load_user_async(&self, user_id: i64) -> Result<model::User> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || self_copy.load_user(user_id).map_err(DBAsyncError::from)).await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn sign_up_async(&self, email: &str, password: &str) -> Result<SignUpResult> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
let email_copy = email.to_string();
|
|
||||||
let password_copy = password.to_string();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || {
|
|
||||||
self_copy
|
|
||||||
.sign_up(&email_copy, &password_copy)
|
|
||||||
.map_err(DBAsyncError::from)
|
|
||||||
})
|
|
||||||
.await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn validation_async(
|
|
||||||
&self,
|
|
||||||
token: &str,
|
|
||||||
validation_time: Duration,
|
|
||||||
ip: &str,
|
|
||||||
user_agent: &str,
|
|
||||||
) -> Result<ValidationResult> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
let token_copy = token.to_string();
|
|
||||||
let ip_copy = ip.to_string();
|
|
||||||
let user_agent_copy = user_agent.to_string();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || {
|
|
||||||
self_copy
|
|
||||||
.validation(&token_copy, validation_time, &ip_copy, &user_agent_copy)
|
|
||||||
.map_err(DBAsyncError::from)
|
|
||||||
})
|
|
||||||
.await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn sign_in_async(
|
|
||||||
&self,
|
|
||||||
email: &str,
|
|
||||||
password: &str,
|
|
||||||
ip: &str,
|
|
||||||
user_agent: &str,
|
|
||||||
) -> Result<SignInResult> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
let email_copy = email.to_string();
|
|
||||||
let password_copy = password.to_string();
|
|
||||||
let ip_copy = ip.to_string();
|
|
||||||
let user_agent_copy = user_agent.to_string();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || {
|
|
||||||
self_copy
|
|
||||||
.sign_in(&email_copy, &password_copy, &ip_copy, &user_agent_copy)
|
|
||||||
.map_err(DBAsyncError::from)
|
|
||||||
})
|
|
||||||
.await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn authentication_async(
|
|
||||||
&self,
|
|
||||||
token: &str,
|
|
||||||
ip: &str,
|
|
||||||
user_agent: &str,
|
|
||||||
) -> Result<AuthenticationResult> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
let token_copy = token.to_string();
|
|
||||||
let ip_copy = ip.to_string();
|
|
||||||
let user_agent_copy = user_agent.to_string();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || {
|
|
||||||
self_copy
|
|
||||||
.authentication(&token_copy, &ip_copy, &user_agent_copy)
|
|
||||||
.map_err(DBAsyncError::from)
|
|
||||||
})
|
|
||||||
.await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn sign_out_async(&self, token: &str) -> Result<()> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
let token_copy = token.to_string();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || self_copy.sign_out(&token_copy).map_err(DBAsyncError::from)).await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn create_recipe_async(&self, user_id: i64) -> Result<i64> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || self_copy.create_recipe(user_id).map_err(DBAsyncError::from)).await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn set_recipe_title_async(&self, recipe_id: i64, title: &str) -> Result<()> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
let title_copy = title.to_string();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || {
|
|
||||||
self_copy
|
|
||||||
.set_recipe_title(recipe_id, &title_copy)
|
|
||||||
.map_err(DBAsyncError::from)
|
|
||||||
})
|
|
||||||
.await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn set_recipe_description_async(
|
|
||||||
&self,
|
|
||||||
recipe_id: i64,
|
|
||||||
description: &str,
|
|
||||||
) -> Result<()> {
|
|
||||||
let self_copy = self.clone();
|
|
||||||
let description_copy = description.to_string();
|
|
||||||
combine_errors(
|
|
||||||
web::block(move || {
|
|
||||||
self_copy
|
|
||||||
.set_recipe_description(recipe_id, &description_copy)
|
|
||||||
.map_err(DBAsyncError::from)
|
|
||||||
})
|
|
||||||
.await,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,2 +1,2 @@
|
||||||
pub mod asynchronous;
|
|
||||||
pub mod db;
|
pub mod db;
|
||||||
|
mod utils;
|
||||||
|
|
|
||||||
33
backend/src/data/utils.rs
Normal file
33
backend/src/data/utils.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
use sqlx::{sqlite::SqliteRow, FromRow, Row};
|
||||||
|
|
||||||
|
use crate::model;
|
||||||
|
|
||||||
|
impl FromRow<'_, SqliteRow> for model::Recipe {
|
||||||
|
fn from_row(row: &SqliteRow) -> sqlx::Result<Self> {
|
||||||
|
Ok(model::Recipe::new(
|
||||||
|
row.try_get("id")?,
|
||||||
|
row.try_get("user_id")?,
|
||||||
|
row.try_get("title")?,
|
||||||
|
row.try_get("description")?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRow<'_, SqliteRow> for model::UserLoginInfo {
|
||||||
|
fn from_row(row: &SqliteRow) -> sqlx::Result<Self> {
|
||||||
|
Ok(model::UserLoginInfo {
|
||||||
|
last_login_datetime: row.try_get("last_login_datetime")?,
|
||||||
|
ip: row.try_get("ip")?,
|
||||||
|
user_agent: row.try_get("user_agent")?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRow<'_, SqliteRow> for model::User {
|
||||||
|
fn from_row(row: &SqliteRow) -> sqlx::Result<Self> {
|
||||||
|
Ok(model::User {
|
||||||
|
id: row.try_get("id")?,
|
||||||
|
email: row.try_get("email")?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
|
use lettre::{
|
||||||
use std::time::Duration;
|
transport::smtp::{authentication::Credentials, AsyncSmtpTransport},
|
||||||
|
AsyncTransport, Message, Tokio1Executor,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::consts;
|
use crate::consts;
|
||||||
|
|
||||||
|
|
@ -29,10 +31,11 @@ impl From<lettre::error::Error> for Error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send_validation(
|
pub async fn send_validation(
|
||||||
site_url: &str,
|
site_url: &str,
|
||||||
email: &str,
|
email: &str,
|
||||||
token: &str,
|
token: &str,
|
||||||
|
smtp_relay_address: &str,
|
||||||
smtp_login: &str,
|
smtp_login: &str,
|
||||||
smtp_password: &str,
|
smtp_password: &str,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
|
|
@ -40,20 +43,20 @@ pub fn send_validation(
|
||||||
.message_id(None)
|
.message_id(None)
|
||||||
.from("recipes@gburri.org".parse()?)
|
.from("recipes@gburri.org".parse()?)
|
||||||
.to(email.parse()?)
|
.to(email.parse()?)
|
||||||
.subject("Recipes.gburri.org account validation")
|
.subject("recipes.gburri.org account validation")
|
||||||
.body(format!(
|
.body(format!(
|
||||||
"Follow this link to confirm your inscription: {}/validation?token={}",
|
"Follow this link to confirm your inscription: {}/validation?validation_token={}",
|
||||||
site_url, token
|
site_url, token
|
||||||
))?;
|
))?;
|
||||||
|
|
||||||
let credentials = Credentials::new(smtp_login.to_string(), smtp_password.to_string());
|
let credentials = Credentials::new(smtp_login.to_string(), smtp_password.to_string());
|
||||||
|
|
||||||
let mailer = SmtpTransport::relay("mail.gandi.net")?
|
let mailer = AsyncSmtpTransport::<Tokio1Executor>::relay(smtp_relay_address)?
|
||||||
.credentials(credentials)
|
.credentials(credentials)
|
||||||
.timeout(Some(consts::SEND_EMAIL_TIMEOUT))
|
.timeout(Some(consts::SEND_EMAIL_TIMEOUT))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
if let Err(error) = mailer.send(&email) {
|
if let Err(error) = mailer.send(email).await {
|
||||||
eprintln!("Error when sending E-mail:\n{:?}", &error);
|
eprintln!("Error when sending E-mail:\n{:?}", &error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,17 @@
|
||||||
use std::path::Path;
|
use std::{net::SocketAddr, path::Path};
|
||||||
|
|
||||||
use actix_files as fs;
|
use axum::{
|
||||||
use actix_web::{middleware, web, App, HttpServer};
|
extract::{ConnectInfo, FromRef, Request, State},
|
||||||
|
middleware::{self, Next},
|
||||||
|
response::{Response, Result},
|
||||||
|
routing::get,
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
use axum_extra::extract::cookie::CookieJar;
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
|
use config::Config;
|
||||||
|
use tower_http::services::ServeDir;
|
||||||
|
|
||||||
use data::db;
|
use data::db;
|
||||||
|
|
||||||
|
|
@ -16,49 +24,121 @@ mod model;
|
||||||
mod services;
|
mod services;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
#[actix_web::main]
|
#[derive(Clone)]
|
||||||
async fn main() -> std::io::Result<()> {
|
struct AppState {
|
||||||
if process_args() {
|
config: Config,
|
||||||
return Ok(());
|
db_connection: db::Connection,
|
||||||
}
|
}
|
||||||
|
|
||||||
std::env::set_var("RUST_LOG", "info,actix_web=info");
|
impl FromRef<AppState> for Config {
|
||||||
env_logger::init();
|
fn from_ref(app_state: &AppState) -> Config {
|
||||||
|
app_state.config.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRef<AppState> for db::Connection {
|
||||||
|
fn from_ref(app_state: &AppState) -> db::Connection {
|
||||||
|
app_state.db_connection.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Should main returns 'Result'?
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
if process_args().await {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
println!("Starting Recipes as web server...");
|
println!("Starting Recipes as web server...");
|
||||||
|
|
||||||
let config = web::Data::new(config::load());
|
let config = config::load();
|
||||||
let port = config.as_ref().port;
|
let port = config.port;
|
||||||
|
|
||||||
println!("Configuration: {:?}", config);
|
println!("Configuration: {:?}", config);
|
||||||
|
|
||||||
let db_connection = web::Data::new(db::Connection::new().unwrap());
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
let server = HttpServer::new(move || {
|
let db_connection = db::Connection::new().await.unwrap();
|
||||||
App::new()
|
|
||||||
.wrap(middleware::Logger::default())
|
|
||||||
.wrap(middleware::Compress::default())
|
|
||||||
.app_data(db_connection.clone())
|
|
||||||
.app_data(config.clone())
|
|
||||||
.service(services::home_page)
|
|
||||||
.service(services::sign_up_get)
|
|
||||||
.service(services::sign_up_post)
|
|
||||||
.service(services::sign_up_check_email)
|
|
||||||
.service(services::sign_up_validation)
|
|
||||||
.service(services::sign_in_get)
|
|
||||||
.service(services::sign_in_post)
|
|
||||||
.service(services::sign_out)
|
|
||||||
.service(services::view_recipe)
|
|
||||||
.service(services::edit_recipe)
|
|
||||||
.service(services::new_recipe)
|
|
||||||
.service(services::webapi::set_recipe_title)
|
|
||||||
.service(services::webapi::set_recipe_description)
|
|
||||||
.service(fs::Files::new("/static", "static"))
|
|
||||||
.default_service(web::to(services::not_found))
|
|
||||||
});
|
|
||||||
//.workers(1);
|
|
||||||
|
|
||||||
server.bind(&format!("0.0.0.0:{}", port))?.run().await
|
let state = AppState {
|
||||||
|
config,
|
||||||
|
db_connection,
|
||||||
|
};
|
||||||
|
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/", get(services::home_page))
|
||||||
|
.route(
|
||||||
|
"/signup",
|
||||||
|
get(services::sign_up_get).post(services::sign_up_post),
|
||||||
|
)
|
||||||
|
.route("/validation", get(services::sign_up_validation))
|
||||||
|
.route("/recipe/view/:id", get(services::view_recipe))
|
||||||
|
.route(
|
||||||
|
"/signin",
|
||||||
|
get(services::sign_in_get).post(services::sign_in_post),
|
||||||
|
)
|
||||||
|
.route("/signout", get(services::sign_out))
|
||||||
|
.route_layer(middleware::from_fn_with_state(
|
||||||
|
state.clone(),
|
||||||
|
user_authentication,
|
||||||
|
))
|
||||||
|
.nest_service("/static", ServeDir::new("static"))
|
||||||
|
.fallback(services::not_found)
|
||||||
|
.with_state(state)
|
||||||
|
.into_make_service_with_connect_info::<SocketAddr>();
|
||||||
|
|
||||||
|
let addr = SocketAddr::from(([0, 0, 0, 0], port));
|
||||||
|
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||||
|
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn user_authentication(
|
||||||
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
|
State(connection): State<db::Connection>,
|
||||||
|
mut req: Request,
|
||||||
|
next: Next,
|
||||||
|
) -> Result<Response> {
|
||||||
|
let jar = CookieJar::from_headers(req.headers());
|
||||||
|
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(req.headers(), addr);
|
||||||
|
let user = get_current_user(connection, &jar, &client_ip, &client_user_agent).await;
|
||||||
|
req.extensions_mut().insert(user);
|
||||||
|
Ok(next.run(req).await)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_current_user(
|
||||||
|
connection: db::Connection,
|
||||||
|
jar: &CookieJar,
|
||||||
|
client_ip: &str,
|
||||||
|
client_user_agent: &str,
|
||||||
|
) -> Option<model::User> {
|
||||||
|
match jar.get(consts::COOKIE_AUTH_TOKEN_NAME) {
|
||||||
|
Some(token_cookie) => match connection
|
||||||
|
.authentication(token_cookie.value(), &client_ip, &client_user_agent)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(db::AuthenticationResult::NotValidToken) => {
|
||||||
|
// TODO: remove cookie?
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Ok(db::AuthenticationResult::Ok(user_id)) => {
|
||||||
|
match connection.load_user(user_id).await {
|
||||||
|
Ok(user) => user,
|
||||||
|
Err(error) => {
|
||||||
|
// TODO: Return 'Result'?
|
||||||
|
println!("Error during authentication: {}", error);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
// TODO: Return 'Result'?
|
||||||
|
println!("Error during authentication: {}", error);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
|
|
@ -68,7 +148,7 @@ struct Args {
|
||||||
dbtest: bool,
|
dbtest: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_args() -> bool {
|
async fn process_args() -> bool {
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
if args.dbtest {
|
if args.dbtest {
|
||||||
|
|
@ -93,16 +173,18 @@ fn process_args() -> bool {
|
||||||
.expect(&format!("Unable to remove db file: {:?}", &db_path));
|
.expect(&format!("Unable to remove db file: {:?}", &db_path));
|
||||||
}
|
}
|
||||||
|
|
||||||
match db::Connection::new() {
|
match db::Connection::new().await {
|
||||||
Ok(con) => {
|
Ok(con) => {
|
||||||
if let Err(error) = con.execute_file("sql/data_test.sql") {
|
if let Err(error) = con.execute_file("sql/data_test.sql").await {
|
||||||
eprintln!("{}", error);
|
eprintln!("{}", error);
|
||||||
}
|
}
|
||||||
// Set the creation datetime to 'now'.
|
// Set the creation datetime to 'now'.
|
||||||
con.execute_sql(
|
con.execute_sql(
|
||||||
"UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'",
|
sqlx::query(
|
||||||
[Utc::now()],
|
"UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'")
|
||||||
|
.bind(Utc::now())
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
|
|
|
||||||
|
|
@ -1,145 +1,29 @@
|
||||||
use std::collections::HashMap;
|
use std::{collections::HashMap, net::SocketAddr};
|
||||||
|
|
||||||
use actix_web::{
|
use askama::Template;
|
||||||
cookie::Cookie,
|
use axum::{
|
||||||
get,
|
body::Body,
|
||||||
http::{header, header::ContentType, StatusCode},
|
debug_handler,
|
||||||
post, web, HttpRequest, HttpResponse, Responder,
|
extract::{ConnectInfo, Extension, Host, Path, Query, Request, State},
|
||||||
|
http::{HeaderMap, StatusCode},
|
||||||
|
response::{IntoResponse, Redirect, Response, Result},
|
||||||
|
Form,
|
||||||
};
|
};
|
||||||
use askama_actix::{Template, TemplateToResponse};
|
use axum_extra::extract::cookie::{Cookie, CookieJar};
|
||||||
use chrono::Duration;
|
use chrono::Duration;
|
||||||
use log::{debug, error, info, log_enabled, Level};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::{
|
use crate::{config::Config, consts, data::db, email, model, utils, AppState};
|
||||||
config::Config,
|
|
||||||
consts,
|
|
||||||
data::{asynchronous, db},
|
|
||||||
email, model, utils,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub mod webapi;
|
pub mod webapi;
|
||||||
|
|
||||||
///// UTILS /////
|
impl axum::response::IntoResponse for db::DBError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
|
let body = MessageTemplate {
|
||||||
let ip = match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
|
user: None,
|
||||||
Some(v) => v.to_str().unwrap_or_default().to_string(),
|
|
||||||
None => req
|
|
||||||
.peer_addr()
|
|
||||||
.map(|addr| addr.ip().to_string())
|
|
||||||
.unwrap_or_default(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let user_agent = req
|
|
||||||
.headers()
|
|
||||||
.get(header::USER_AGENT)
|
|
||||||
.map(|v| v.to_str().unwrap_or_default())
|
|
||||||
.unwrap_or_default()
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
(ip, user_agent)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_current_user(
|
|
||||||
req: &HttpRequest,
|
|
||||||
connection: web::Data<db::Connection>,
|
|
||||||
) -> Option<model::User> {
|
|
||||||
let (client_ip, client_user_agent) = get_ip_and_user_agent(req);
|
|
||||||
|
|
||||||
match req.cookie(consts::COOKIE_AUTH_TOKEN_NAME) {
|
|
||||||
Some(token_cookie) => match connection
|
|
||||||
.authentication_async(token_cookie.value(), &client_ip, &client_user_agent)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(db::AuthenticationResult::NotValidToken) =>
|
|
||||||
// TODO: remove cookie?
|
|
||||||
{
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Ok(db::AuthenticationResult::Ok(user_id)) => {
|
|
||||||
match connection.load_user_async(user_id).await {
|
|
||||||
Ok(user) => Some(user),
|
|
||||||
Err(error) => {
|
|
||||||
error!("Error during authentication: {}", error);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
error!("Error during authentication: {}", error);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
},
|
|
||||||
None => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Result<T> = std::result::Result<T, ServiceError>;
|
|
||||||
|
|
||||||
///// ERROR /////
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ServiceError {
|
|
||||||
status_code: StatusCode,
|
|
||||||
message: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<asynchronous::DBAsyncError> for ServiceError {
|
|
||||||
fn from(error: asynchronous::DBAsyncError) -> Self {
|
|
||||||
ServiceError {
|
|
||||||
status_code: StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
message: Some(format!("{:?}", error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<email::Error> for ServiceError {
|
|
||||||
fn from(error: email::Error) -> Self {
|
|
||||||
ServiceError {
|
|
||||||
status_code: StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
message: Some(format!("{:?}", error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<actix_web::error::BlockingError> for ServiceError {
|
|
||||||
fn from(error: actix_web::error::BlockingError) -> Self {
|
|
||||||
ServiceError {
|
|
||||||
status_code: StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
message: Some(format!("{:?}", error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ron::error::SpannedError> for ServiceError {
|
|
||||||
fn from(error: ron::error::SpannedError) -> Self {
|
|
||||||
ServiceError {
|
|
||||||
status_code: StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
message: Some(format!("{:?}", error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for ServiceError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
|
||||||
if let Some(ref m) = self.message {
|
|
||||||
write!(f, "**{}**\n\n", m)?;
|
|
||||||
}
|
|
||||||
write!(f, "Code: {}", self.status_code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl actix_web::error::ResponseError for ServiceError {
|
|
||||||
fn error_response(&self) -> HttpResponse {
|
|
||||||
MessageBaseTemplate {
|
|
||||||
message: &self.to_string(),
|
message: &self.to_string(),
|
||||||
}
|
};
|
||||||
.to_response()
|
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
|
||||||
}
|
|
||||||
|
|
||||||
fn status_code(&self) -> StatusCode {
|
|
||||||
self.status_code
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -153,20 +37,18 @@ struct HomeTemplate {
|
||||||
current_recipe_id: Option<i64>,
|
current_recipe_id: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/")]
|
#[debug_handler]
|
||||||
pub async fn home_page(
|
pub async fn home_page(
|
||||||
req: HttpRequest,
|
State(connection): State<db::Connection>,
|
||||||
connection: web::Data<db::Connection>,
|
Extension(user): Extension<Option<model::User>>,
|
||||||
) -> Result<HttpResponse> {
|
) -> Result<impl IntoResponse> {
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let recipes = connection.get_all_recipe_titles().await?;
|
||||||
let recipes = connection.get_all_recipe_titles_async().await?;
|
|
||||||
|
|
||||||
Ok(HomeTemplate {
|
Ok(HomeTemplate {
|
||||||
user,
|
user,
|
||||||
current_recipe_id: None,
|
current_recipe_id: None,
|
||||||
recipes,
|
recipes,
|
||||||
}
|
})
|
||||||
.to_response())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
///// VIEW RECIPE /////
|
///// VIEW RECIPE /////
|
||||||
|
|
@ -177,115 +59,117 @@ struct ViewRecipeTemplate {
|
||||||
user: Option<model::User>,
|
user: Option<model::User>,
|
||||||
recipes: Vec<(i64, String)>,
|
recipes: Vec<(i64, String)>,
|
||||||
current_recipe_id: Option<i64>,
|
current_recipe_id: Option<i64>,
|
||||||
|
|
||||||
current_recipe: model::Recipe,
|
current_recipe: model::Recipe,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/recipe/view/{id}")]
|
#[debug_handler]
|
||||||
pub async fn view_recipe(
|
pub async fn view_recipe(
|
||||||
req: HttpRequest,
|
State(connection): State<db::Connection>,
|
||||||
path: web::Path<(i64,)>,
|
Extension(user): Extension<Option<model::User>>,
|
||||||
connection: web::Data<db::Connection>,
|
Path(recipe_id): Path<i64>,
|
||||||
) -> Result<HttpResponse> {
|
) -> Result<Response> {
|
||||||
let (id,) = path.into_inner();
|
let recipes = connection.get_all_recipe_titles().await?;
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
match connection.get_recipe(recipe_id).await? {
|
||||||
let recipes = connection.get_all_recipe_titles_async().await?;
|
Some(recipe) => Ok(ViewRecipeTemplate {
|
||||||
let recipe = connection.get_recipe_async(id).await?;
|
user,
|
||||||
|
current_recipe_id: Some(recipe.id),
|
||||||
Ok(ViewRecipeTemplate {
|
recipes,
|
||||||
user,
|
current_recipe: recipe,
|
||||||
current_recipe_id: Some(recipe.id),
|
}
|
||||||
recipes,
|
.into_response()),
|
||||||
current_recipe: recipe,
|
None => Ok(MessageTemplate {
|
||||||
|
user,
|
||||||
|
message: &format!("Cannot find the recipe {}", recipe_id),
|
||||||
|
}
|
||||||
|
.into_response()),
|
||||||
}
|
}
|
||||||
.to_response())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
///// EDIT/NEW RECIPE /////
|
///// EDIT/NEW RECIPE /////
|
||||||
|
|
||||||
#[derive(Template)]
|
// #[derive(Template)]
|
||||||
#[template(path = "edit_recipe.html")]
|
// #[template(path = "edit_recipe.html")]
|
||||||
struct EditRecipeTemplate {
|
// struct EditRecipeTemplate {
|
||||||
user: Option<model::User>,
|
// user: Option<model::User>,
|
||||||
recipes: Vec<(i64, String)>,
|
// recipes: Vec<(i64, String)>,
|
||||||
current_recipe_id: Option<i64>,
|
// current_recipe_id: Option<i64>,
|
||||||
|
|
||||||
current_recipe: model::Recipe,
|
// current_recipe: model::Recipe,
|
||||||
}
|
// }
|
||||||
|
|
||||||
#[get("/recipe/edit/{id}")]
|
// #[get("/recipe/edit/{id}")]
|
||||||
pub async fn edit_recipe(
|
// pub async fn edit_recipe(
|
||||||
req: HttpRequest,
|
// req: HttpRequest,
|
||||||
path: web::Path<(i64,)>,
|
// path: web::Path<(i64,)>,
|
||||||
connection: web::Data<db::Connection>,
|
// connection: web::Data<db::Connection>,
|
||||||
) -> Result<HttpResponse> {
|
// ) -> Result<HttpResponse> {
|
||||||
let (id,) = path.into_inner();
|
// let (id,) = path.into_inner();
|
||||||
let user = match get_current_user(&req, connection.clone()).await {
|
// let user = match get_current_user(&req, connection.clone()).await {
|
||||||
Some(u) => u,
|
// Some(u) => u,
|
||||||
None => {
|
// None => {
|
||||||
return Ok(MessageTemplate {
|
// return Ok(MessageTemplate {
|
||||||
user: None,
|
// user: None,
|
||||||
message: "Cannot edit a recipe without being logged in",
|
// message: "Cannot edit a recipe without being logged in",
|
||||||
}
|
// }
|
||||||
.to_response())
|
// .to_response())
|
||||||
}
|
// }
|
||||||
};
|
// };
|
||||||
|
|
||||||
let recipe = connection.get_recipe_async(id).await?;
|
// let recipe = connection.get_recipe_async(id).await?;
|
||||||
|
|
||||||
if recipe.user_id != user.id {
|
// if recipe.user_id != user.id {
|
||||||
return Ok(MessageTemplate {
|
// return Ok(MessageTemplate {
|
||||||
message: "Cannot edit a recipe you don't own",
|
// message: "Cannot edit a recipe you don't own",
|
||||||
user: Some(user),
|
// user: Some(user),
|
||||||
}
|
// }
|
||||||
.to_response());
|
// .to_response());
|
||||||
}
|
// }
|
||||||
|
|
||||||
let recipes = connection.get_all_recipe_titles_async().await?;
|
// let recipes = connection.get_all_recipe_titles_async().await?;
|
||||||
|
|
||||||
Ok(EditRecipeTemplate {
|
// Ok(EditRecipeTemplate {
|
||||||
user: Some(user),
|
// user: Some(user),
|
||||||
current_recipe_id: Some(recipe.id),
|
// current_recipe_id: Some(recipe.id),
|
||||||
recipes,
|
// recipes,
|
||||||
current_recipe: recipe,
|
// current_recipe: recipe,
|
||||||
}
|
// }
|
||||||
.to_response())
|
// .to_response())
|
||||||
}
|
// }
|
||||||
|
|
||||||
#[get("/recipe/new")]
|
// #[get("/recipe/new")]
|
||||||
pub async fn new_recipe(
|
// pub async fn new_recipe(
|
||||||
req: HttpRequest,
|
// req: HttpRequest,
|
||||||
connection: web::Data<db::Connection>,
|
// connection: web::Data<db::Connection>,
|
||||||
) -> Result<HttpResponse> {
|
// ) -> Result<HttpResponse> {
|
||||||
let user = match get_current_user(&req, connection.clone()).await {
|
// let user = match get_current_user(&req, connection.clone()).await {
|
||||||
Some(u) => u,
|
// Some(u) => u,
|
||||||
None => {
|
// None => {
|
||||||
return Ok(MessageTemplate {
|
// return Ok(MessageTemplate {
|
||||||
message: "Cannot create a recipe without being logged in",
|
// message: "Cannot create a recipe without being logged in",
|
||||||
user: None,
|
// user: None,
|
||||||
}
|
// }
|
||||||
.to_response())
|
// .to_response())
|
||||||
}
|
// }
|
||||||
};
|
// };
|
||||||
|
|
||||||
let recipe_id = connection.create_recipe_async(user.id).await?;
|
// let recipe_id = connection.create_recipe_async(user.id).await?;
|
||||||
let recipes = connection.get_all_recipe_titles_async().await?;
|
// let recipes = connection.get_all_recipe_titles_async().await?;
|
||||||
let user_id = user.id;
|
// let user_id = user.id;
|
||||||
|
|
||||||
Ok(EditRecipeTemplate {
|
// Ok(EditRecipeTemplate {
|
||||||
user: Some(user),
|
// user: Some(user),
|
||||||
current_recipe_id: Some(recipe_id),
|
// current_recipe_id: Some(recipe_id),
|
||||||
recipes,
|
// recipes,
|
||||||
current_recipe: model::Recipe::empty(recipe_id, user_id),
|
// current_recipe: model::Recipe::empty(recipe_id, user_id),
|
||||||
}
|
// }
|
||||||
.to_response())
|
// .to_response())
|
||||||
}
|
// }
|
||||||
|
|
||||||
///// MESSAGE /////
|
///// MESSAGE /////
|
||||||
|
|
||||||
#[derive(Template)]
|
#[derive(Template)]
|
||||||
#[template(path = "message_base.html")]
|
#[template(path = "message_without_user.html")]
|
||||||
struct MessageBaseTemplate<'a> {
|
struct MessageWithoutUser<'a> {
|
||||||
message: &'a str,
|
message: &'a str,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -308,22 +192,20 @@ struct SignUpFormTemplate {
|
||||||
message_password: String,
|
message_password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/signup")]
|
#[debug_handler]
|
||||||
pub async fn sign_up_get(
|
pub async fn sign_up_get(
|
||||||
req: HttpRequest,
|
Extension(user): Extension<Option<model::User>>,
|
||||||
connection: web::Data<db::Connection>,
|
) -> Result<impl IntoResponse> {
|
||||||
) -> impl Responder {
|
Ok(SignUpFormTemplate {
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
|
||||||
SignUpFormTemplate {
|
|
||||||
user,
|
user,
|
||||||
email: String::new(),
|
email: String::new(),
|
||||||
message: String::new(),
|
message: String::new(),
|
||||||
message_email: String::new(),
|
message_email: String::new(),
|
||||||
message_password: String::new(),
|
message_password: String::new(),
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize, Debug)]
|
||||||
pub struct SignUpFormData {
|
pub struct SignUpFormData {
|
||||||
email: String,
|
email: String,
|
||||||
password_1: String,
|
password_1: String,
|
||||||
|
|
@ -339,21 +221,22 @@ enum SignUpError {
|
||||||
UnableSendEmail,
|
UnableSendEmail,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/signup")]
|
#[debug_handler(state = AppState)]
|
||||||
pub async fn sign_up_post(
|
pub async fn sign_up_post(
|
||||||
req: HttpRequest,
|
Host(host): Host,
|
||||||
form: web::Form<SignUpFormData>,
|
State(connection): State<db::Connection>,
|
||||||
connection: web::Data<db::Connection>,
|
State(config): State<Config>,
|
||||||
config: web::Data<Config>,
|
Extension(user): Extension<Option<model::User>>,
|
||||||
) -> Result<HttpResponse> {
|
Form(form_data): Form<SignUpFormData>,
|
||||||
|
) -> Result<Response> {
|
||||||
fn error_response(
|
fn error_response(
|
||||||
error: SignUpError,
|
error: SignUpError,
|
||||||
form: &web::Form<SignUpFormData>,
|
form_data: &SignUpFormData,
|
||||||
user: Option<model::User>,
|
user: Option<model::User>,
|
||||||
) -> Result<HttpResponse> {
|
) -> Result<Response> {
|
||||||
Ok(SignUpFormTemplate {
|
Ok(SignUpFormTemplate {
|
||||||
user,
|
user,
|
||||||
email: form.email.clone(),
|
email: form_data.email.clone(),
|
||||||
message_email: match error {
|
message_email: match error {
|
||||||
SignUpError::InvalidEmail => "Invalid email",
|
SignUpError::InvalidEmail => "Invalid email",
|
||||||
_ => "",
|
_ => "",
|
||||||
|
|
@ -373,40 +256,35 @@ pub async fn sign_up_post(
|
||||||
}
|
}
|
||||||
.to_string(),
|
.to_string(),
|
||||||
}
|
}
|
||||||
.to_response())
|
.into_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
|
||||||
|
|
||||||
// Validation of email and password.
|
// Validation of email and password.
|
||||||
if let common::utils::EmailValidation::NotValid = common::utils::validate_email(&form.email) {
|
if let common::utils::EmailValidation::NotValid =
|
||||||
return error_response(SignUpError::InvalidEmail, &form, user);
|
common::utils::validate_email(&form_data.email)
|
||||||
|
{
|
||||||
|
return error_response(SignUpError::InvalidEmail, &form_data, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
if form.password_1 != form.password_2 {
|
if form_data.password_1 != form_data.password_2 {
|
||||||
return error_response(SignUpError::PasswordsNotEqual, &form, user);
|
return error_response(SignUpError::PasswordsNotEqual, &form_data, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let common::utils::PasswordValidation::TooShort =
|
if let common::utils::PasswordValidation::TooShort =
|
||||||
common::utils::validate_password(&form.password_1)
|
common::utils::validate_password(&form_data.password_1)
|
||||||
{
|
{
|
||||||
return error_response(SignUpError::InvalidPassword, &form, user);
|
return error_response(SignUpError::InvalidPassword, &form_data, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
match connection
|
match connection
|
||||||
.sign_up_async(&form.email, &form.password_1)
|
.sign_up(&form_data.email, &form_data.password_1)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(db::SignUpResult::UserAlreadyExists) => {
|
Ok(db::SignUpResult::UserAlreadyExists) => {
|
||||||
error_response(SignUpError::UserAlreadyExists, &form, user)
|
error_response(SignUpError::UserAlreadyExists, &form_data, user)
|
||||||
}
|
}
|
||||||
Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => {
|
Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => {
|
||||||
let url = {
|
let url = {
|
||||||
let host = req
|
|
||||||
.headers()
|
|
||||||
.get(header::HOST)
|
|
||||||
.map(|v| v.to_str().unwrap_or_default())
|
|
||||||
.unwrap_or_default();
|
|
||||||
let port: Option<u16> = 'p: {
|
let port: Option<u16> = 'p: {
|
||||||
let split_port: Vec<&str> = host.split(':').collect();
|
let split_port: Vec<&str> = host.split(':').collect();
|
||||||
if split_port.len() == 2 {
|
if split_port.len() == 2 {
|
||||||
|
|
@ -427,60 +305,61 @@ pub async fn sign_up_post(
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let email = form.email.clone();
|
println!("{}", &url);
|
||||||
|
|
||||||
match web::block(move || {
|
let email = form_data.email.clone();
|
||||||
email::send_validation(
|
match email::send_validation(
|
||||||
&url,
|
&url,
|
||||||
&email,
|
&email,
|
||||||
&token,
|
&token,
|
||||||
&config.smtp_login,
|
&config.smtp_relay_address,
|
||||||
&config.smtp_password,
|
&config.smtp_login,
|
||||||
)
|
&config.smtp_password,
|
||||||
})
|
)
|
||||||
.await?
|
.await
|
||||||
{
|
{
|
||||||
Ok(()) => Ok(HttpResponse::Found()
|
Ok(()) => Ok(MessageTemplate {
|
||||||
.insert_header((header::LOCATION, "/signup_check_email"))
|
user,
|
||||||
.finish()),
|
message: "An email has been sent, follow the link to validate your account.",
|
||||||
Err(error) => {
|
}
|
||||||
error!("Email validation error: {}", error);
|
.into_response()),
|
||||||
error_response(SignUpError::UnableSendEmail, &form, user)
|
Err(_) => {
|
||||||
|
// error!("Email validation error: {}", error); // TODO: log
|
||||||
|
error_response(SignUpError::UnableSendEmail, &form_data, user)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(_) => {
|
||||||
error!("Signup database error: {}", error);
|
// error!("Signup database error: {}", error);
|
||||||
error_response(SignUpError::DatabaseError, &form, user)
|
error_response(SignUpError::DatabaseError, &form_data, user)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/signup_check_email")]
|
#[debug_handler]
|
||||||
pub async fn sign_up_check_email(
|
|
||||||
req: HttpRequest,
|
|
||||||
connection: web::Data<db::Connection>,
|
|
||||||
) -> impl Responder {
|
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
|
||||||
MessageTemplate {
|
|
||||||
user,
|
|
||||||
message: "An email has been sent, follow the link to validate your account.",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/validation")]
|
|
||||||
pub async fn sign_up_validation(
|
pub async fn sign_up_validation(
|
||||||
req: HttpRequest,
|
State(connection): State<db::Connection>,
|
||||||
query: web::Query<HashMap<String, String>>,
|
Extension(user): Extension<Option<model::User>>,
|
||||||
connection: web::Data<db::Connection>,
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
) -> Result<HttpResponse> {
|
Query(query): Query<HashMap<String, String>>,
|
||||||
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
|
headers: HeaderMap,
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
) -> Result<(CookieJar, impl IntoResponse)> {
|
||||||
|
let mut jar = CookieJar::from_headers(&headers);
|
||||||
match query.get("token") {
|
if user.is_some() {
|
||||||
|
return Ok((
|
||||||
|
jar,
|
||||||
|
MessageTemplate {
|
||||||
|
user,
|
||||||
|
message: "User already exists",
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(&headers, addr);
|
||||||
|
match query.get("validation_token") {
|
||||||
|
// 'validation_token' exists only when a user tries to validate a new account.
|
||||||
Some(token) => {
|
Some(token) => {
|
||||||
match connection
|
match connection
|
||||||
.validation_async(
|
.validation(
|
||||||
token,
|
token,
|
||||||
Duration::seconds(consts::VALIDATION_TOKEN_DURATION),
|
Duration::seconds(consts::VALIDATION_TOKEN_DURATION),
|
||||||
&client_ip,
|
&client_ip,
|
||||||
|
|
@ -490,43 +369,39 @@ pub async fn sign_up_validation(
|
||||||
{
|
{
|
||||||
db::ValidationResult::Ok(token, user_id) => {
|
db::ValidationResult::Ok(token, user_id) => {
|
||||||
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
|
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
|
||||||
let user = match connection.load_user(user_id) {
|
jar = jar.add(cookie);
|
||||||
Ok(user) => Some(user),
|
let user = connection.load_user(user_id).await?;
|
||||||
Err(error) => {
|
Ok((
|
||||||
error!("Error retrieving user by id: {}", error);
|
jar,
|
||||||
None
|
MessageTemplate {
|
||||||
}
|
user,
|
||||||
};
|
message: "Email validation successful, your account has been created",
|
||||||
|
},
|
||||||
let mut response = MessageTemplate {
|
))
|
||||||
|
}
|
||||||
|
db::ValidationResult::ValidationExpired => Ok((
|
||||||
|
jar,
|
||||||
|
MessageTemplate {
|
||||||
user,
|
user,
|
||||||
message: "Email validation successful, your account has been created",
|
message: "The validation has expired. Try to sign up again",
|
||||||
}
|
},
|
||||||
.to_response();
|
)),
|
||||||
|
db::ValidationResult::UnknownUser => Ok((
|
||||||
if let Err(error) = response.add_cookie(&cookie) {
|
jar,
|
||||||
error!("Unable to set cookie after validation: {}", error);
|
MessageTemplate {
|
||||||
};
|
user,
|
||||||
|
message: "Validation error. Try to sign up again",
|
||||||
Ok(response)
|
},
|
||||||
}
|
)),
|
||||||
db::ValidationResult::ValidationExpired => Ok(MessageTemplate {
|
|
||||||
user,
|
|
||||||
message: "The validation has expired. Try to sign up again.",
|
|
||||||
}
|
|
||||||
.to_response()),
|
|
||||||
db::ValidationResult::UnknownUser => Ok(MessageTemplate {
|
|
||||||
user,
|
|
||||||
message: "Validation error.",
|
|
||||||
}
|
|
||||||
.to_response()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => Ok(MessageTemplate {
|
None => Ok((
|
||||||
user,
|
jar,
|
||||||
message: &format!("No token provided"),
|
MessageTemplate {
|
||||||
}
|
user,
|
||||||
.to_response()),
|
message: "Validation error",
|
||||||
|
},
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -540,109 +415,89 @@ struct SignInFormTemplate {
|
||||||
message: String,
|
message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/signin")]
|
#[debug_handler]
|
||||||
pub async fn sign_in_get(
|
pub async fn sign_in_get(
|
||||||
req: HttpRequest,
|
Extension(user): Extension<Option<model::User>>,
|
||||||
connection: web::Data<db::Connection>,
|
) -> Result<impl IntoResponse> {
|
||||||
) -> impl Responder {
|
Ok(SignInFormTemplate {
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
|
||||||
SignInFormTemplate {
|
|
||||||
user,
|
user,
|
||||||
email: String::new(),
|
email: String::new(),
|
||||||
message: String::new(),
|
message: String::new(),
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize, Debug)]
|
||||||
pub struct SignInFormData {
|
pub struct SignInFormData {
|
||||||
email: String,
|
email: String,
|
||||||
password: String,
|
password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
enum SignInError {
|
#[debug_handler]
|
||||||
AccountNotValidated,
|
|
||||||
AuthenticationFailed,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/signin")]
|
|
||||||
pub async fn sign_in_post(
|
pub async fn sign_in_post(
|
||||||
req: HttpRequest,
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
form: web::Form<SignInFormData>,
|
State(connection): State<db::Connection>,
|
||||||
connection: web::Data<db::Connection>,
|
Extension(user): Extension<Option<model::User>>,
|
||||||
) -> Result<HttpResponse> {
|
headers: HeaderMap,
|
||||||
fn error_response(
|
Form(form_data): Form<SignInFormData>,
|
||||||
error: SignInError,
|
) -> Result<(CookieJar, Response)> {
|
||||||
form: &web::Form<SignInFormData>,
|
let jar = CookieJar::from_headers(&headers);
|
||||||
user: Option<model::User>,
|
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(&headers, addr);
|
||||||
) -> Result<HttpResponse> {
|
|
||||||
Ok(SignInFormTemplate {
|
|
||||||
user,
|
|
||||||
email: form.email.clone(),
|
|
||||||
message: match error {
|
|
||||||
SignInError::AccountNotValidated => "This account must be validated first",
|
|
||||||
SignInError::AuthenticationFailed => "Wrong email or password",
|
|
||||||
}
|
|
||||||
.to_string(),
|
|
||||||
}
|
|
||||||
.to_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
|
||||||
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
|
|
||||||
|
|
||||||
match connection
|
match connection
|
||||||
.sign_in_async(&form.email, &form.password, &client_ip, &client_user_agent)
|
.sign_in(
|
||||||
.await
|
&form_data.email,
|
||||||
|
&form_data.password,
|
||||||
|
&client_ip,
|
||||||
|
&client_user_agent,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
{
|
{
|
||||||
Ok(db::SignInResult::AccountNotValidated) => {
|
db::SignInResult::AccountNotValidated => Ok((
|
||||||
error_response(SignInError::AccountNotValidated, &form, user)
|
jar,
|
||||||
}
|
SignInFormTemplate {
|
||||||
Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => {
|
user,
|
||||||
error_response(SignInError::AuthenticationFailed, &form, user)
|
email: form_data.email,
|
||||||
}
|
message: "This account must be validated first".to_string(),
|
||||||
Ok(db::SignInResult::Ok(token, user_id)) => {
|
}
|
||||||
|
.into_response(),
|
||||||
|
)),
|
||||||
|
db::SignInResult::UserNotFound | db::SignInResult::WrongPassword => Ok((
|
||||||
|
jar,
|
||||||
|
SignInFormTemplate {
|
||||||
|
user,
|
||||||
|
email: form_data.email,
|
||||||
|
message: "Wrong email or password".to_string(),
|
||||||
|
}
|
||||||
|
.into_response(),
|
||||||
|
)),
|
||||||
|
db::SignInResult::Ok(token, _user_id) => {
|
||||||
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
|
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
|
||||||
let mut response = HttpResponse::Found()
|
Ok((jar.add(cookie), Redirect::to("/").into_response()))
|
||||||
.insert_header((header::LOCATION, "/"))
|
|
||||||
.finish();
|
|
||||||
if let Err(error) = response.add_cookie(&cookie) {
|
|
||||||
error!("Unable to set cookie after sign in: {}", error);
|
|
||||||
};
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
error!("Signin error: {}", error);
|
|
||||||
error_response(SignInError::AuthenticationFailed, &form, user)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///// SIGN OUT /////
|
///// SIGN OUT /////
|
||||||
|
|
||||||
#[get("/signout")]
|
#[debug_handler]
|
||||||
pub async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
|
pub async fn sign_out(
|
||||||
let mut response = HttpResponse::Found()
|
State(connection): State<db::Connection>,
|
||||||
.insert_header((header::LOCATION, "/"))
|
req: Request<Body>,
|
||||||
.finish();
|
) -> Result<(CookieJar, Redirect)> {
|
||||||
|
let mut jar = CookieJar::from_headers(req.headers());
|
||||||
if let Some(token_cookie) = req.cookie(consts::COOKIE_AUTH_TOKEN_NAME) {
|
if let Some(token_cookie) = jar.get(consts::COOKIE_AUTH_TOKEN_NAME) {
|
||||||
if let Err(error) = connection.sign_out_async(token_cookie.value()).await {
|
let token = token_cookie.value().to_string();
|
||||||
error!("Unable to sign out: {}", error);
|
jar = jar.remove(consts::COOKIE_AUTH_TOKEN_NAME);
|
||||||
};
|
connection.sign_out(&token).await?;
|
||||||
|
|
||||||
if let Err(error) =
|
|
||||||
response.add_removal_cookie(&Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, ""))
|
|
||||||
{
|
|
||||||
error!("Unable to set a removal cookie after sign out: {}", error);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn not_found(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
|
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
|
||||||
MessageTemplate {
|
|
||||||
user,
|
|
||||||
message: "404: Not found",
|
|
||||||
}
|
}
|
||||||
|
Ok((jar, Redirect::to("/")))
|
||||||
|
}
|
||||||
|
|
||||||
|
///// 404 /////
|
||||||
|
|
||||||
|
#[debug_handler]
|
||||||
|
pub async fn not_found() -> Result<impl IntoResponse> {
|
||||||
|
Ok(MessageWithoutUser {
|
||||||
|
message: "404: Not found",
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,38 +1,38 @@
|
||||||
use actix_web::{
|
// use actix_web::{
|
||||||
http::{header, header::ContentType, StatusCode},
|
// http::{header, header::ContentType, StatusCode},
|
||||||
post, put, web, HttpMessage, HttpRequest, HttpResponse, Responder,
|
// post, put, web, HttpMessage, HttpRequest, HttpResponse, Responder,
|
||||||
};
|
// };
|
||||||
use log::{debug, error, info, log_enabled, Level};
|
// use log::{debug, error, info, log_enabled, Level};
|
||||||
use ron::de::from_bytes;
|
// use ron::de::from_bytes;
|
||||||
|
|
||||||
use super::Result;
|
// use super::Result;
|
||||||
use crate::data::{asynchronous, db};
|
// use crate::data::db;
|
||||||
|
|
||||||
#[put("/ron-api/recipe/set-title")]
|
// #[put("/ron-api/recipe/set-title")]
|
||||||
pub async fn set_recipe_title(
|
// pub async fn set_recipe_title(
|
||||||
req: HttpRequest,
|
// req: HttpRequest,
|
||||||
body: web::Bytes,
|
// body: web::Bytes,
|
||||||
connection: web::Data<db::Connection>,
|
// connection: web::Data<db::Connection>,
|
||||||
) -> Result<HttpResponse> {
|
// ) -> Result<HttpResponse> {
|
||||||
let ron_req: common::ron_api::SetRecipeTitle = from_bytes(&body)?;
|
// let ron_req: common::ron_api::SetRecipeTitle = from_bytes(&body)?;
|
||||||
connection
|
// connection
|
||||||
.set_recipe_title_async(ron_req.recipe_id, &ron_req.title)
|
// .set_recipe_title_async(ron_req.recipe_id, &ron_req.title)
|
||||||
.await?;
|
// .await?;
|
||||||
Ok(HttpResponse::Ok().finish())
|
// Ok(HttpResponse::Ok().finish())
|
||||||
}
|
// }
|
||||||
|
|
||||||
#[put("/ron-api/recipe/set-description")]
|
// #[put("/ron-api/recipe/set-description")]
|
||||||
pub async fn set_recipe_description(
|
// pub async fn set_recipe_description(
|
||||||
req: HttpRequest,
|
// req: HttpRequest,
|
||||||
body: web::Bytes,
|
// body: web::Bytes,
|
||||||
connection: web::Data<db::Connection>,
|
// connection: web::Data<db::Connection>,
|
||||||
) -> Result<HttpResponse> {
|
// ) -> Result<HttpResponse> {
|
||||||
let ron_req: common::ron_api::SetRecipeDescription = from_bytes(&body)?;
|
// let ron_req: common::ron_api::SetRecipeDescription = from_bytes(&body)?;
|
||||||
connection
|
// connection
|
||||||
.set_recipe_description_async(ron_req.recipe_id, &ron_req.description)
|
// .set_recipe_description_async(ron_req.recipe_id, &ron_req.description)
|
||||||
.await?;
|
// .await?;
|
||||||
Ok(HttpResponse::Ok().finish())
|
// Ok(HttpResponse::Ok().finish())
|
||||||
}
|
// }
|
||||||
|
|
||||||
// #[put("/ron-api/recipe/add-image)]
|
// #[put("/ron-api/recipe/add-image)]
|
||||||
// #[put("/ron-api/recipe/rm-photo")]
|
// #[put("/ron-api/recipe/rm-photo")]
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,20 @@
|
||||||
use log::error;
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
pub fn unwrap_print_err<T, E>(r: Result<T, E>) -> T
|
use axum::http::HeaderMap;
|
||||||
where
|
|
||||||
E: std::fmt::Debug,
|
use crate::consts;
|
||||||
{
|
|
||||||
if let Err(ref error) = r {
|
pub fn get_ip_and_user_agent(headers: &HeaderMap, remote_address: SocketAddr) -> (String, String) {
|
||||||
error!("{:?}", error);
|
let ip = match headers.get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
|
||||||
}
|
Some(v) => v.to_str().unwrap_or_default().to_string(),
|
||||||
r.unwrap()
|
None => remote_address.to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let user_agent = headers
|
||||||
|
.get(axum::http::header::USER_AGENT)
|
||||||
|
.map(|v| v.to_str().unwrap_or_default())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
(ip, user_agent)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
{% block body_container %}
|
{% block body_container %}
|
||||||
<div class="header-container">
|
<div class="header-container">
|
||||||
<a class="title" href="/">~~ Recettes de cuisine ~~</a>
|
{% include "title.html" %}
|
||||||
|
|
||||||
{% match user %}
|
{% match user %}
|
||||||
{% when Some with (user) %}
|
{% when Some with (user) %}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
{% extends "base_with_header.html" %}
|
{% extends "base_with_header.html" %}
|
||||||
|
|
||||||
{% block main_container %}
|
{% block main_container %}
|
||||||
|
{{ message|markdown }}
|
||||||
{{ message|markdown }}
|
<a href="/">Go to home</a>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
|
|
||||||
{% block body_container %}
|
{% block body_container %}
|
||||||
{% include "title.html" %}
|
{% include "title.html" %}
|
||||||
{{ message|markdown }}
|
{{ message|markdown }}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
@ -1 +1 @@
|
||||||
<h1><a href="/">~~ Recettes de cuisine ~~</a></h1>
|
<a class="title" href="/">~~ Recettes de cuisine ~~</a>
|
||||||
2
check_cargo_dependencies_upgrade.nu
Normal file
2
check_cargo_dependencies_upgrade.nu
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
# It needs cargo-edit: https://crates.io/crates/cargo-edit .
|
||||||
|
cargo upgrade --dry-run --verbose
|
||||||
|
|
@ -1,2 +1,2 @@
|
||||||
|
pub mod ron_api;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
pub mod ron_api;
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
use ron::de::from_reader;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone)]
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
use regex::Regex;
|
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
pub enum EmailValidation {
|
pub enum EmailValidation {
|
||||||
Ok,
|
Ok,
|
||||||
|
|
@ -7,11 +7,18 @@ pub enum EmailValidation {
|
||||||
}
|
}
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref EMAIL_REGEX: Regex = Regex::new(r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})").expect("Error parsing email regex");
|
static ref EMAIL_REGEX: Regex = Regex::new(
|
||||||
|
r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})"
|
||||||
|
)
|
||||||
|
.expect("Error parsing email regex");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn validate_email(email: &str) -> EmailValidation {
|
pub fn validate_email(email: &str) -> EmailValidation {
|
||||||
if EMAIL_REGEX.is_match(email) { EmailValidation::Ok } else { EmailValidation::NotValid }
|
if EMAIL_REGEX.is_match(email) {
|
||||||
|
EmailValidation::Ok
|
||||||
|
} else {
|
||||||
|
EmailValidation::NotValid
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum PasswordValidation {
|
pub enum PasswordValidation {
|
||||||
|
|
@ -20,5 +27,9 @@ pub enum PasswordValidation {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn validate_password(password: &str) -> PasswordValidation {
|
pub fn validate_password(password: &str) -> PasswordValidation {
|
||||||
if password.len() < 8 { PasswordValidation::TooShort } else { PasswordValidation::Ok }
|
if password.len() < 8 {
|
||||||
}
|
PasswordValidation::TooShort
|
||||||
|
} else {
|
||||||
|
PasswordValidation::Ok
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,20 @@
|
||||||
def main [host: string, destination: string, ssh_key: path] {
|
def main [host: string, destination: string, ssh_key: path] {
|
||||||
let ssh_args = [-i $ssh_key $host]
|
let ssh_args = [-i $ssh_key $host]
|
||||||
let scp_args = [-r -i $ssh_key]
|
let scp_args = [-r -i $ssh_key]
|
||||||
let target = "aarch64-unknown-linux-gnu" # For raspberry pi zero 1: "arm-unknown-linux-gnueabihf"
|
|
||||||
|
# For raspberry pi zero 1: "arm-unknown-linux-gnueabihf"
|
||||||
|
let target = "aarch64-unknown-linux-gnu"
|
||||||
|
|
||||||
def invoke_ssh [command: list] {
|
def invoke_ssh [command: list] {
|
||||||
let args = $ssh_args ++ $command
|
let args = $ssh_args ++ $command
|
||||||
print $"Executing: ssh ($args)"
|
print $"Executing: ssh ($args)"
|
||||||
ssh $args
|
ssh ...$args
|
||||||
}
|
}
|
||||||
|
|
||||||
def copy_ssh [source: string, destination: string] {
|
def copy_ssh [source: string, destination: string] {
|
||||||
let args = $scp_args ++ [$source $"($host):($destination)"]
|
let args = $scp_args ++ [$source $"($host):($destination)"]
|
||||||
print $"Executing: scp ($args)"
|
print $"Executing: scp ($args)"
|
||||||
scp $args
|
scp ...$args
|
||||||
}
|
}
|
||||||
|
|
||||||
cargo build --target $target --release
|
cargo build --target $target --release
|
||||||
|
|
@ -25,4 +27,3 @@ def main [host: string, destination: string, ssh_key: path] {
|
||||||
invoke_ssh [sudo systemctl start recipes]
|
invoke_ssh [sudo systemctl start recipes]
|
||||||
print "Deployment finished"
|
print "Deployment finished"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,21 +11,29 @@ crate-type = ["cdylib"]
|
||||||
default = ["console_error_panic_hook"]
|
default = ["console_error_panic_hook"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
common = {path = "../common"}
|
common = { path = "../common" }
|
||||||
|
|
||||||
wasm-bindgen = "0.2"
|
wasm-bindgen = "0.2"
|
||||||
web-sys = {version = "0.3", features = ['console', 'Document', 'Element', 'HtmlElement', 'Node', 'Window', 'Location']}
|
web-sys = { version = "0.3", features = [
|
||||||
|
'console',
|
||||||
|
'Document',
|
||||||
|
'Element',
|
||||||
|
'HtmlElement',
|
||||||
|
'Node',
|
||||||
|
'Window',
|
||||||
|
'Location',
|
||||||
|
] }
|
||||||
|
|
||||||
# The `console_error_panic_hook` crate provides better debugging of panics by
|
# The `console_error_panic_hook` crate provides better debugging of panics by
|
||||||
# logging them with `console.error`. This is great for development, but requires
|
# logging them with `console.error`. This is great for development, but requires
|
||||||
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
|
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
|
||||||
# code size when deploying.
|
# code size when deploying.
|
||||||
console_error_panic_hook = {version = "0.1", optional = true}
|
console_error_panic_hook = { version = "0.1", optional = true }
|
||||||
|
|
||||||
# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
|
# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
|
||||||
# compared to the default allocator's ~10K. It is slower than the default
|
# compared to the default allocator's ~10K. It is slower than the default
|
||||||
# allocator, however.
|
# allocator, however.
|
||||||
wee_alloc = {version = "0.4", optional = true}
|
wee_alloc = { version = "0.4", optional = true }
|
||||||
|
|
||||||
# [dev-dependencies]
|
# [dev-dependencies]
|
||||||
# wasm-bindgen-test = "0.3"
|
# wasm-bindgen-test = "0.3"
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue