Sign up method.
beginning of adding methods to create account and authentication.
This commit is contained in:
parent
855eb16973
commit
5e4e086247
5 changed files with 258 additions and 32 deletions
18
backend/sql/data_test.sql
Normal file
18
backend/sql/data_test.sql
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
|
||||||
|
VALUES (
|
||||||
|
1,
|
||||||
|
'paul@test.org',
|
||||||
|
'paul',
|
||||||
|
'$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
|
||||||
|
0,
|
||||||
|
NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO [Recipe] ([user_id], [title])
|
||||||
|
VALUES (1, 'Croissant au jambon');
|
||||||
|
|
||||||
|
INSERT INTO [Recipe] ([user_id], [title])
|
||||||
|
VALUES (1, 'Gratin de thon aux olives');
|
||||||
|
|
||||||
|
INSERT INTO [Recipe] ([user_id], [title])
|
||||||
|
VALUES (1, 'Saumon en croute');
|
||||||
|
|
@ -8,16 +8,38 @@ CREATE TABLE [Version] (
|
||||||
CREATE TABLE [User] (
|
CREATE TABLE [User] (
|
||||||
[id] INTEGER PRIMARY KEY,
|
[id] INTEGER PRIMARY KEY,
|
||||||
[email] TEXT NOT NULL,
|
[email] TEXT NOT NULL,
|
||||||
[password] TEXT NOT NULL, -- Hashed and salted.
|
[name] TEXT,
|
||||||
[name] TEXT NOT NULL
|
[default_servings] INTEGER DEFAULT 4,
|
||||||
|
|
||||||
|
[password] TEXT NOT NULL, -- argon2(password_plain, salt).
|
||||||
|
|
||||||
|
[creation_datetime] DATETIME NOT NULL, -- Updated when the validation email is sent.
|
||||||
|
[validation_token] TEXT -- If not null then the user has not validated his account yet.
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX [User_email_index] ON [User] ([email]);
|
||||||
|
|
||||||
|
CREATE TABLE [UserLoginToken] (
|
||||||
|
[id] INTEGER PRIMARY KEY,
|
||||||
|
[user_id] INTEGER NOT NULL,
|
||||||
|
[last_login_datetime] DATETIME,
|
||||||
|
[token] TEXT NOT NULL, -- 24 alphanumeric character token. Can be stored in a cookie to be able to authenticate without a password.
|
||||||
|
|
||||||
|
[ip] INTEGER,
|
||||||
|
[user_agent] TEXT,
|
||||||
|
|
||||||
|
FOREIGN KEY([user_id]) REFERENCES [User]([id])
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX [UserLoginToken_token_index] ON [UserLoginToken] ([token]);
|
||||||
|
|
||||||
CREATE TABLE [Recipe] (
|
CREATE TABLE [Recipe] (
|
||||||
[id] INTEGER PRIMARY KEY,
|
[id] INTEGER PRIMARY KEY,
|
||||||
[user_id] INTEGER NOT NULL,
|
[user_id] INTEGER NOT NULL,
|
||||||
[title] TEXT NOT NULL,
|
[title] TEXT NOT NULL,
|
||||||
[estimate_time] INTEGER,
|
[estimate_time] INTEGER,
|
||||||
[description] TEXT,
|
[description] TEXT,
|
||||||
|
[servings] INTEGER DEFAULT 4,
|
||||||
|
|
||||||
FOREIGN KEY([user_id]) REFERENCES [User]([id])
|
FOREIGN KEY([user_id]) REFERENCES [User]([id])
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
use std::{fs::{self, File}, path::Path, io::Read};
|
use std::{fmt::Display, fs::{self, File}, path::Path, io::Read};
|
||||||
|
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
//use rusqlite::types::ToSql;
|
use chrono::{prelude::*, Duration};
|
||||||
//use rusqlite::{Connection, Result, NO_PARAMS};
|
use rusqlite::{params, Params, OptionalExtension};
|
||||||
use r2d2::Pool;
|
use r2d2::Pool;
|
||||||
use r2d2_sqlite::SqliteConnectionManager;
|
use r2d2_sqlite::SqliteConnectionManager;
|
||||||
|
use rand::distributions::{Alphanumeric, DistString};
|
||||||
|
|
||||||
use crate::consts;
|
use crate::consts;
|
||||||
|
use crate::hash::hash;
|
||||||
use crate::model;
|
use crate::model;
|
||||||
|
|
||||||
const CURRENT_DB_VERSION: u32 = 1;
|
const CURRENT_DB_VERSION: u32 = 1;
|
||||||
|
|
@ -31,8 +33,39 @@ impl From<r2d2::Error> for DBError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Is there a better solution?
|
||||||
|
impl DBError {
|
||||||
|
fn from_dyn_error(error: Box<dyn std::error::Error>) -> Self {
|
||||||
|
DBError::Other(error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type Result<T> = std::result::Result<T, DBError>;
|
type Result<T> = std::result::Result<T, DBError>;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum SignUpResult {
|
||||||
|
UserAlreadyExists,
|
||||||
|
UserCreatedWaitingForValidation(String), // Validation token.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ValidationResult {
|
||||||
|
ValidationExpired,
|
||||||
|
OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum SignInResult {
|
||||||
|
NotValidToken,
|
||||||
|
OK,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum AuthenticationResult {
|
||||||
|
NotValidToken,
|
||||||
|
OK,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Connection {
|
pub struct Connection {
|
||||||
//con: rusqlite::Connection
|
//con: rusqlite::Connection
|
||||||
|
|
@ -41,25 +74,26 @@ pub struct Connection {
|
||||||
|
|
||||||
impl Connection {
|
impl Connection {
|
||||||
pub fn new() -> Result<Connection> {
|
pub fn new() -> Result<Connection> {
|
||||||
|
let path = Path::new(consts::DB_DIRECTORY).join(consts::DB_FILENAME);
|
||||||
|
Self::new_from_file(path)
|
||||||
|
}
|
||||||
|
|
||||||
let data_dir = Path::new(consts::DB_DIRECTORY);
|
pub fn new_in_memory() -> Result<Connection> {
|
||||||
|
Self::create_connection(SqliteConnectionManager::memory())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_from_file<P: AsRef<Path>>(file: P) -> Result<Connection> {
|
||||||
|
if let Some(data_dir) = file.as_ref().parent() {
|
||||||
if !data_dir.exists() {
|
if !data_dir.exists() {
|
||||||
fs::DirBuilder::new().create(data_dir).unwrap();
|
fs::DirBuilder::new().create(data_dir).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
let manager = SqliteConnectionManager::file(consts::DB_FILENAME);
|
|
||||||
let pool = r2d2::Pool::new(manager).unwrap();
|
|
||||||
|
|
||||||
let connection = Connection { pool };
|
|
||||||
connection.create_or_update()?;
|
|
||||||
Ok(connection)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
Self::create_connection(SqliteConnectionManager::file(file))
|
||||||
* Called after the connection has been established for creating or updating the database.
|
}
|
||||||
* The 'Version' table tracks the current state of the database.
|
|
||||||
*/
|
/// Called after the connection has been established for creating or updating the database.
|
||||||
|
/// The 'Version' table tracks the current state of the database.
|
||||||
fn create_or_update(&self) -> Result<()> {
|
fn create_or_update(&self) -> Result<()> {
|
||||||
// Check the Database version.
|
// Check the Database version.
|
||||||
let mut con = self.pool.get()?;
|
let mut con = self.pool.get()?;
|
||||||
|
|
@ -86,6 +120,13 @@ impl Connection {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn create_connection(manager: SqliteConnectionManager) -> Result<Connection> {;
|
||||||
|
let pool = r2d2::Pool::new(manager).unwrap();
|
||||||
|
let connection = Connection { pool };
|
||||||
|
connection.create_or_update()?;
|
||||||
|
Ok(connection)
|
||||||
|
}
|
||||||
|
|
||||||
fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result<bool> {
|
fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result<bool> {
|
||||||
let next_version = current_version + 1;
|
let next_version = current_version + 1;
|
||||||
|
|
||||||
|
|
@ -106,7 +147,8 @@ impl Connection {
|
||||||
|
|
||||||
match next_version {
|
match next_version {
|
||||||
1 => {
|
1 => {
|
||||||
tx.execute_batch(&load_sql_file(next_version)?)?;
|
let sql_file = consts::SQL_FILENAME.replace("{VERSION}", &next_version.to_string());
|
||||||
|
tx.execute_batch(&load_sql_file(&sql_file)?)?;
|
||||||
update_version(next_version, tx)?;
|
update_version(next_version, tx)?;
|
||||||
|
|
||||||
ok(true)
|
ok(true)
|
||||||
|
|
@ -131,6 +173,7 @@ impl Connection {
|
||||||
Ok(titles)
|
Ok(titles)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Not used for the moment.
|
||||||
pub fn get_all_recipes(&self) -> Result<Vec<model::Recipe>> {
|
pub fn get_all_recipes(&self) -> Result<Vec<model::Recipe>> {
|
||||||
let con = self.pool.get()?;
|
let con = self.pool.get()?;
|
||||||
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]")?;
|
||||||
|
|
@ -139,7 +182,7 @@ impl Connection {
|
||||||
Ok(model::Recipe::new(row.get(0)?, row.get(1)?))
|
Ok(model::Recipe::new(row.get(0)?, row.get(1)?))
|
||||||
})?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.
|
})?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.
|
||||||
Ok(recipes)
|
Ok(recipes)
|
||||||
}
|
} */
|
||||||
|
|
||||||
pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {
|
pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {
|
||||||
let con = self.pool.get()?;
|
let con = self.pool.get()?;
|
||||||
|
|
@ -147,12 +190,127 @@ impl Connection {
|
||||||
Ok(model::Recipe::new(row.get(0)?, row.get(1)?))
|
Ok(model::Recipe::new(row.get(0)?, row.get(1)?))
|
||||||
}).map_err(DBError::from)
|
}).map_err(DBError::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
pub fn sign_up(&self, password: &str, email: &str) -> Result<SignUpResult> {
|
||||||
|
self.sign_up_with_given_time(password, email, Utc::now())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign_up_with_given_time(&self, password: &str, email: &str, datetime: DateTime<Utc>) -> Result<SignUpResult> {
|
||||||
|
let mut con = self.pool.get()?;
|
||||||
|
let tx = con.transaction()?;
|
||||||
|
let token =
|
||||||
|
match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {
|
||||||
|
Ok((r.get::<&str, i32>("id")?, r.get::<&str, Option<String>>("validation_token")?))
|
||||||
|
}).optional()? {
|
||||||
|
Some((id, validation_token)) => {
|
||||||
|
if validation_token.is_none() {
|
||||||
|
return Ok(SignUpResult::UserAlreadyExists)
|
||||||
|
}
|
||||||
|
let token = generate_token();
|
||||||
|
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])?;
|
||||||
|
token
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
let token = generate_token();
|
||||||
|
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])?;
|
||||||
|
token
|
||||||
|
},
|
||||||
|
};
|
||||||
|
tx.commit()?;
|
||||||
|
Ok(SignUpResult::UserCreatedWaitingForValidation(token))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validation(&self, token: &str, validation_time: Duration) -> Result<ValidationResult> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sign_in(&self, password: &str, email: String) -> Result<SignInResult> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn authentication(&self, token: &str) -> Result<AuthenticationResult> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn logout(&self, token: &str) -> Result<()> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execute a given SQL file.
|
||||||
|
pub fn execute_file<P: AsRef<Path> + Display>(&self, file: P) -> Result<()> {
|
||||||
|
let con = self.pool.get()?;
|
||||||
|
let sql = load_sql_file(file)?;
|
||||||
|
con.execute_batch(&sql).map_err(DBError::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execute any SQL statement.
|
||||||
|
/// Mainly used for testing.
|
||||||
|
pub fn execute_sql<P: Params>(&self, sql: &str, params: P) -> Result<usize> {
|
||||||
|
let con = self.pool.get()?;
|
||||||
|
con.execute(sql, params).map_err(DBError::from)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_sql_file(version: u32) -> Result<String> {
|
fn load_sql_file<P: AsRef<Path> + Display>(sql_file: P) -> Result<String> {
|
||||||
let sql_file = consts::SQL_FILENAME.replace("{VERSION}", &version.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 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn generate_token() -> String {
|
||||||
|
Alphanumeric.sample_string(&mut rand::thread_rng(), 24)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sign_up() -> Result<()> {
|
||||||
|
let connection = Connection::new_in_memory()?;
|
||||||
|
match connection.sign_up("12345", "paul@test.org")? {
|
||||||
|
SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case.
|
||||||
|
other => panic!("{:?}", other),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sign_up_to_an_already_existing_user() -> Result<()> {
|
||||||
|
let connection = Connection::new_in_memory()?;
|
||||||
|
connection.execute_sql("
|
||||||
|
INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
|
||||||
|
VALUES (
|
||||||
|
1,
|
||||||
|
'paul@test.org',
|
||||||
|
'paul',
|
||||||
|
'$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
|
||||||
|
0,
|
||||||
|
NULL
|
||||||
|
);", [])?;
|
||||||
|
match connection.sign_up("12345", "paul@test.org")? {
|
||||||
|
SignUpResult::UserAlreadyExists => (), // Nominal case.
|
||||||
|
other => panic!("{:?}", other),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sign_up_to_an_unvalidated_already_existing_user() -> Result<()> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign_up_then_send_validation_at_time() -> Result<()> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign_up_then_send_validation_too_late() -> Result<()> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
//fn sign_up_then_send_validation_then_sign_in()
|
||||||
|
}
|
||||||
|
|
|
||||||
16
backend/src/hash.rs
Normal file
16
backend/src/hash.rs
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
use std::{string::String, env::consts::OS};
|
||||||
|
|
||||||
|
use argon2::{
|
||||||
|
password_hash::{
|
||||||
|
Error,
|
||||||
|
rand_core::OsRng,
|
||||||
|
PasswordHash, PasswordHasher, PasswordVerifier, SaltString
|
||||||
|
},
|
||||||
|
Argon2
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn hash(password: &str) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
let argon2 = Argon2::default();
|
||||||
|
argon2.hash_password(password.as_bytes(), &salt).map(|h| h.to_string()).map_err(|e| e.into())
|
||||||
|
}
|
||||||
|
|
@ -4,13 +4,15 @@ use std::sync::Mutex;
|
||||||
use actix_files as fs;
|
use actix_files as fs;
|
||||||
use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpRequest};
|
use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpRequest};
|
||||||
use askama_actix::Template;
|
use askama_actix::Template;
|
||||||
|
use chrono::prelude::*;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use ron::de::from_reader;
|
use ron::de::from_reader;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
mod consts;
|
mod consts;
|
||||||
mod model;
|
|
||||||
mod db;
|
mod db;
|
||||||
|
mod hash;
|
||||||
|
mod model;
|
||||||
|
|
||||||
#[derive(Template)]
|
#[derive(Template)]
|
||||||
#[template(path = "home.html")]
|
#[template(path = "home.html")]
|
||||||
|
|
@ -98,16 +100,26 @@ async fn main() -> std::io::Result<()> {
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
struct Args {
|
struct Args {
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
test: bool
|
dbtest: bool
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_args() -> bool {
|
fn process_args() -> bool {
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
if args.test {
|
if args.dbtest {
|
||||||
if let Err(error) = db::Connection::new() {
|
match db::Connection::new() {
|
||||||
println!("Error: {:?}", error)
|
Ok(con) => {
|
||||||
|
if let Err(error) = con.execute_file("sql/data_test.sql") {
|
||||||
|
println!("Error: {:?}", error);
|
||||||
}
|
}
|
||||||
|
// Set the creation datetime to 'now'.
|
||||||
|
con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap();
|
||||||
|
},
|
||||||
|
Err(error) => {
|
||||||
|
println!("Error: {:?}", error)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue