Replace Rusqlite by Sqlx and Actix by Axum (A lot of changes)

This commit is contained in:
Greg Burri 2024-11-03 10:13:31 +01:00
parent 57d7e7a3ce
commit 980c5884a4
28 changed files with 2860 additions and 2262 deletions

2813
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,8 @@
[workspace]
members = [
"backend",
"frontend",
"common",
]
resolver = "2"
members = ["backend", "frontend", "common"]
[profile.release]
strip = true

View file

@ -46,7 +46,6 @@ To launch node run 'npm run start' in 'frontend/www' directory
## Useful URLs
* 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/

17
TODO.md
View file

@ -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)
* Understand the example here:
* https://github.com/rustwasm/wasm-bindgen/tree/main/examples/todomvc -> https://rustwasm.github.io/wasm-bindgen/exbuild/todomvc/#/
* Describe the use cases.
* Define the UI (mockups).
* Add a level of severity for the message template, use error severity in "impl axum::response::IntoResponse for db::DBError"
* Review the recipe model (SQL)
* Describe the use cases in details.
* Define the UI (mockups).
* 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.
* 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.
[ok] Reactivate sign up/in/out
[ok] Change all id to i64
[ok] Check cookie lifetime -> Session by default
[ok] Asynchonous email sending and database requests
[ok] Try to return Result for async routes (and watch what is printed in log)
[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] How to log error to journalctl?
[ok] Sign out
[ok] Read all the askama doc and see if the current approach is good
[ok] Handle 404

View file

@ -5,36 +5,48 @@ authors = ["Grégory Burri <greg.burri@gmail.com>"]
edition = "2021"
[dependencies]
common = {path = "../common"}
common = { path = "../common" }
actix-web = "4"
actix-files = "0.6"
axum = { version = "0.7", features = ["macros"] }
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"
ron = "0.8" # Rust object notation, to load configuration files.
serde = {version = "1.0", features = ["derive"]}
# Rust object notation, to load configuration files.
ron = "0.8"
serde = { version = "1.0", features = ["derive"] }
itertools = "0.10"
clap = {version = "4", features = ["derive"]}
itertools = "0.13"
clap = { version = "4", features = ["derive"] }
log = "0.4"
env_logger = "0.10"
sqlx = { version = "0.8", features = ["sqlite", "runtime-tokio", "chrono"] }
r2d2_sqlite = "0.21" # Connection pool with rusqlite (SQLite access).
r2d2 = "0.8"
rusqlite = {version = "0.28", features = ["bundled", "chrono"]}
futures = "0.3" # Needed by askam with the feature 'with-actix-web'.
askama = {version = "0.12", features = ["with-actix-web", "mime", "mime_guess", "markdown"]}
askama_actix = "0.14"
argon2 = {version = "0.5", features = ["default", "std"]}
rand_core = {version = "0.6", features = ["std"]}
askama = { version = "0.12", features = [
"with-axum",
"mime",
"mime_guess",
"markdown",
] }
askama_axum = "0.4"
argon2 = { version = "0.5", features = ["default", "std"] }
rand_core = { version = "0.6", features = ["std"] }
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"

View file

@ -1,22 +1,38 @@
use std::{fmt, fs::File};
use ron::de::from_reader;
use serde::Deserialize;
use ron::{
de::from_reader,
ser::{to_writer_pretty, PrettyConfig},
};
use serde::{Deserialize, Serialize};
use crate::consts;
#[derive(Deserialize, Clone)]
#[derive(Deserialize, Serialize, Clone)]
pub struct Config {
pub port: u16,
pub smtp_relay_address: String,
pub smtp_login: 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.
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Config")
.field("port", &self.port)
.field("smtp_relay_address", &self.smtp_relay_address)
.field("smtp_login", &self.smtp_login)
.field("smtp_password", &"*****")
.finish()
@ -24,10 +40,25 @@ impl fmt::Debug for Config {
}
pub fn load() -> Config {
let f = File::open(consts::FILE_CONF)
.unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
match from_reader(f) {
Ok(c) => c,
Err(e) => panic!("Failed to load config: {}", e),
match File::open(consts::FILE_CONF) {
Ok(file) => from_reader(file).expect(&format!(
"Failed to open configuration file {}",
consts::FILE_CONF
)),
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
}
}
}

View file

@ -5,7 +5,13 @@ pub const DB_DIRECTORY: &str = "data";
pub const DB_FILENAME: &str = "recipes.sqlite";
pub const SQL_FILENAME: &str = "sql/version_{VERSION}.sql";
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 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);
// 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).

View file

@ -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

View file

@ -1,2 +1,2 @@
pub mod asynchronous;
pub mod db;
mod utils;

33
backend/src/data/utils.rs Normal file
View 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")?,
})
}
}

View file

@ -1,6 +1,8 @@
use derive_more::Display;
use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
use std::time::Duration;
use lettre::{
transport::smtp::{authentication::Credentials, AsyncSmtpTransport},
AsyncTransport, Message, Tokio1Executor,
};
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,
email: &str,
token: &str,
smtp_relay_address: &str,
smtp_login: &str,
smtp_password: &str,
) -> Result<(), Error> {
@ -40,20 +43,20 @@ pub fn send_validation(
.message_id(None)
.from("recipes@gburri.org".parse()?)
.to(email.parse()?)
.subject("Recipes.gburri.org account validation")
.subject("recipes.gburri.org account validation")
.body(format!(
"Follow this link to confirm your inscription: {}/validation?token={}",
"Follow this link to confirm your inscription: {}/validation?validation_token={}",
site_url, token
))?;
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)
.timeout(Some(consts::SEND_EMAIL_TIMEOUT))
.build();
if let Err(error) = mailer.send(&email) {
if let Err(error) = mailer.send(email).await {
eprintln!("Error when sending E-mail:\n{:?}", &error);
}

View file

@ -1,9 +1,17 @@
use std::path::Path;
use std::{net::SocketAddr, path::Path};
use actix_files as fs;
use actix_web::{middleware, web, App, HttpServer};
use axum::{
extract::{ConnectInfo, FromRef, Request, State},
middleware::{self, Next},
response::{Response, Result},
routing::get,
Router,
};
use axum_extra::extract::cookie::CookieJar;
use chrono::prelude::*;
use clap::Parser;
use config::Config;
use tower_http::services::ServeDir;
use data::db;
@ -16,49 +24,121 @@ mod model;
mod services;
mod utils;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
if process_args() {
return Ok(());
}
#[derive(Clone)]
struct AppState {
config: Config,
db_connection: db::Connection,
}
std::env::set_var("RUST_LOG", "info,actix_web=info");
env_logger::init();
impl FromRef<AppState> for Config {
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...");
let config = web::Data::new(config::load());
let port = config.as_ref().port;
let config = config::load();
let port = config.port;
println!("Configuration: {:?}", config);
let db_connection = web::Data::new(db::Connection::new().unwrap());
tracing_subscriber::fmt::init();
let server = HttpServer::new(move || {
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);
let db_connection = db::Connection::new().await.unwrap();
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)]
@ -68,7 +148,7 @@ struct Args {
dbtest: bool,
}
fn process_args() -> bool {
async fn process_args() -> bool {
let args = Args::parse();
if args.dbtest {
@ -93,16 +173,18 @@ fn process_args() -> bool {
.expect(&format!("Unable to remove db file: {:?}", &db_path));
}
match db::Connection::new() {
match db::Connection::new().await {
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);
}
// Set the creation datetime to 'now'.
con.execute_sql(
"UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'",
[Utc::now()],
sqlx::query(
"UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'")
.bind(Utc::now())
)
.await
.unwrap();
}
Err(error) => {

View file

@ -1,5 +1,6 @@
use chrono::prelude::*;
#[derive(Debug, Clone)]
pub struct User {
pub id: i64,
pub email: String,

View file

@ -1,145 +1,29 @@
use std::collections::HashMap;
use std::{collections::HashMap, net::SocketAddr};
use actix_web::{
cookie::Cookie,
get,
http::{header, header::ContentType, StatusCode},
post, web, HttpRequest, HttpResponse, Responder,
use askama::Template;
use axum::{
body::Body,
debug_handler,
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 log::{debug, error, info, log_enabled, Level};
use serde::Deserialize;
use crate::{
config::Config,
consts,
data::{asynchronous, db},
email, model, utils,
};
use crate::{config::Config, consts, data::db, email, model, utils, AppState};
pub mod webapi;
///// UTILS /////
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
let ip = match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
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 {
impl axum::response::IntoResponse for db::DBError {
fn into_response(self) -> Response {
let body = MessageTemplate {
user: None,
message: &self.to_string(),
}
.to_response()
}
fn status_code(&self) -> StatusCode {
self.status_code
};
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}
}
@ -153,20 +37,18 @@ struct HomeTemplate {
current_recipe_id: Option<i64>,
}
#[get("/")]
#[debug_handler]
pub async fn home_page(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let user = get_current_user(&req, connection.clone()).await;
let recipes = connection.get_all_recipe_titles_async().await?;
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
) -> Result<impl IntoResponse> {
let recipes = connection.get_all_recipe_titles().await?;
Ok(HomeTemplate {
user,
current_recipe_id: None,
recipes,
}
.to_response())
})
}
///// VIEW RECIPE /////
@ -177,115 +59,117 @@ struct ViewRecipeTemplate {
user: Option<model::User>,
recipes: Vec<(i64, String)>,
current_recipe_id: Option<i64>,
current_recipe: model::Recipe,
}
#[get("/recipe/view/{id}")]
#[debug_handler]
pub async fn view_recipe(
req: HttpRequest,
path: web::Path<(i64,)>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let (id,) = path.into_inner();
let user = get_current_user(&req, connection.clone()).await;
let recipes = connection.get_all_recipe_titles_async().await?;
let recipe = connection.get_recipe_async(id).await?;
Ok(ViewRecipeTemplate {
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Path(recipe_id): Path<i64>,
) -> Result<Response> {
let recipes = connection.get_all_recipe_titles().await?;
match connection.get_recipe(recipe_id).await? {
Some(recipe) => Ok(ViewRecipeTemplate {
user,
current_recipe_id: Some(recipe.id),
recipes,
current_recipe: recipe,
}
.to_response())
.into_response()),
None => Ok(MessageTemplate {
user,
message: &format!("Cannot find the recipe {}", recipe_id),
}
.into_response()),
}
}
///// EDIT/NEW RECIPE /////
#[derive(Template)]
#[template(path = "edit_recipe.html")]
struct EditRecipeTemplate {
user: Option<model::User>,
recipes: Vec<(i64, String)>,
current_recipe_id: Option<i64>,
// #[derive(Template)]
// #[template(path = "edit_recipe.html")]
// struct EditRecipeTemplate {
// user: Option<model::User>,
// recipes: Vec<(i64, String)>,
// current_recipe_id: Option<i64>,
current_recipe: model::Recipe,
}
// current_recipe: model::Recipe,
// }
#[get("/recipe/edit/{id}")]
pub async fn edit_recipe(
req: HttpRequest,
path: web::Path<(i64,)>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let (id,) = path.into_inner();
let user = match get_current_user(&req, connection.clone()).await {
Some(u) => u,
None => {
return Ok(MessageTemplate {
user: None,
message: "Cannot edit a recipe without being logged in",
}
.to_response())
}
};
// #[get("/recipe/edit/{id}")]
// pub async fn edit_recipe(
// req: HttpRequest,
// path: web::Path<(i64,)>,
// connection: web::Data<db::Connection>,
// ) -> Result<HttpResponse> {
// let (id,) = path.into_inner();
// let user = match get_current_user(&req, connection.clone()).await {
// Some(u) => u,
// None => {
// return Ok(MessageTemplate {
// user: None,
// message: "Cannot edit a recipe without being logged in",
// }
// .to_response())
// }
// };
let recipe = connection.get_recipe_async(id).await?;
// let recipe = connection.get_recipe_async(id).await?;
if recipe.user_id != user.id {
return Ok(MessageTemplate {
message: "Cannot edit a recipe you don't own",
user: Some(user),
}
.to_response());
}
// if recipe.user_id != user.id {
// return Ok(MessageTemplate {
// message: "Cannot edit a recipe you don't own",
// user: Some(user),
// }
// .to_response());
// }
let recipes = connection.get_all_recipe_titles_async().await?;
// let recipes = connection.get_all_recipe_titles_async().await?;
Ok(EditRecipeTemplate {
user: Some(user),
current_recipe_id: Some(recipe.id),
recipes,
current_recipe: recipe,
}
.to_response())
}
// Ok(EditRecipeTemplate {
// user: Some(user),
// current_recipe_id: Some(recipe.id),
// recipes,
// current_recipe: recipe,
// }
// .to_response())
// }
#[get("/recipe/new")]
pub async fn new_recipe(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let user = match get_current_user(&req, connection.clone()).await {
Some(u) => u,
None => {
return Ok(MessageTemplate {
message: "Cannot create a recipe without being logged in",
user: None,
}
.to_response())
}
};
// #[get("/recipe/new")]
// pub async fn new_recipe(
// req: HttpRequest,
// connection: web::Data<db::Connection>,
// ) -> Result<HttpResponse> {
// let user = match get_current_user(&req, connection.clone()).await {
// Some(u) => u,
// None => {
// return Ok(MessageTemplate {
// message: "Cannot create a recipe without being logged in",
// user: None,
// }
// .to_response())
// }
// };
let recipe_id = connection.create_recipe_async(user.id).await?;
let recipes = connection.get_all_recipe_titles_async().await?;
let user_id = user.id;
// let recipe_id = connection.create_recipe_async(user.id).await?;
// let recipes = connection.get_all_recipe_titles_async().await?;
// let user_id = user.id;
Ok(EditRecipeTemplate {
user: Some(user),
current_recipe_id: Some(recipe_id),
recipes,
current_recipe: model::Recipe::empty(recipe_id, user_id),
}
.to_response())
}
// Ok(EditRecipeTemplate {
// user: Some(user),
// current_recipe_id: Some(recipe_id),
// recipes,
// current_recipe: model::Recipe::empty(recipe_id, user_id),
// }
// .to_response())
// }
///// MESSAGE /////
#[derive(Template)]
#[template(path = "message_base.html")]
struct MessageBaseTemplate<'a> {
#[template(path = "message_without_user.html")]
struct MessageWithoutUser<'a> {
message: &'a str,
}
@ -308,22 +192,20 @@ struct SignUpFormTemplate {
message_password: String,
}
#[get("/signup")]
#[debug_handler]
pub async fn sign_up_get(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> impl Responder {
let user = get_current_user(&req, connection.clone()).await;
SignUpFormTemplate {
Extension(user): Extension<Option<model::User>>,
) -> Result<impl IntoResponse> {
Ok(SignUpFormTemplate {
user,
email: String::new(),
message: String::new(),
message_email: String::new(),
message_password: String::new(),
}
})
}
#[derive(Deserialize)]
#[derive(Deserialize, Debug)]
pub struct SignUpFormData {
email: String,
password_1: String,
@ -339,21 +221,22 @@ enum SignUpError {
UnableSendEmail,
}
#[post("/signup")]
#[debug_handler(state = AppState)]
pub async fn sign_up_post(
req: HttpRequest,
form: web::Form<SignUpFormData>,
connection: web::Data<db::Connection>,
config: web::Data<Config>,
) -> Result<HttpResponse> {
Host(host): Host,
State(connection): State<db::Connection>,
State(config): State<Config>,
Extension(user): Extension<Option<model::User>>,
Form(form_data): Form<SignUpFormData>,
) -> Result<Response> {
fn error_response(
error: SignUpError,
form: &web::Form<SignUpFormData>,
form_data: &SignUpFormData,
user: Option<model::User>,
) -> Result<HttpResponse> {
) -> Result<Response> {
Ok(SignUpFormTemplate {
user,
email: form.email.clone(),
email: form_data.email.clone(),
message_email: match error {
SignUpError::InvalidEmail => "Invalid email",
_ => "",
@ -373,40 +256,35 @@ pub async fn sign_up_post(
}
.to_string(),
}
.to_response())
.into_response())
}
let user = get_current_user(&req, connection.clone()).await;
// Validation of email and password.
if let common::utils::EmailValidation::NotValid = common::utils::validate_email(&form.email) {
return error_response(SignUpError::InvalidEmail, &form, user);
if let common::utils::EmailValidation::NotValid =
common::utils::validate_email(&form_data.email)
{
return error_response(SignUpError::InvalidEmail, &form_data, user);
}
if form.password_1 != form.password_2 {
return error_response(SignUpError::PasswordsNotEqual, &form, user);
if form_data.password_1 != form_data.password_2 {
return error_response(SignUpError::PasswordsNotEqual, &form_data, user);
}
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
.sign_up_async(&form.email, &form.password_1)
.sign_up(&form_data.email, &form_data.password_1)
.await
{
Ok(db::SignUpResult::UserAlreadyExists) => {
error_response(SignUpError::UserAlreadyExists, &form, user)
error_response(SignUpError::UserAlreadyExists, &form_data, user)
}
Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => {
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 split_port: Vec<&str> = host.split(':').collect();
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 || {
email::send_validation(
let email = form_data.email.clone();
match email::send_validation(
&url,
&email,
&token,
&config.smtp_relay_address,
&config.smtp_login,
&config.smtp_password,
)
})
.await?
.await
{
Ok(()) => Ok(HttpResponse::Found()
.insert_header((header::LOCATION, "/signup_check_email"))
.finish()),
Err(error) => {
error!("Email validation error: {}", error);
error_response(SignUpError::UnableSendEmail, &form, user)
}
}
}
Err(error) => {
error!("Signup database error: {}", error);
error_response(SignUpError::DatabaseError, &form, user)
}
}
}
#[get("/signup_check_email")]
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 {
Ok(()) => Ok(MessageTemplate {
user,
message: "An email has been sent, follow the link to validate your account.",
}
.into_response()),
Err(_) => {
// error!("Email validation error: {}", error); // TODO: log
error_response(SignUpError::UnableSendEmail, &form_data, user)
}
}
}
Err(_) => {
// error!("Signup database error: {}", error);
error_response(SignUpError::DatabaseError, &form_data, user)
}
}
}
#[get("/validation")]
#[debug_handler]
pub async fn sign_up_validation(
req: HttpRequest,
query: web::Query<HashMap<String, String>>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
let user = get_current_user(&req, connection.clone()).await;
match query.get("token") {
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
Query(query): Query<HashMap<String, String>>,
headers: HeaderMap,
) -> Result<(CookieJar, impl IntoResponse)> {
let mut jar = CookieJar::from_headers(&headers);
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) => {
match connection
.validation_async(
.validation(
token,
Duration::seconds(consts::VALIDATION_TOKEN_DURATION),
&client_ip,
@ -490,43 +369,39 @@ pub async fn sign_up_validation(
{
db::ValidationResult::Ok(token, user_id) => {
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
let user = match connection.load_user(user_id) {
Ok(user) => Some(user),
Err(error) => {
error!("Error retrieving user by id: {}", error);
None
}
};
let mut response = MessageTemplate {
jar = jar.add(cookie);
let user = connection.load_user(user_id).await?;
Ok((
jar,
MessageTemplate {
user,
message: "Email validation successful, your account has been created",
},
))
}
.to_response();
if let Err(error) = response.add_cookie(&cookie) {
error!("Unable to set cookie after validation: {}", error);
};
Ok(response)
}
db::ValidationResult::ValidationExpired => Ok(MessageTemplate {
db::ValidationResult::ValidationExpired => Ok((
jar,
MessageTemplate {
user,
message: "The validation has expired. Try to sign up again.",
}
.to_response()),
db::ValidationResult::UnknownUser => Ok(MessageTemplate {
message: "The validation has expired. Try to sign up again",
},
)),
db::ValidationResult::UnknownUser => Ok((
jar,
MessageTemplate {
user,
message: "Validation error.",
}
.to_response()),
message: "Validation error. Try to sign up again",
},
)),
}
}
None => Ok(MessageTemplate {
None => Ok((
jar,
MessageTemplate {
user,
message: &format!("No token provided"),
}
.to_response()),
message: "Validation error",
},
)),
}
}
@ -540,109 +415,89 @@ struct SignInFormTemplate {
message: String,
}
#[get("/signin")]
#[debug_handler]
pub async fn sign_in_get(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> impl Responder {
let user = get_current_user(&req, connection.clone()).await;
SignInFormTemplate {
Extension(user): Extension<Option<model::User>>,
) -> Result<impl IntoResponse> {
Ok(SignInFormTemplate {
user,
email: String::new(),
message: String::new(),
}
})
}
#[derive(Deserialize)]
#[derive(Deserialize, Debug)]
pub struct SignInFormData {
email: String,
password: String,
}
enum SignInError {
AccountNotValidated,
AuthenticationFailed,
}
#[post("/signin")]
#[debug_handler]
pub async fn sign_in_post(
req: HttpRequest,
form: web::Form<SignInFormData>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
fn error_response(
error: SignInError,
form: &web::Form<SignInFormData>,
user: Option<model::User>,
) -> 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);
ConnectInfo(addr): ConnectInfo<SocketAddr>,
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
headers: HeaderMap,
Form(form_data): Form<SignInFormData>,
) -> Result<(CookieJar, Response)> {
let jar = CookieJar::from_headers(&headers);
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(&headers, addr);
match connection
.sign_in_async(&form.email, &form.password, &client_ip, &client_user_agent)
.await
.sign_in(
&form_data.email,
&form_data.password,
&client_ip,
&client_user_agent,
)
.await?
{
Ok(db::SignInResult::AccountNotValidated) => {
error_response(SignInError::AccountNotValidated, &form, user)
db::SignInResult::AccountNotValidated => Ok((
jar,
SignInFormTemplate {
user,
email: form_data.email,
message: "This account must be validated first".to_string(),
}
Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => {
error_response(SignInError::AuthenticationFailed, &form, user)
.into_response(),
)),
db::SignInResult::UserNotFound | db::SignInResult::WrongPassword => Ok((
jar,
SignInFormTemplate {
user,
email: form_data.email,
message: "Wrong email or password".to_string(),
}
Ok(db::SignInResult::Ok(token, user_id)) => {
.into_response(),
)),
db::SignInResult::Ok(token, _user_id) => {
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
let mut response = HttpResponse::Found()
.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)
Ok((jar.add(cookie), Redirect::to("/").into_response()))
}
}
}
///// SIGN OUT /////
#[get("/signout")]
pub async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
let mut response = HttpResponse::Found()
.insert_header((header::LOCATION, "/"))
.finish();
if let Some(token_cookie) = req.cookie(consts::COOKIE_AUTH_TOKEN_NAME) {
if let Err(error) = connection.sign_out_async(token_cookie.value()).await {
error!("Unable to sign out: {}", error);
};
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",
#[debug_handler]
pub async fn sign_out(
State(connection): State<db::Connection>,
req: Request<Body>,
) -> Result<(CookieJar, Redirect)> {
let mut jar = CookieJar::from_headers(req.headers());
if let Some(token_cookie) = jar.get(consts::COOKIE_AUTH_TOKEN_NAME) {
let token = token_cookie.value().to_string();
jar = jar.remove(consts::COOKIE_AUTH_TOKEN_NAME);
connection.sign_out(&token).await?;
}
Ok((jar, Redirect::to("/")))
}
///// 404 /////
#[debug_handler]
pub async fn not_found() -> Result<impl IntoResponse> {
Ok(MessageWithoutUser {
message: "404: Not found",
})
}

View file

@ -1,38 +1,38 @@
use actix_web::{
http::{header, header::ContentType, StatusCode},
post, put, web, HttpMessage, HttpRequest, HttpResponse, Responder,
};
use log::{debug, error, info, log_enabled, Level};
use ron::de::from_bytes;
// use actix_web::{
// http::{header, header::ContentType, StatusCode},
// post, put, web, HttpMessage, HttpRequest, HttpResponse, Responder,
// };
// use log::{debug, error, info, log_enabled, Level};
// use ron::de::from_bytes;
use super::Result;
use crate::data::{asynchronous, db};
// use super::Result;
// use crate::data::db;
#[put("/ron-api/recipe/set-title")]
pub async fn set_recipe_title(
req: HttpRequest,
body: web::Bytes,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let ron_req: common::ron_api::SetRecipeTitle = from_bytes(&body)?;
connection
.set_recipe_title_async(ron_req.recipe_id, &ron_req.title)
.await?;
Ok(HttpResponse::Ok().finish())
}
// #[put("/ron-api/recipe/set-title")]
// pub async fn set_recipe_title(
// req: HttpRequest,
// body: web::Bytes,
// connection: web::Data<db::Connection>,
// ) -> Result<HttpResponse> {
// let ron_req: common::ron_api::SetRecipeTitle = from_bytes(&body)?;
// connection
// .set_recipe_title_async(ron_req.recipe_id, &ron_req.title)
// .await?;
// Ok(HttpResponse::Ok().finish())
// }
#[put("/ron-api/recipe/set-description")]
pub async fn set_recipe_description(
req: HttpRequest,
body: web::Bytes,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let ron_req: common::ron_api::SetRecipeDescription = from_bytes(&body)?;
connection
.set_recipe_description_async(ron_req.recipe_id, &ron_req.description)
.await?;
Ok(HttpResponse::Ok().finish())
}
// #[put("/ron-api/recipe/set-description")]
// pub async fn set_recipe_description(
// req: HttpRequest,
// body: web::Bytes,
// connection: web::Data<db::Connection>,
// ) -> Result<HttpResponse> {
// let ron_req: common::ron_api::SetRecipeDescription = from_bytes(&body)?;
// connection
// .set_recipe_description_async(ron_req.recipe_id, &ron_req.description)
// .await?;
// Ok(HttpResponse::Ok().finish())
// }
// #[put("/ron-api/recipe/add-image)]
// #[put("/ron-api/recipe/rm-photo")]

View file

@ -1,11 +1,20 @@
use log::error;
use std::net::SocketAddr;
pub fn unwrap_print_err<T, E>(r: Result<T, E>) -> T
where
E: std::fmt::Debug,
{
if let Err(ref error) = r {
error!("{:?}", error);
}
r.unwrap()
use axum::http::HeaderMap;
use crate::consts;
pub fn get_ip_and_user_agent(headers: &HeaderMap, remote_address: SocketAddr) -> (String, String) {
let ip = match headers.get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
Some(v) => v.to_str().unwrap_or_default().to_string(),
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)
}

View file

@ -2,7 +2,7 @@
{% block body_container %}
<div class="header-container">
<a class="title" href="/">~~ Recettes de cuisine ~~</a>
{% include "title.html" %}
{% match user %}
{% when Some with (user) %}

View file

@ -1,7 +1,6 @@
{% extends "base_with_header.html" %}
{% block main_container %}
{{ message|markdown }}
{{ message|markdown }}
<a href="/">Go to home</a>
{% endblock %}

View file

@ -1,6 +1,6 @@
{% extends "base.html" %}
{% block body_container %}
{% include "title.html" %}
{{ message|markdown }}
{% include "title.html" %}
{{ message|markdown }}
{% endblock %}

View file

@ -1 +1 @@
<h1><a href="/">~~ Recettes de cuisine ~~</a></h1>
<a class="title" href="/">~~ Recettes de cuisine ~~</a>

View file

@ -0,0 +1,2 @@
# It needs cargo-edit: https://crates.io/crates/cargo-edit .
cargo upgrade --dry-run --verbose

View file

@ -1,2 +1,2 @@
pub mod utils;
pub mod ron_api;
pub mod utils;

View file

@ -1,4 +1,3 @@
use ron::de::from_reader;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]

View file

@ -1,5 +1,5 @@
use regex::Regex;
use lazy_static::lazy_static;
use regex::Regex;
pub enum EmailValidation {
Ok,
@ -7,11 +7,18 @@ pub enum EmailValidation {
}
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 {
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 {
@ -20,5 +27,9 @@ pub enum 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
}
}

View file

@ -1,18 +1,20 @@
def main [host: string, destination: string, ssh_key: path] {
let ssh_args = [-i $ssh_key $host]
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] {
let args = $ssh_args ++ $command
print $"Executing: ssh ($args)"
ssh $args
ssh ...$args
}
def copy_ssh [source: string, destination: string] {
let args = $scp_args ++ [$source $"($host):($destination)"]
print $"Executing: scp ($args)"
scp $args
scp ...$args
}
cargo build --target $target --release
@ -25,4 +27,3 @@ def main [host: string, destination: string, ssh_key: path] {
invoke_ssh [sudo systemctl start recipes]
print "Deployment finished"
}

View file

@ -11,21 +11,29 @@ crate-type = ["cdylib"]
default = ["console_error_panic_hook"]
[dependencies]
common = {path = "../common"}
common = { path = "../common" }
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
# 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
# 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
# compared to the default allocator's ~10K. It is slower than the default
# allocator, however.
wee_alloc = {version = "0.4", optional = true}
wee_alloc = { version = "0.4", optional = true }
# [dev-dependencies]
# wasm-bindgen-test = "0.3"