rustfmt
This commit is contained in:
parent
cbe276fc06
commit
0a1631e66c
13 changed files with 766 additions and 381 deletions
|
|
@ -5,12 +5,20 @@ What is build here:
|
||||||
- Compile the SASS file to CSS file.
|
- Compile the SASS file to CSS file.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use std::{ env, process::{ Command, Output }, path::Path };
|
use std::{
|
||||||
|
env,
|
||||||
|
path::Path,
|
||||||
|
process::{Command, Output},
|
||||||
|
};
|
||||||
|
|
||||||
fn exists_in_path<P>(filename: P) -> bool
|
fn exists_in_path<P>(filename: P) -> bool
|
||||||
where P: AsRef<Path> {
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
{
|
||||||
for path in env::split_paths(&env::var_os("PATH").unwrap()) {
|
for path in env::split_paths(&env::var_os("PATH").unwrap()) {
|
||||||
if path.join(&filename).is_file() { return true; }
|
if path.join(&filename).is_file() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
@ -26,8 +34,7 @@ fn main() {
|
||||||
.expect("Unable to compile SASS file, install SASS, see https://sass-lang.com/")
|
.expect("Unable to compile SASS file, install SASS, see https://sass-lang.com/")
|
||||||
}
|
}
|
||||||
|
|
||||||
let output =
|
let output = if exists_in_path("sass.bat") {
|
||||||
if exists_in_path("sass.bat") {
|
|
||||||
run_sass(Command::new("cmd").args(&["/C", "sass.bat"]))
|
run_sass(Command::new("cmd").args(&["/C", "sass.bat"]))
|
||||||
} else {
|
} else {
|
||||||
run_sass(&mut Command::new("sass"))
|
run_sass(&mut Command::new("sass"))
|
||||||
|
|
@ -35,7 +42,8 @@ fn main() {
|
||||||
|
|
||||||
if !output.status.success() {
|
if !output.status.success() {
|
||||||
// SASS will put the error in the file.
|
// SASS will put the error in the file.
|
||||||
let error = std::fs::read_to_string("./static/style.css").expect("unable to read style.css");
|
let error =
|
||||||
|
std::fs::read_to_string("./static/style.css").expect("unable to read style.css");
|
||||||
panic!("{}", error);
|
panic!("{}", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -24,9 +24,10 @@ impl fmt::Debug for Config {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load() -> Config {
|
pub fn load() -> Config {
|
||||||
let f = File::open(consts::FILE_CONF).unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
|
let f = File::open(consts::FILE_CONF)
|
||||||
|
.unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
|
||||||
match from_reader(f) {
|
match from_reader(f) {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => panic!("Failed to load config: {}", e)
|
Err(e) => panic!("Failed to load config: {}", e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
pub const FILE_CONF: &str = "conf.ron";
|
pub const FILE_CONF: &str = "conf.ron";
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
use actix_web::{error::BlockingError, web};
|
||||||
use chrono::{prelude::*, Duration};
|
use chrono::{prelude::*, Duration};
|
||||||
use actix_web::{web, error::BlockingError};
|
|
||||||
|
|
||||||
use super::db::*;
|
use super::db::*;
|
||||||
use crate::model;
|
use crate::model;
|
||||||
|
|
@ -42,7 +42,9 @@ impl DBAsyncError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn combine_errors<T>(error: std::result::Result<std::result::Result<T, DBAsyncError>, BlockingError>) -> Result<T> {
|
fn combine_errors<T>(
|
||||||
|
error: std::result::Result<std::result::Result<T, DBAsyncError>, BlockingError>,
|
||||||
|
) -> Result<T> {
|
||||||
error?
|
error?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -51,71 +53,144 @@ type Result<T> = std::result::Result<T, DBAsyncError>;
|
||||||
impl Connection {
|
impl Connection {
|
||||||
pub async fn get_all_recipe_titles_async(&self) -> Result<Vec<(i64, String)>> {
|
pub async fn get_all_recipe_titles_async(&self) -> Result<Vec<(i64, String)>> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
web::block(move || { self_copy.get_all_recipe_titles().unwrap_or_default() }).await.map_err(DBAsyncError::from)
|
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> {
|
pub async fn get_recipe_async(&self, id: i64) -> Result<model::Recipe> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
combine_errors(web::block(move || { self_copy.get_recipe(id).map_err(DBAsyncError::from) }).await)
|
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<User> {
|
pub async fn load_user_async(&self, user_id: i64) -> Result<User> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
combine_errors(web::block(move || { self_copy.load_user(user_id).map_err(DBAsyncError::from) }).await)
|
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> {
|
pub async fn sign_up_async(&self, email: &str, password: &str) -> Result<SignUpResult> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
let email_copy = email.to_string();
|
let email_copy = email.to_string();
|
||||||
let password_copy = password.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)
|
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> {
|
pub async fn validation_async(
|
||||||
|
&self,
|
||||||
|
token: &str,
|
||||||
|
validation_time: Duration,
|
||||||
|
ip: &str,
|
||||||
|
user_agent: &str,
|
||||||
|
) -> Result<ValidationResult> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
let token_copy = token.to_string();
|
let token_copy = token.to_string();
|
||||||
let ip_copy = ip.to_string();
|
let ip_copy = ip.to_string();
|
||||||
let user_agent_copy = user_agent.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)
|
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> {
|
pub async fn sign_in_async(
|
||||||
|
&self,
|
||||||
|
email: &str,
|
||||||
|
password: &str,
|
||||||
|
ip: &str,
|
||||||
|
user_agent: &str,
|
||||||
|
) -> Result<SignInResult> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
let email_copy = email.to_string();
|
let email_copy = email.to_string();
|
||||||
let password_copy = password.to_string();
|
let password_copy = password.to_string();
|
||||||
let ip_copy = ip.to_string();
|
let ip_copy = ip.to_string();
|
||||||
let user_agent_copy = user_agent.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)
|
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> {
|
pub async fn authentication_async(
|
||||||
|
&self,
|
||||||
|
token: &str,
|
||||||
|
ip: &str,
|
||||||
|
user_agent: &str,
|
||||||
|
) -> Result<AuthenticationResult> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
let token_copy = token.to_string();
|
let token_copy = token.to_string();
|
||||||
let ip_copy = ip.to_string();
|
let ip_copy = ip.to_string();
|
||||||
let user_agent_copy = user_agent.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)
|
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<()> {
|
pub async fn sign_out_async(&self, token: &str) -> Result<()> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
let token_copy = token.to_string();
|
let token_copy = token.to_string();
|
||||||
combine_errors(web::block(move || { self_copy.sign_out(&token_copy).map_err(DBAsyncError::from) }).await)
|
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> {
|
pub async fn create_recipe_async(&self, user_id: i64) -> Result<i64> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
combine_errors(web::block(move || { self_copy.create_recipe(user_id).map_err(DBAsyncError::from) }).await)
|
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<()> {
|
pub async fn set_recipe_title_async(&self, recipe_id: i64, title: &str) -> Result<()> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
let title_copy = title.to_string();
|
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)
|
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<()> {
|
pub async fn set_recipe_description_async(
|
||||||
|
&self,
|
||||||
|
recipe_id: i64,
|
||||||
|
description: &str,
|
||||||
|
) -> Result<()> {
|
||||||
let self_copy = self.clone();
|
let self_copy = self.clone();
|
||||||
let description_copy = description.to_string();
|
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)
|
combine_errors(
|
||||||
|
web::block(move || {
|
||||||
|
self_copy
|
||||||
|
.set_recipe_description(recipe_id, &description_copy)
|
||||||
|
.map_err(DBAsyncError::from)
|
||||||
|
})
|
||||||
|
.await,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,16 +1,21 @@
|
||||||
use std::{fmt, fs::{self, File}, path::Path, io::Read};
|
use std::{
|
||||||
|
fmt,
|
||||||
|
fs::{self, File},
|
||||||
|
io::Read,
|
||||||
|
path::Path,
|
||||||
|
};
|
||||||
|
|
||||||
use itertools::Itertools;
|
|
||||||
use chrono::{prelude::*, Duration};
|
use chrono::{prelude::*, Duration};
|
||||||
use rusqlite::{named_params, OptionalExtension, params, Params};
|
use itertools::Itertools;
|
||||||
use r2d2::{Pool, PooledConnection};
|
use r2d2::{Pool, PooledConnection};
|
||||||
use r2d2_sqlite::SqliteConnectionManager;
|
use r2d2_sqlite::SqliteConnectionManager;
|
||||||
use rand::distributions::{Alphanumeric, DistString};
|
use rand::distributions::{Alphanumeric, DistString};
|
||||||
|
use rusqlite::{named_params, params, OptionalExtension, Params};
|
||||||
|
|
||||||
use crate::{consts, user};
|
|
||||||
use crate::hash::{hash, verify_password};
|
use crate::hash::{hash, verify_password};
|
||||||
use crate::model;
|
use crate::model;
|
||||||
use crate::user::*;
|
use crate::user::*;
|
||||||
|
use crate::{consts, user};
|
||||||
|
|
||||||
const CURRENT_DB_VERSION: u32 = 1;
|
const CURRENT_DB_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
|
@ -79,7 +84,7 @@ pub enum AuthenticationResult {
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Connection {
|
pub struct Connection {
|
||||||
pool: Pool<SqliteConnectionManager>
|
pool: Pool<SqliteConnectionManager>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Connection {
|
impl Connection {
|
||||||
|
|
@ -129,10 +134,16 @@ impl Connection {
|
||||||
match tx.query_row(
|
match tx.query_row(
|
||||||
"SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",
|
"SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",
|
||||||
[],
|
[],
|
||||||
|row| row.get::<usize, String>(0)
|
|row| row.get::<usize, String>(0),
|
||||||
) {
|
) {
|
||||||
Ok(_) => tx.query_row("SELECT [version] FROM [Version] ORDER BY [id] DESC", [], |row| row.get(0)).unwrap_or_default(),
|
Ok(_) => tx
|
||||||
Err(_) => 0
|
.query_row(
|
||||||
|
"SELECT [version] FROM [Version] ORDER BY [id] DESC",
|
||||||
|
[],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
Err(_) => 0,
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -153,7 +164,12 @@ impl Connection {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_version(to_version: u32, tx: &rusqlite::Transaction) -> Result<()> {
|
fn update_version(to_version: u32, tx: &rusqlite::Transaction) -> Result<()> {
|
||||||
tx.execute("INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", [to_version]).map(|_| ()).map_err(DBError::from)
|
tx.execute(
|
||||||
|
"INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))",
|
||||||
|
[to_version],
|
||||||
|
)
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(DBError::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ok(updated: bool) -> Result<bool> {
|
fn ok(updated: bool) -> Result<bool> {
|
||||||
|
|
@ -173,11 +189,9 @@ impl Connection {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Version 1 doesn't exist yet.
|
// Version 1 doesn't exist yet.
|
||||||
2 =>
|
2 => ok(false),
|
||||||
ok(false),
|
|
||||||
|
|
||||||
v =>
|
v => Err(DBError::UnsupportedVersion(v)),
|
||||||
Err(DBError::UnsupportedVersion(v)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -186,10 +200,9 @@ impl Connection {
|
||||||
|
|
||||||
let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;
|
let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;
|
||||||
|
|
||||||
let titles: std::result::Result<Vec<(i64, String)>, rusqlite::Error> =
|
let titles: std::result::Result<Vec<(i64, String)>, rusqlite::Error> = stmt
|
||||||
stmt.query_map([], |row| {
|
.query_map([], |row| Ok((row.get("id")?, row.get("title")?)))?
|
||||||
Ok((row.get("id")?, row.get("title")?))
|
.collect();
|
||||||
})?.collect();
|
|
||||||
|
|
||||||
titles.map_err(DBError::from)
|
titles.map_err(DBError::from)
|
||||||
}
|
}
|
||||||
|
|
@ -207,9 +220,18 @@ impl Connection {
|
||||||
|
|
||||||
pub fn get_recipe(&self, id: i64) -> Result<model::Recipe> {
|
pub fn get_recipe(&self, id: i64) -> Result<model::Recipe> {
|
||||||
let con = self.get()?;
|
let con = self.get()?;
|
||||||
con.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| {
|
con.query_row(
|
||||||
Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?))
|
"SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1",
|
||||||
}).map_err(DBError::from)
|
[id],
|
||||||
|
|row| {
|
||||||
|
Ok(model::Recipe::new(
|
||||||
|
row.get("id")?,
|
||||||
|
row.get("title")?,
|
||||||
|
row.get("description")?,
|
||||||
|
))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(DBError::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_user_login_info(&self, token: &str) -> Result<UserLoginInfo> {
|
pub fn get_user_login_info(&self, token: &str) -> Result<UserLoginInfo> {
|
||||||
|
|
@ -225,116 +247,185 @@ impl Connection {
|
||||||
|
|
||||||
pub fn load_user(&self, user_id: i64) -> Result<User> {
|
pub fn load_user(&self, user_id: i64) -> Result<User> {
|
||||||
let con = self.get()?;
|
let con = self.get()?;
|
||||||
con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| {
|
con.query_row(
|
||||||
|
"SELECT [email] FROM [User] WHERE [id] = ?1",
|
||||||
|
[user_id],
|
||||||
|
|r| {
|
||||||
Ok(User {
|
Ok(User {
|
||||||
email: r.get("email")?,
|
email: r.get("email")?,
|
||||||
})
|
})
|
||||||
}).map_err(DBError::from)
|
},
|
||||||
|
)
|
||||||
|
.map_err(DBError::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sign_up(&self, email: &str, password: &str) -> Result<SignUpResult> {
|
pub fn sign_up(&self, email: &str, password: &str) -> Result<SignUpResult> {
|
||||||
self.sign_up_with_given_time(email, password, Utc::now())
|
self.sign_up_with_given_time(email, password, Utc::now())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sign_up_with_given_time(&self, email: &str, password: &str, datetime: DateTime<Utc>) -> Result<SignUpResult> {
|
fn sign_up_with_given_time(
|
||||||
|
&self,
|
||||||
|
email: &str,
|
||||||
|
password: &str,
|
||||||
|
datetime: DateTime<Utc>,
|
||||||
|
) -> Result<SignUpResult> {
|
||||||
let mut con = self.get()?;
|
let mut con = self.get()?;
|
||||||
let tx = con.transaction()?;
|
let tx = con.transaction()?;
|
||||||
let token =
|
let token = match tx
|
||||||
match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {
|
.query_row(
|
||||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, Option<String>>("validation_token")?))
|
"SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1",
|
||||||
}).optional()? {
|
[email],
|
||||||
|
|r| {
|
||||||
|
Ok((
|
||||||
|
r.get::<&str, i64>("id")?,
|
||||||
|
r.get::<&str, Option<String>>("validation_token")?,
|
||||||
|
))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
{
|
||||||
Some((id, validation_token)) => {
|
Some((id, validation_token)) => {
|
||||||
if validation_token.is_none() {
|
if validation_token.is_none() {
|
||||||
return Ok(SignUpResult::UserAlreadyExists)
|
return Ok(SignUpResult::UserAlreadyExists);
|
||||||
}
|
}
|
||||||
let token = generate_token();
|
let token = generate_token();
|
||||||
let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;
|
let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;
|
||||||
tx.execute("UPDATE [User] SET [validation_token] = ?2, [creation_datetime] = ?3, [password] = ?4 WHERE [id] = ?1", params![id, token, datetime, hashed_password])?;
|
tx.execute("UPDATE [User] SET [validation_token] = ?2, [creation_datetime] = ?3, [password] = ?4 WHERE [id] = ?1", params![id, token, datetime, hashed_password])?;
|
||||||
token
|
token
|
||||||
},
|
}
|
||||||
None => {
|
None => {
|
||||||
let token = generate_token();
|
let token = generate_token();
|
||||||
let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;
|
let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;
|
||||||
tx.execute("INSERT INTO [User] ([email], [validation_token], [creation_datetime], [password]) VALUES (?1, ?2, ?3, ?4)", params![email, token, datetime, hashed_password])?;
|
tx.execute("INSERT INTO [User] ([email], [validation_token], [creation_datetime], [password]) VALUES (?1, ?2, ?3, ?4)", params![email, token, datetime, hashed_password])?;
|
||||||
token
|
token
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
Ok(SignUpResult::UserCreatedWaitingForValidation(token))
|
Ok(SignUpResult::UserCreatedWaitingForValidation(token))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn validation(&self, token: &str, validation_time: Duration, ip: &str, user_agent: &str) -> Result<ValidationResult> {
|
pub fn validation(
|
||||||
|
&self,
|
||||||
|
token: &str,
|
||||||
|
validation_time: Duration,
|
||||||
|
ip: &str,
|
||||||
|
user_agent: &str,
|
||||||
|
) -> Result<ValidationResult> {
|
||||||
let mut con = self.get()?;
|
let mut con = self.get()?;
|
||||||
let tx = con.transaction()?;
|
let tx = con.transaction()?;
|
||||||
let user_id =
|
let user_id = match tx
|
||||||
match tx.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token], |r| {
|
.query_row(
|
||||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, DateTime<Utc>>("creation_datetime")?))
|
"SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1",
|
||||||
}).optional()? {
|
[token],
|
||||||
|
|r| {
|
||||||
|
Ok((
|
||||||
|
r.get::<&str, i64>("id")?,
|
||||||
|
r.get::<&str, DateTime<Utc>>("creation_datetime")?,
|
||||||
|
))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
{
|
||||||
Some((id, creation_datetime)) => {
|
Some((id, creation_datetime)) => {
|
||||||
if Utc::now() - creation_datetime > validation_time {
|
if Utc::now() - creation_datetime > validation_time {
|
||||||
return Ok(ValidationResult::ValidationExpired)
|
return Ok(ValidationResult::ValidationExpired);
|
||||||
}
|
}
|
||||||
tx.execute("UPDATE [User] SET [validation_token] = NULL WHERE [id] = ?1", [id])?;
|
tx.execute(
|
||||||
|
"UPDATE [User] SET [validation_token] = NULL WHERE [id] = ?1",
|
||||||
|
[id],
|
||||||
|
)?;
|
||||||
id
|
id
|
||||||
},
|
}
|
||||||
None => {
|
None => return Ok(ValidationResult::UnknownUser),
|
||||||
return Ok(ValidationResult::UnknownUser)
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
let token = Connection::create_login_token(&tx, user_id, ip, user_agent)?;
|
let token = Connection::create_login_token(&tx, user_id, ip, user_agent)?;
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
Ok(ValidationResult::Ok(token, user_id))
|
Ok(ValidationResult::Ok(token, user_id))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sign_in(&self, email: &str, password: &str, ip: &str, user_agent: &str) -> Result<SignInResult> {
|
pub fn sign_in(
|
||||||
|
&self,
|
||||||
|
email: &str,
|
||||||
|
password: &str,
|
||||||
|
ip: &str,
|
||||||
|
user_agent: &str,
|
||||||
|
) -> Result<SignInResult> {
|
||||||
let mut con = self.get()?;
|
let mut con = self.get()?;
|
||||||
let tx = con.transaction()?;
|
let tx = con.transaction()?;
|
||||||
match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {
|
match tx
|
||||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option<String>>("validation_token")?))
|
.query_row(
|
||||||
}).optional()? {
|
"SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1",
|
||||||
|
[email],
|
||||||
|
|r| {
|
||||||
|
Ok((
|
||||||
|
r.get::<&str, i64>("id")?,
|
||||||
|
r.get::<&str, String>("password")?,
|
||||||
|
r.get::<&str, Option<String>>("validation_token")?,
|
||||||
|
))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
{
|
||||||
Some((id, stored_password, validation_token)) => {
|
Some((id, stored_password, validation_token)) => {
|
||||||
if validation_token.is_some() {
|
if validation_token.is_some() {
|
||||||
Ok(SignInResult::AccountNotValidated)
|
Ok(SignInResult::AccountNotValidated)
|
||||||
} else if verify_password(password, &stored_password).map_err(DBError::from_dyn_error)? {
|
} else if verify_password(password, &stored_password)
|
||||||
|
.map_err(DBError::from_dyn_error)?
|
||||||
|
{
|
||||||
let token = Connection::create_login_token(&tx, id, ip, user_agent)?;
|
let token = Connection::create_login_token(&tx, id, ip, user_agent)?;
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
Ok(SignInResult::Ok(token, id))
|
Ok(SignInResult::Ok(token, id))
|
||||||
} else {
|
} else {
|
||||||
Ok(SignInResult::WrongPassword)
|
Ok(SignInResult::WrongPassword)
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
None => {
|
None => Ok(SignInResult::UserNotFound),
|
||||||
Ok(SignInResult::UserNotFound)
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn authentication(&self, token: &str, ip: &str, user_agent: &str) -> Result<AuthenticationResult> {
|
pub fn authentication(
|
||||||
|
&self,
|
||||||
|
token: &str,
|
||||||
|
ip: &str,
|
||||||
|
user_agent: &str,
|
||||||
|
) -> Result<AuthenticationResult> {
|
||||||
let mut con = self.get()?;
|
let mut con = self.get()?;
|
||||||
let tx = con.transaction()?;
|
let tx = con.transaction()?;
|
||||||
match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {
|
match tx
|
||||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, i64>("user_id")?))
|
.query_row(
|
||||||
}).optional()? {
|
"SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1",
|
||||||
|
[token],
|
||||||
|
|r| Ok((r.get::<&str, i64>("id")?, r.get::<&str, i64>("user_id")?)),
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
{
|
||||||
Some((login_id, user_id)) => {
|
Some((login_id, user_id)) => {
|
||||||
tx.execute("UPDATE [UserLoginToken] SET [last_login_datetime] = ?2, [ip] = ?3, [user_agent] = ?4 WHERE [id] = ?1", params![login_id, Utc::now(), ip, user_agent])?;
|
tx.execute("UPDATE [UserLoginToken] SET [last_login_datetime] = ?2, [ip] = ?3, [user_agent] = ?4 WHERE [id] = ?1", params![login_id, Utc::now(), ip, user_agent])?;
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
Ok(AuthenticationResult::Ok(user_id))
|
Ok(AuthenticationResult::Ok(user_id))
|
||||||
},
|
}
|
||||||
None =>
|
None => Ok(AuthenticationResult::NotValidToken),
|
||||||
Ok(AuthenticationResult::NotValidToken)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sign_out(&self, token: &str) -> Result<()> {
|
pub fn sign_out(&self, token: &str) -> Result<()> {
|
||||||
let mut con = self.get()?;
|
let mut con = self.get()?;
|
||||||
let tx = con.transaction()?;
|
let tx = con.transaction()?;
|
||||||
match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {
|
match tx
|
||||||
Ok(r.get::<&str, i64>("id")?)
|
.query_row(
|
||||||
}).optional()? {
|
"SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1",
|
||||||
|
[token],
|
||||||
|
|r| Ok(r.get::<&str, i64>("id")?),
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
{
|
||||||
Some(login_id) => {
|
Some(login_id) => {
|
||||||
tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?;
|
tx.execute(
|
||||||
|
"DELETE FROM [UserLoginToken] WHERE [id] = ?1",
|
||||||
|
params![login_id],
|
||||||
|
)?;
|
||||||
tx.commit()?
|
tx.commit()?
|
||||||
},
|
}
|
||||||
None => (),
|
None => (),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
@ -364,12 +455,22 @@ impl Connection {
|
||||||
|
|
||||||
pub fn set_recipe_title(&self, recipe_id: i64, title: &str) -> Result<()> {
|
pub fn set_recipe_title(&self, recipe_id: i64, title: &str) -> Result<()> {
|
||||||
let con = self.get()?;
|
let con = self.get()?;
|
||||||
con.execute("UPDATE [Recipe] SET [title] = ?2 WHERE [id] = ?1", params![recipe_id, title]).map(|_n| ()).map_err(DBError::from)
|
con.execute(
|
||||||
|
"UPDATE [Recipe] SET [title] = ?2 WHERE [id] = ?1",
|
||||||
|
params![recipe_id, title],
|
||||||
|
)
|
||||||
|
.map(|_n| ())
|
||||||
|
.map_err(DBError::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_recipe_description(&self, recipe_id: i64, description: &str) -> Result<()> {
|
pub fn set_recipe_description(&self, recipe_id: i64, description: &str) -> Result<()> {
|
||||||
let con = self.get()?;
|
let con = self.get()?;
|
||||||
con.execute("UPDATE [Recipe] SET [description] = ?2 WHERE [id] = ?1", params![recipe_id, description]).map(|_n| ()).map_err(DBError::from)
|
con.execute(
|
||||||
|
"UPDATE [Recipe] SET [description] = ?2 WHERE [id] = ?1",
|
||||||
|
params![recipe_id, description],
|
||||||
|
)
|
||||||
|
.map(|_n| ())
|
||||||
|
.map_err(DBError::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute a given SQL file.
|
/// Execute a given SQL file.
|
||||||
|
|
@ -387,7 +488,12 @@ impl Connection {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return the token.
|
// Return the token.
|
||||||
fn create_login_token(tx: &rusqlite::Transaction, user_id: i64, ip: &str, user_agent: &str) -> Result<String> {
|
fn create_login_token(
|
||||||
|
tx: &rusqlite::Transaction,
|
||||||
|
user_id: i64,
|
||||||
|
ip: &str,
|
||||||
|
user_agent: &str,
|
||||||
|
) -> Result<String> {
|
||||||
let token = generate_token();
|
let token = generate_token();
|
||||||
tx.execute("INSERT INTO [UserLoginToken] ([user_id], [last_login_datetime], [token], [ip], [user_agent]) VALUES (?1, ?2, ?3, ?4, ?5)", params![user_id, Utc::now(), token, ip, user_agent])?;
|
tx.execute("INSERT INTO [UserLoginToken] ([user_id], [last_login_datetime], [token], [ip], [user_agent]) VALUES (?1, ?2, ?3, ?4, ?5)", params![user_id, Utc::now(), token, ip, user_agent])?;
|
||||||
Ok(token)
|
Ok(token)
|
||||||
|
|
@ -395,9 +501,21 @@ impl Connection {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_sql_file<P: AsRef<Path> + fmt::Display>(sql_file: P) -> Result<String> {
|
fn load_sql_file<P: AsRef<Path> + fmt::Display>(sql_file: P) -> Result<String> {
|
||||||
let mut file = File::open(&sql_file).map_err(|err| DBError::Other(format!("Cannot open SQL file ({}): {}", &sql_file, err.to_string())))?;
|
let mut file = File::open(&sql_file).map_err(|err| {
|
||||||
|
DBError::Other(format!(
|
||||||
|
"Cannot open SQL file ({}): {}",
|
||||||
|
&sql_file,
|
||||||
|
err.to_string()
|
||||||
|
))
|
||||||
|
})?;
|
||||||
let mut sql = String::new();
|
let mut sql = String::new();
|
||||||
file.read_to_string(&mut sql).map_err(|err| DBError::Other(format!("Cannot read SQL file ({}) : {}", &sql_file, err.to_string())))?;
|
file.read_to_string(&mut sql).map_err(|err| {
|
||||||
|
DBError::Other(format!(
|
||||||
|
"Cannot read SQL file ({}) : {}",
|
||||||
|
&sql_file,
|
||||||
|
err.to_string()
|
||||||
|
))
|
||||||
|
})?;
|
||||||
Ok(sql)
|
Ok(sql)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -408,7 +526,7 @@ fn generate_token() -> String {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rusqlite::{Error, ErrorCode, ffi, types::Value};
|
use rusqlite::{ffi, types::Value, Error, ErrorCode};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn sign_up() -> Result<()> {
|
fn sign_up() -> Result<()> {
|
||||||
|
|
@ -484,12 +602,16 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn sign_up_then_send_validation_at_time() -> Result<()> {
|
fn sign_up_then_send_validation_at_time() -> Result<()> {
|
||||||
let connection = Connection::new_in_memory()?;
|
let connection = Connection::new_in_memory()?;
|
||||||
let validation_token =
|
let validation_token = match connection.sign_up("paul@atreides.com", "12345")? {
|
||||||
match connection.sign_up("paul@atreides.com", "12345")? {
|
|
||||||
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {
|
match connection.validation(
|
||||||
|
&validation_token,
|
||||||
|
Duration::hours(1),
|
||||||
|
"127.0.0.1",
|
||||||
|
"Mozilla/5.0",
|
||||||
|
)? {
|
||||||
ValidationResult::Ok(_, _) => (), // Nominal case.
|
ValidationResult::Ok(_, _) => (), // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
}
|
}
|
||||||
|
|
@ -499,12 +621,20 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn sign_up_then_send_validation_too_late() -> Result<()> {
|
fn sign_up_then_send_validation_too_late() -> Result<()> {
|
||||||
let connection = Connection::new_in_memory()?;
|
let connection = Connection::new_in_memory()?;
|
||||||
let validation_token =
|
let validation_token = match connection.sign_up_with_given_time(
|
||||||
match connection.sign_up_with_given_time("paul@atreides.com", "12345", Utc::now() - Duration::days(1))? {
|
"paul@atreides.com",
|
||||||
|
"12345",
|
||||||
|
Utc::now() - Duration::days(1),
|
||||||
|
)? {
|
||||||
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {
|
match connection.validation(
|
||||||
|
&validation_token,
|
||||||
|
Duration::hours(1),
|
||||||
|
"127.0.0.1",
|
||||||
|
"Mozilla/5.0",
|
||||||
|
)? {
|
||||||
ValidationResult::ValidationExpired => (), // Nominal case.
|
ValidationResult::ValidationExpired => (), // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
}
|
}
|
||||||
|
|
@ -514,13 +644,17 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn sign_up_then_send_validation_with_bad_token() -> Result<()> {
|
fn sign_up_then_send_validation_with_bad_token() -> Result<()> {
|
||||||
let connection = Connection::new_in_memory()?;
|
let connection = Connection::new_in_memory()?;
|
||||||
let _validation_token =
|
let _validation_token = match connection.sign_up("paul@atreides.com", "12345")? {
|
||||||
match connection.sign_up("paul@atreides.com", "12345")? {
|
|
||||||
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
let random_token = generate_token();
|
let random_token = generate_token();
|
||||||
match connection.validation(&random_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {
|
match connection.validation(
|
||||||
|
&random_token,
|
||||||
|
Duration::hours(1),
|
||||||
|
"127.0.0.1",
|
||||||
|
"Mozilla/5.0",
|
||||||
|
)? {
|
||||||
ValidationResult::UnknownUser => (), // Nominal case.
|
ValidationResult::UnknownUser => (), // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
}
|
}
|
||||||
|
|
@ -535,14 +669,18 @@ mod tests {
|
||||||
let password = "12345";
|
let password = "12345";
|
||||||
|
|
||||||
// Sign up.
|
// Sign up.
|
||||||
let validation_token =
|
let validation_token = match connection.sign_up(email, password)? {
|
||||||
match connection.sign_up(email, password)? {
|
|
||||||
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Validation.
|
// Validation.
|
||||||
match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {
|
match connection.validation(
|
||||||
|
&validation_token,
|
||||||
|
Duration::hours(1),
|
||||||
|
"127.0.0.1",
|
||||||
|
"Mozilla/5.0",
|
||||||
|
)? {
|
||||||
ValidationResult::Ok(_, _) => (),
|
ValidationResult::Ok(_, _) => (),
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
|
|
@ -564,14 +702,18 @@ mod tests {
|
||||||
let password = "12345";
|
let password = "12345";
|
||||||
|
|
||||||
// Sign up.
|
// Sign up.
|
||||||
let validation_token =
|
let validation_token = match connection.sign_up(email, password)? {
|
||||||
match connection.sign_up(email, password)? {
|
|
||||||
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Validation.
|
// Validation.
|
||||||
let (authentication_token, user_id) = match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla")? {
|
let (authentication_token, user_id) = match connection.validation(
|
||||||
|
&validation_token,
|
||||||
|
Duration::hours(1),
|
||||||
|
"127.0.0.1",
|
||||||
|
"Mozilla",
|
||||||
|
)? {
|
||||||
ValidationResult::Ok(token, user_id) => (token, user_id),
|
ValidationResult::Ok(token, user_id) => (token, user_id),
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
|
|
@ -604,15 +746,18 @@ mod tests {
|
||||||
let password = "12345";
|
let password = "12345";
|
||||||
|
|
||||||
// Sign up.
|
// Sign up.
|
||||||
let validation_token =
|
let validation_token = match connection.sign_up(email, password)? {
|
||||||
match connection.sign_up(email, password)? {
|
|
||||||
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Validation.
|
// Validation.
|
||||||
let (authentication_token_1, user_id_1) =
|
let (authentication_token_1, user_id_1) = match connection.validation(
|
||||||
match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla")? {
|
&validation_token,
|
||||||
|
Duration::hours(1),
|
||||||
|
"127.0.0.1",
|
||||||
|
"Mozilla",
|
||||||
|
)? {
|
||||||
ValidationResult::Ok(token, user_id) => (token, user_id),
|
ValidationResult::Ok(token, user_id) => (token, user_id),
|
||||||
other => panic!("{:?}", other),
|
other => panic!("{:?}", other),
|
||||||
};
|
};
|
||||||
|
|
@ -644,7 +789,6 @@ mod tests {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn create_a_new_recipe_then_update_its_title() -> Result<()> {
|
fn create_a_new_recipe_then_update_its_title() -> Result<()> {
|
||||||
let connection = Connection::new_in_memory()?;
|
let connection = Connection::new_in_memory()?;
|
||||||
|
|
@ -662,8 +806,17 @@ mod tests {
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
match connection.create_recipe(2) {
|
match connection.create_recipe(2) {
|
||||||
Err(DBError::SqliteError(Error::SqliteFailure(ffi::Error { code: ErrorCode::ConstraintViolation, extended_code: _ }, Some(_)))) => (), // Nominal case.
|
Err(DBError::SqliteError(Error::SqliteFailure(
|
||||||
other => panic!("Creating a recipe with an inexistant user must fail: {:?}", other),
|
ffi::Error {
|
||||||
|
code: ErrorCode::ConstraintViolation,
|
||||||
|
extended_code: _,
|
||||||
|
},
|
||||||
|
Some(_),
|
||||||
|
))) => (), // Nominal case.
|
||||||
|
other => panic!(
|
||||||
|
"Creating a recipe with an inexistant user must fail: {:?}",
|
||||||
|
other
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
let recipe_id = connection.create_recipe(1)?;
|
let recipe_id = connection.create_recipe(1)?;
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
use std::time::Duration;
|
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
|
use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::consts;
|
use crate::consts;
|
||||||
|
|
||||||
|
|
@ -29,17 +29,29 @@ impl From<lettre::error::Error> for Error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send_validation(site_url: &str, email: &str, token: &str, smtp_login: &str, smtp_password: &str) -> Result<(), Error> {
|
pub fn send_validation(
|
||||||
|
site_url: &str,
|
||||||
|
email: &str,
|
||||||
|
token: &str,
|
||||||
|
smtp_login: &str,
|
||||||
|
smtp_password: &str,
|
||||||
|
) -> Result<(), Error> {
|
||||||
let email = Message::builder()
|
let email = Message::builder()
|
||||||
.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!("Follow this link to confirm your inscription: {}/validation?token={}", site_url, token))?;
|
.body(format!(
|
||||||
|
"Follow this link to confirm your inscription: {}/validation?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")?.credentials(credentials).timeout(Some(consts::SEND_EMAIL_TIMEOUT)).build();
|
let mailer = SmtpTransport::relay("mail.gandi.net")?
|
||||||
|
.credentials(credentials)
|
||||||
|
.timeout(Some(consts::SEND_EMAIL_TIMEOUT))
|
||||||
|
.build();
|
||||||
|
|
||||||
if let Err(error) = mailer.send(&email) {
|
if let Err(error) = mailer.send(&email) {
|
||||||
eprintln!("Error when sending E-mail:\n{:?}", &error);
|
eprintln!("Error when sending E-mail:\n{:?}", &error);
|
||||||
|
|
|
||||||
|
|
@ -1,23 +1,28 @@
|
||||||
use std::{string::String};
|
use std::string::String;
|
||||||
|
|
||||||
use argon2::{
|
use argon2::{
|
||||||
password_hash::{
|
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||||
rand_core::OsRng,
|
Argon2,
|
||||||
PasswordHash, PasswordHasher, PasswordVerifier, SaltString
|
|
||||||
},
|
|
||||||
Argon2
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn hash(password: &str) -> Result<String, Box<dyn std::error::Error>> {
|
pub fn hash(password: &str) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
let salt = SaltString::generate(&mut OsRng);
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
let argon2 = Argon2::default();
|
let argon2 = Argon2::default();
|
||||||
argon2.hash_password(password.as_bytes(), &salt).map(|h| h.to_string()).map_err(|e| e.into())
|
argon2
|
||||||
|
.hash_password(password.as_bytes(), &salt)
|
||||||
|
.map(|h| h.to_string())
|
||||||
|
.map_err(|e| e.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn verify_password(password: &str, hashed_password: &str) -> Result<bool, Box<dyn std::error::Error>> {
|
pub fn verify_password(
|
||||||
|
password: &str,
|
||||||
|
hashed_password: &str,
|
||||||
|
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||||
let argon2 = Argon2::default();
|
let argon2 = Argon2::default();
|
||||||
let parsed_hash = PasswordHash::new(hashed_password)?;
|
let parsed_hash = PasswordHash::new(hashed_password)?;
|
||||||
Ok(argon2.verify_password(password.as_bytes(), &parsed_hash).is_ok())
|
Ok(argon2
|
||||||
|
.verify_password(password.as_bytes(), &parsed_hash)
|
||||||
|
.is_ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
|
||||||
|
|
@ -1,24 +1,26 @@
|
||||||
use actix_files as fs;
|
use actix_files as fs;
|
||||||
use actix_web::{web, middleware, App, HttpServer};
|
use actix_web::{middleware, web, App, HttpServer};
|
||||||
use chrono::prelude::*;
|
use chrono::prelude::*;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use log::error;
|
use log::error;
|
||||||
|
|
||||||
use data::db;
|
use data::db;
|
||||||
|
|
||||||
|
mod config;
|
||||||
mod consts;
|
mod consts;
|
||||||
mod utils;
|
|
||||||
mod data;
|
mod data;
|
||||||
|
mod email;
|
||||||
mod hash;
|
mod hash;
|
||||||
mod model;
|
mod model;
|
||||||
mod user;
|
|
||||||
mod email;
|
|
||||||
mod config;
|
|
||||||
mod services;
|
mod services;
|
||||||
|
mod user;
|
||||||
|
mod utils;
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
if process_args() { return Ok(()) }
|
if process_args() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
std::env::set_var("RUST_LOG", "info,actix_web=info");
|
std::env::set_var("RUST_LOG", "info,actix_web=info");
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
|
|
@ -32,8 +34,7 @@ async fn main() -> std::io::Result<()> {
|
||||||
|
|
||||||
let db_connection = web::Data::new(db::Connection::new().unwrap());
|
let db_connection = web::Data::new(db::Connection::new().unwrap());
|
||||||
|
|
||||||
let server =
|
let server = HttpServer::new(move || {
|
||||||
HttpServer::new(move || {
|
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
.wrap(middleware::Compress::default())
|
.wrap(middleware::Compress::default())
|
||||||
|
|
@ -60,7 +61,7 @@ async fn main() -> std::io::Result<()> {
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
struct Args {
|
struct Args {
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
dbtest: bool
|
dbtest: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_args() -> bool {
|
fn process_args() -> bool {
|
||||||
|
|
@ -73,11 +74,15 @@ fn process_args() -> bool {
|
||||||
eprintln!("{}", error);
|
eprintln!("{}", error);
|
||||||
}
|
}
|
||||||
// Set the creation datetime to 'now'.
|
// Set the creation datetime to 'now'.
|
||||||
con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap();
|
con.execute_sql(
|
||||||
},
|
"UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'",
|
||||||
|
[Utc::now()],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
eprintln!("{}", error);
|
eprintln!("{}", error);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
|
||||||
|
|
@ -1,59 +1,78 @@
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use actix_web::{http::{header, header::ContentType, StatusCode}, get, post, web, Responder, HttpRequest, HttpResponse, cookie::Cookie};
|
use actix_web::{
|
||||||
|
cookie::Cookie,
|
||||||
|
get,
|
||||||
|
http::{header, header::ContentType, StatusCode},
|
||||||
|
post, web, HttpRequest, HttpResponse, Responder,
|
||||||
|
};
|
||||||
use askama_actix::{Template, TemplateToResponse};
|
use askama_actix::{Template, TemplateToResponse};
|
||||||
use chrono::Duration;
|
use chrono::Duration;
|
||||||
|
use log::{debug, error, info, log_enabled, Level};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use log::{debug, error, log_enabled, info, Level};
|
|
||||||
|
|
||||||
use crate::utils;
|
|
||||||
use crate::email;
|
|
||||||
use crate::consts;
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::user::User;
|
use crate::consts;
|
||||||
|
use crate::data::{asynchronous, db};
|
||||||
|
use crate::email;
|
||||||
use crate::model;
|
use crate::model;
|
||||||
use crate::data::{db, asynchronous};
|
use crate::user::User;
|
||||||
|
use crate::utils;
|
||||||
|
|
||||||
mod api;
|
mod api;
|
||||||
|
|
||||||
///// UTILS /////
|
///// UTILS /////
|
||||||
|
|
||||||
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
|
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
|
||||||
let ip =
|
let ip = match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
|
||||||
match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
|
|
||||||
Some(v) => v.to_str().unwrap_or_default().to_string(),
|
Some(v) => v.to_str().unwrap_or_default().to_string(),
|
||||||
None => req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default()
|
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();
|
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)
|
(ip, user_agent)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_current_user(req: &HttpRequest, connection: web::Data<db::Connection>) -> Option<User> {
|
async fn get_current_user(
|
||||||
|
req: &HttpRequest,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
) -> Option<User> {
|
||||||
let (client_ip, client_user_agent) = get_ip_and_user_agent(req);
|
let (client_ip, client_user_agent) = get_ip_and_user_agent(req);
|
||||||
|
|
||||||
match req.cookie(consts::COOKIE_AUTH_TOKEN_NAME) {
|
match req.cookie(consts::COOKIE_AUTH_TOKEN_NAME) {
|
||||||
Some(token_cookie) =>
|
Some(token_cookie) => match connection
|
||||||
match connection.authentication_async(token_cookie.value(), &client_ip, &client_user_agent).await {
|
.authentication_async(token_cookie.value(), &client_ip, &client_user_agent)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(db::AuthenticationResult::NotValidToken) =>
|
Ok(db::AuthenticationResult::NotValidToken) =>
|
||||||
// TODO: remove cookie?
|
// TODO: remove cookie?
|
||||||
None,
|
{
|
||||||
Ok(db::AuthenticationResult::Ok(user_id)) =>
|
None
|
||||||
|
}
|
||||||
|
Ok(db::AuthenticationResult::Ok(user_id)) => {
|
||||||
match connection.load_user_async(user_id).await {
|
match connection.load_user_async(user_id).await {
|
||||||
Ok(user) =>
|
Ok(user) => Some(user),
|
||||||
Some(user),
|
Err(error) => {
|
||||||
|
error!("Error during authentication: {}", error);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
error!("Error during authentication: {}", error);
|
error!("Error during authentication: {}", error);
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Err(error) => {
|
None => None,
|
||||||
error!("Error during authentication: {}", error);
|
|
||||||
None
|
|
||||||
},
|
|
||||||
},
|
|
||||||
None => None
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -116,7 +135,8 @@ impl actix_web::error::ResponseError for ServiceError {
|
||||||
fn error_response(&self) -> HttpResponse {
|
fn error_response(&self) -> HttpResponse {
|
||||||
MessageBaseTemplate {
|
MessageBaseTemplate {
|
||||||
message: &self.to_string(),
|
message: &self.to_string(),
|
||||||
}.to_response()
|
}
|
||||||
|
.to_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
|
|
@ -135,11 +155,19 @@ struct HomeTemplate {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
pub async fn home_page(req: HttpRequest, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
|
pub async fn home_page(
|
||||||
|
req: HttpRequest,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
let recipes = connection.get_all_recipe_titles_async().await?;
|
let recipes = connection.get_all_recipe_titles_async().await?;
|
||||||
|
|
||||||
Ok(HomeTemplate { user, current_recipe_id: None, recipes }.to_response())
|
Ok(HomeTemplate {
|
||||||
|
user,
|
||||||
|
current_recipe_id: None,
|
||||||
|
recipes,
|
||||||
|
}
|
||||||
|
.to_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
///// VIEW RECIPE /////
|
///// VIEW RECIPE /////
|
||||||
|
|
@ -154,7 +182,11 @@ struct ViewRecipeTemplate {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/recipe/view/{id}")]
|
#[get("/recipe/view/{id}")]
|
||||||
pub async fn view_recipe(req: HttpRequest, path: web::Path<(i64,)>, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
|
pub async fn view_recipe(
|
||||||
|
req: HttpRequest,
|
||||||
|
path: web::Path<(i64,)>,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
let (id,) = path.into_inner();
|
let (id,) = path.into_inner();
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
let recipes = connection.get_all_recipe_titles_async().await?;
|
let recipes = connection.get_all_recipe_titles_async().await?;
|
||||||
|
|
@ -165,7 +197,8 @@ pub async fn view_recipe(req: HttpRequest, path: web::Path<(i64,)>, connection:
|
||||||
current_recipe_id: Some(recipe.id),
|
current_recipe_id: Some(recipe.id),
|
||||||
recipes,
|
recipes,
|
||||||
current_recipe: recipe,
|
current_recipe: recipe,
|
||||||
}.to_response())
|
}
|
||||||
|
.to_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
///// EDIT RECIPE /////
|
///// EDIT RECIPE /////
|
||||||
|
|
@ -180,7 +213,11 @@ struct EditRecipeTemplate {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/recipe/edit/{id}")]
|
#[get("/recipe/edit/{id}")]
|
||||||
pub async fn edit_recipe(req: HttpRequest, path: web::Path<(i64,)>, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
|
pub async fn edit_recipe(
|
||||||
|
req: HttpRequest,
|
||||||
|
path: web::Path<(i64,)>,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
let (id,) = path.into_inner();
|
let (id,) = path.into_inner();
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
let recipes = connection.get_all_recipe_titles_async().await?;
|
let recipes = connection.get_all_recipe_titles_async().await?;
|
||||||
|
|
@ -191,7 +228,8 @@ pub async fn edit_recipe(req: HttpRequest, path: web::Path<(i64,)>, connection:
|
||||||
current_recipe_id: Some(recipe.id),
|
current_recipe_id: Some(recipe.id),
|
||||||
recipes,
|
recipes,
|
||||||
current_recipe: recipe,
|
current_recipe: recipe,
|
||||||
}.to_response())
|
}
|
||||||
|
.to_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
///// MESSAGE /////
|
///// MESSAGE /////
|
||||||
|
|
@ -222,9 +260,18 @@ struct SignUpFormTemplate {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/signup")]
|
#[get("/signup")]
|
||||||
pub async fn sign_up_get(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
|
pub async fn sign_up_get(
|
||||||
|
req: HttpRequest,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
) -> impl Responder {
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
SignUpFormTemplate { user, email: String::new(), message: String::new(), message_email: String::new(), message_password: String::new() }
|
SignUpFormTemplate {
|
||||||
|
user,
|
||||||
|
email: String::new(),
|
||||||
|
message: String::new(),
|
||||||
|
message_email: String::new(),
|
||||||
|
message_password: String::new(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
|
|
@ -244,30 +291,40 @@ enum SignUpError {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/signup")]
|
#[post("/signup")]
|
||||||
pub async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connection: web::Data<db::Connection>, config: web::Data<Config>) -> Result<HttpResponse> {
|
pub async fn sign_up_post(
|
||||||
fn error_response(error: SignUpError, form: &web::Form<SignUpFormData>, user: Option<User>) -> Result<HttpResponse> {
|
req: HttpRequest,
|
||||||
|
form: web::Form<SignUpFormData>,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
config: web::Data<Config>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
|
fn error_response(
|
||||||
|
error: SignUpError,
|
||||||
|
form: &web::Form<SignUpFormData>,
|
||||||
|
user: Option<User>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
Ok(SignUpFormTemplate {
|
Ok(SignUpFormTemplate {
|
||||||
user,
|
user,
|
||||||
email: form.email.clone(),
|
email: form.email.clone(),
|
||||||
message_email:
|
message_email: match error {
|
||||||
match error {
|
|
||||||
SignUpError::InvalidEmail => "Invalid email",
|
SignUpError::InvalidEmail => "Invalid email",
|
||||||
_ => "",
|
_ => "",
|
||||||
}.to_string(),
|
}
|
||||||
message_password:
|
.to_string(),
|
||||||
match error {
|
message_password: match error {
|
||||||
SignUpError::PasswordsNotEqual => "Passwords don't match",
|
SignUpError::PasswordsNotEqual => "Passwords don't match",
|
||||||
SignUpError::InvalidPassword => "Password must have at least eight characters",
|
SignUpError::InvalidPassword => "Password must have at least eight characters",
|
||||||
_ => "",
|
_ => "",
|
||||||
}.to_string(),
|
}
|
||||||
message:
|
.to_string(),
|
||||||
match error {
|
message: match error {
|
||||||
SignUpError::UserAlreadyExists => "This email is already taken",
|
SignUpError::UserAlreadyExists => "This email is already taken",
|
||||||
SignUpError::DatabaseError => "Database error",
|
SignUpError::DatabaseError => "Database error",
|
||||||
SignUpError::UnableSendEmail => "Unable to send the validation email",
|
SignUpError::UnableSendEmail => "Unable to send the validation email",
|
||||||
_ => "",
|
_ => "",
|
||||||
}.to_string(),
|
}
|
||||||
}.to_response())
|
.to_string(),
|
||||||
|
}
|
||||||
|
.to_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
|
|
@ -281,51 +338,80 @@ pub async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, con
|
||||||
return error_response(SignUpError::PasswordsNotEqual, &form, user);
|
return error_response(SignUpError::PasswordsNotEqual, &form, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let common::utils::PasswordValidation::TooShort = common::utils::validate_password(&form.password_1) {
|
if let common::utils::PasswordValidation::TooShort =
|
||||||
|
common::utils::validate_password(&form.password_1)
|
||||||
|
{
|
||||||
return error_response(SignUpError::InvalidPassword, &form, user);
|
return error_response(SignUpError::InvalidPassword, &form, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
match connection.sign_up_async(&form.email, &form.password_1).await {
|
match connection
|
||||||
|
.sign_up_async(&form.email, &form.password_1)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(db::SignUpResult::UserAlreadyExists) => {
|
Ok(db::SignUpResult::UserAlreadyExists) => {
|
||||||
error_response(SignUpError::UserAlreadyExists, &form, user)
|
error_response(SignUpError::UserAlreadyExists, &form, 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 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 {
|
||||||
if let Ok(p) = split_port[1].parse::<u16>() {
|
if let Ok(p) = split_port[1].parse::<u16>() {
|
||||||
break 'p Some(p)
|
break 'p Some(p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
format!("http{}://{}", if port.is_some() && port.unwrap() != 443 { "" } else { "s" }, host)
|
format!(
|
||||||
|
"http{}://{}",
|
||||||
|
if port.is_some() && port.unwrap() != 443 {
|
||||||
|
""
|
||||||
|
} else {
|
||||||
|
"s"
|
||||||
|
},
|
||||||
|
host
|
||||||
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let email = form.email.clone();
|
let email = form.email.clone();
|
||||||
|
|
||||||
match web::block(move || { email::send_validation(&url, &email, &token, &config.smtp_login, &config.smtp_password) }).await? {
|
match web::block(move || {
|
||||||
Ok(()) =>
|
email::send_validation(
|
||||||
Ok(HttpResponse::Found()
|
&url,
|
||||||
|
&email,
|
||||||
|
&token,
|
||||||
|
&config.smtp_login,
|
||||||
|
&config.smtp_password,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Ok(()) => Ok(HttpResponse::Found()
|
||||||
.insert_header((header::LOCATION, "/signup_check_email"))
|
.insert_header((header::LOCATION, "/signup_check_email"))
|
||||||
.finish()),
|
.finish()),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
error!("Email validation error: {}", error);
|
error!("Email validation error: {}", error);
|
||||||
error_response(SignUpError::UnableSendEmail, &form, user)
|
error_response(SignUpError::UnableSendEmail, &form, user)
|
||||||
},
|
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
error!("Signup database error: {}", error);
|
error!("Signup database error: {}", error);
|
||||||
error_response(SignUpError::DatabaseError, &form, user)
|
error_response(SignUpError::DatabaseError, &form, user)
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/signup_check_email")]
|
#[get("/signup_check_email")]
|
||||||
pub async fn sign_up_check_email(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
|
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;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
MessageTemplate {
|
MessageTemplate {
|
||||||
user,
|
user,
|
||||||
|
|
@ -334,55 +420,64 @@ pub async fn sign_up_check_email(req: HttpRequest, connection: web::Data<db::Con
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/validation")]
|
#[get("/validation")]
|
||||||
pub async fn sign_up_validation(req: HttpRequest, query: web::Query<HashMap<String, String>>, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
|
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 (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
|
|
||||||
match query.get("token") {
|
match query.get("token") {
|
||||||
Some(token) => {
|
Some(token) => {
|
||||||
match connection.validation_async(token, Duration::seconds(consts::VALIDATION_TOKEN_DURATION), &client_ip, &client_user_agent).await? {
|
match connection
|
||||||
|
.validation_async(
|
||||||
|
token,
|
||||||
|
Duration::seconds(consts::VALIDATION_TOKEN_DURATION),
|
||||||
|
&client_ip,
|
||||||
|
&client_user_agent,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
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 =
|
let user = match connection.load_user(user_id) {
|
||||||
match connection.load_user(user_id) {
|
Ok(user) => Some(user),
|
||||||
Ok(user) =>
|
|
||||||
Some(user),
|
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
error!("Error retrieving user by id: {}", error);
|
error!("Error retrieving user by id: {}", error);
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut response =
|
let mut response = MessageTemplate {
|
||||||
MessageTemplate {
|
|
||||||
user,
|
user,
|
||||||
message: "Email validation successful, your account has been created",
|
message: "Email validation successful, your account has been created",
|
||||||
}.to_response();
|
}
|
||||||
|
.to_response();
|
||||||
|
|
||||||
if let Err(error) = response.add_cookie(&cookie) {
|
if let Err(error) = response.add_cookie(&cookie) {
|
||||||
error!("Unable to set cookie after validation: {}", error);
|
error!("Unable to set cookie after validation: {}", error);
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(response)
|
Ok(response)
|
||||||
},
|
}
|
||||||
db::ValidationResult::ValidationExpired =>
|
db::ValidationResult::ValidationExpired => Ok(MessageTemplate {
|
||||||
Ok(MessageTemplate {
|
|
||||||
user,
|
user,
|
||||||
message: "The validation has expired. Try to sign up again.",
|
message: "The validation has expired. Try to sign up again.",
|
||||||
}.to_response()),
|
}
|
||||||
db::ValidationResult::UnknownUser =>
|
.to_response()),
|
||||||
Ok(MessageTemplate {
|
db::ValidationResult::UnknownUser => Ok(MessageTemplate {
|
||||||
user,
|
user,
|
||||||
message: "Validation error.",
|
message: "Validation error.",
|
||||||
}.to_response()),
|
|
||||||
}
|
}
|
||||||
},
|
.to_response()),
|
||||||
None => {
|
}
|
||||||
Ok(MessageTemplate {
|
}
|
||||||
|
None => Ok(MessageTemplate {
|
||||||
user,
|
user,
|
||||||
message: &format!("No token provided"),
|
message: &format!("No token provided"),
|
||||||
}.to_response())
|
}
|
||||||
},
|
.to_response()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -397,7 +492,10 @@ struct SignInFormTemplate {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/signin")]
|
#[get("/signin")]
|
||||||
pub async fn sign_in_get(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
|
pub async fn sign_in_get(
|
||||||
|
req: HttpRequest,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
) -> impl Responder {
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
SignInFormTemplate {
|
SignInFormTemplate {
|
||||||
user,
|
user,
|
||||||
|
|
@ -418,53 +516,63 @@ enum SignInError {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/signin")]
|
#[post("/signin")]
|
||||||
pub async fn sign_in_post(req: HttpRequest, form: web::Form<SignInFormData>, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
|
pub async fn sign_in_post(
|
||||||
fn error_response(error: SignInError, form: &web::Form<SignInFormData>, user: Option<User>) -> Result<HttpResponse> {
|
req: HttpRequest,
|
||||||
|
form: web::Form<SignInFormData>,
|
||||||
|
connection: web::Data<db::Connection>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
|
fn error_response(
|
||||||
|
error: SignInError,
|
||||||
|
form: &web::Form<SignInFormData>,
|
||||||
|
user: Option<User>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
Ok(SignInFormTemplate {
|
Ok(SignInFormTemplate {
|
||||||
user,
|
user,
|
||||||
email: form.email.clone(),
|
email: form.email.clone(),
|
||||||
message:
|
message: match error {
|
||||||
match error {
|
|
||||||
SignInError::AccountNotValidated => "This account must be validated first",
|
SignInError::AccountNotValidated => "This account must be validated first",
|
||||||
SignInError::AuthenticationFailed => "Wrong email or password",
|
SignInError::AuthenticationFailed => "Wrong email or password",
|
||||||
}.to_string(),
|
}
|
||||||
}.to_response())
|
.to_string(),
|
||||||
|
}
|
||||||
|
.to_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
let user = get_current_user(&req, connection.clone()).await;
|
let user = get_current_user(&req, connection.clone()).await;
|
||||||
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
|
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
|
||||||
|
|
||||||
match connection.sign_in_async(&form.email, &form.password, &client_ip, &client_user_agent).await {
|
match connection
|
||||||
Ok(db::SignInResult::AccountNotValidated) =>
|
.sign_in_async(&form.email, &form.password, &client_ip, &client_user_agent)
|
||||||
error_response(SignInError::AccountNotValidated, &form, user),
|
.await
|
||||||
|
{
|
||||||
|
Ok(db::SignInResult::AccountNotValidated) => {
|
||||||
|
error_response(SignInError::AccountNotValidated, &form, user)
|
||||||
|
}
|
||||||
Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => {
|
Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => {
|
||||||
error_response(SignInError::AuthenticationFailed, &form, user)
|
error_response(SignInError::AuthenticationFailed, &form, user)
|
||||||
},
|
}
|
||||||
Ok(db::SignInResult::Ok(token, user_id)) => {
|
Ok(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 =
|
let mut response = HttpResponse::Found()
|
||||||
HttpResponse::Found()
|
|
||||||
.insert_header((header::LOCATION, "/"))
|
.insert_header((header::LOCATION, "/"))
|
||||||
.finish();
|
.finish();
|
||||||
if let Err(error) = response.add_cookie(&cookie) {
|
if let Err(error) = response.add_cookie(&cookie) {
|
||||||
error!("Unable to set cookie after sign in: {}", error);
|
error!("Unable to set cookie after sign in: {}", error);
|
||||||
};
|
};
|
||||||
Ok(response)
|
Ok(response)
|
||||||
},
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
error!("Signin error: {}", error);
|
error!("Signin error: {}", error);
|
||||||
error_response(SignInError::AuthenticationFailed, &form, user)
|
error_response(SignInError::AuthenticationFailed, &form, user)
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
///// SIGN OUT /////
|
///// SIGN OUT /////
|
||||||
|
|
||||||
#[get("/signout")]
|
#[get("/signout")]
|
||||||
pub async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
|
pub async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
|
||||||
let mut response =
|
let mut response = HttpResponse::Found()
|
||||||
HttpResponse::Found()
|
|
||||||
.insert_header((header::LOCATION, "/"))
|
.insert_header((header::LOCATION, "/"))
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
|
|
@ -473,7 +581,9 @@ pub async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -
|
||||||
error!("Unable to sign out: {}", error);
|
error!("Unable to sign out: {}", error);
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Err(error) = response.add_removal_cookie(&Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, "")) {
|
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);
|
error!("Unable to set a removal cookie after sign out: {}", error);
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,28 +1,45 @@
|
||||||
use actix_web::{http::{header, header::ContentType, StatusCode}, get, post, put, web, Responder, HttpRequest, HttpResponse, cookie::Cookie, HttpMessage};
|
use actix_web::{
|
||||||
|
cookie::Cookie,
|
||||||
|
get,
|
||||||
|
http::{header, header::ContentType, StatusCode},
|
||||||
|
post, put, web, HttpMessage, HttpRequest, HttpResponse, Responder,
|
||||||
|
};
|
||||||
use chrono::Duration;
|
use chrono::Duration;
|
||||||
use futures::TryFutureExt;
|
use futures::TryFutureExt;
|
||||||
use serde::Deserialize;
|
use log::{debug, error, info, log_enabled, Level};
|
||||||
use ron::de::from_bytes;
|
use ron::de::from_bytes;
|
||||||
use log::{debug, error, log_enabled, info, Level};
|
use serde::Deserialize;
|
||||||
|
|
||||||
use super::Result;
|
use super::Result;
|
||||||
use crate::utils;
|
|
||||||
use crate::consts;
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::user::User;
|
use crate::consts;
|
||||||
|
use crate::data::{asynchronous, db};
|
||||||
use crate::model;
|
use crate::model;
|
||||||
use crate::data::{db, asynchronous};
|
use crate::user::User;
|
||||||
|
use crate::utils;
|
||||||
|
|
||||||
#[put("/ron-api/recipe/set-title")]
|
#[put("/ron-api/recipe/set-title")]
|
||||||
pub async fn set_recipe_title(req: HttpRequest, body: web::Bytes, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
|
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)?;
|
let ron_req: common::ron_api::SetRecipeTitle = from_bytes(&body)?;
|
||||||
connection.set_recipe_title_async(ron_req.recipe_id, &ron_req.title).await?;
|
connection
|
||||||
|
.set_recipe_title_async(ron_req.recipe_id, &ron_req.title)
|
||||||
|
.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(req: HttpRequest, body: web::Bytes, connection: web::Data<db::Connection>) -> Result<HttpResponse> {
|
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)?;
|
let ron_req: common::ron_api::SetRecipeDescription = from_bytes(&body)?;
|
||||||
connection.set_recipe_description_async(ron_req.recipe_id, &ron_req.description).await?;
|
connection
|
||||||
|
.set_recipe_description_async(ron_req.recipe_id, &ron_req.description)
|
||||||
|
.await?;
|
||||||
Ok(HttpResponse::Ok().finish())
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
@ -2,7 +2,7 @@ use log::error;
|
||||||
|
|
||||||
pub fn unwrap_print_err<T, E>(r: Result<T, E>) -> T
|
pub fn unwrap_print_err<T, E>(r: Result<T, E>) -> T
|
||||||
where
|
where
|
||||||
E: std::fmt::Debug
|
E: std::fmt::Debug,
|
||||||
{
|
{
|
||||||
if let Err(ref error) = r {
|
if let Err(ref error) = r {
|
||||||
error!("{:?}", error);
|
error!("{:?}", error);
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue