Sign up method.
[recipes.git] / backend / src / db.rs
index 2bf383b..4ef37fe 100644 (file)
@@ -1,12 +1,14 @@
-use std::{fs::{self, File}, path::Path, io::Read};\r
+use std::{fmt::Display, fs::{self, File}, path::Path, io::Read};\r
 \r
 use itertools::Itertools;\r
-//use rusqlite::types::ToSql;\r
-//use rusqlite::{Connection, Result, NO_PARAMS};\r
+use chrono::{prelude::*, Duration};\r
+use rusqlite::{params, Params, OptionalExtension};\r
 use r2d2::Pool;\r
 use r2d2_sqlite::SqliteConnectionManager;\r
+use rand::distributions::{Alphanumeric, DistString};\r
 \r
 use crate::consts;\r
+use crate::hash::hash;\r
 use crate::model;\r
 \r
 const CURRENT_DB_VERSION: u32 = 1;\r
@@ -31,8 +33,39 @@ impl From<r2d2::Error> for DBError  {
     }\r
 }\r
 \r
+// TODO: Is there a better solution?\r
+impl DBError {\r
+    fn from_dyn_error(error: Box<dyn std::error::Error>) -> Self {\r
+        DBError::Other(error.to_string())\r
+    }\r
+}\r
+\r
 type Result<T> = std::result::Result<T, DBError>;\r
 \r
+#[derive(Debug)]\r
+pub enum SignUpResult {\r
+    UserAlreadyExists,\r
+    UserCreatedWaitingForValidation(String), // Validation token.\r
+}\r
+\r
+#[derive(Debug)]\r
+pub enum ValidationResult {\r
+    ValidationExpired,\r
+    OK,\r
+}\r
+\r
+#[derive(Debug)]\r
+pub enum SignInResult {\r
+    NotValidToken,\r
+    OK,\r
+}\r
+\r
+#[derive(Debug)]\r
+pub enum AuthenticationResult {\r
+    NotValidToken,\r
+    OK,\r
+}\r
+\r
 #[derive(Clone)]\r
 pub struct Connection {\r
     //con: rusqlite::Connection\r
@@ -41,25 +74,26 @@ pub struct Connection {
 \r
 impl Connection {\r
     pub fn new() -> Result<Connection> {\r
+        let path = Path::new(consts::DB_DIRECTORY).join(consts::DB_FILENAME);\r
+        Self::new_from_file(path)\r
+    }\r
 \r
-        let data_dir = Path::new(consts::DB_DIRECTORY);\r
+    pub fn new_in_memory() -> Result<Connection> {\r
+        Self::create_connection(SqliteConnectionManager::memory())\r
+    }\r
 \r
-        if !data_dir.exists() {\r
-            fs::DirBuilder::new().create(data_dir).unwrap();\r
+    pub fn new_from_file<P: AsRef<Path>>(file: P) -> Result<Connection> {\r
+        if let Some(data_dir) = file.as_ref().parent() {\r
+            if !data_dir.exists() {\r
+                fs::DirBuilder::new().create(data_dir).unwrap();\r
+            }\r
         }\r
 \r
-        let manager = SqliteConnectionManager::file(consts::DB_FILENAME);\r
-        let pool = r2d2::Pool::new(manager).unwrap();\r
-\r
-        let connection = Connection { pool };\r
-        connection.create_or_update()?;\r
-        Ok(connection)\r
+        Self::create_connection(SqliteConnectionManager::file(file))\r
     }\r
 \r
-    /*\r
-     * Called after the connection has been established for creating or updating the database.\r
-     * The 'Version' table tracks the current state of the database.\r
-     */\r
+    /// Called after the connection has been established for creating or updating the database.\r
+    /// The 'Version' table tracks the current state of the database.\r
     fn create_or_update(&self) -> Result<()> {\r
         // Check the Database version.\r
         let mut con = self.pool.get()?;\r
@@ -86,6 +120,13 @@ impl Connection {
         Ok(())\r
     }\r
 \r
+    fn create_connection(manager: SqliteConnectionManager) -> Result<Connection> {;\r
+        let pool = r2d2::Pool::new(manager).unwrap();\r
+        let connection = Connection { pool };\r
+        connection.create_or_update()?;\r
+        Ok(connection)\r
+    }\r
+\r
     fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result<bool> {\r
         let next_version = current_version + 1;\r
 \r
@@ -106,7 +147,8 @@ impl Connection {
 \r
         match next_version {\r
             1 => {\r
-                tx.execute_batch(&load_sql_file(next_version)?)?;\r
+                let sql_file = consts::SQL_FILENAME.replace("{VERSION}", &next_version.to_string());\r
+                tx.execute_batch(&load_sql_file(&sql_file)?)?;\r
                 update_version(next_version, tx)?;\r
 \r
                 ok(true)\r
@@ -131,6 +173,7 @@ impl Connection {
         Ok(titles)\r
     }\r
 \r
+    /* Not used for the moment.\r
     pub fn get_all_recipes(&self) -> Result<Vec<model::Recipe>> {\r
         let con = self.pool.get()?;\r
         let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;\r
@@ -139,7 +182,7 @@ impl Connection {
                 Ok(model::Recipe::new(row.get(0)?, row.get(1)?))\r
             })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.\r
         Ok(recipes)\r
-    }\r
+    } */\r
 \r
     pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {\r
         let con = self.pool.get()?;\r
@@ -147,12 +190,127 @@ impl Connection {
             Ok(model::Recipe::new(row.get(0)?, row.get(1)?))\r
         }).map_err(DBError::from)\r
     }\r
+\r
+    ///\r
+    pub fn sign_up(&self, password: &str, email: &str) -> Result<SignUpResult> {\r
+        self.sign_up_with_given_time(password, email, Utc::now())\r
+    }\r
+\r
+    fn sign_up_with_given_time(&self, password: &str, email: &str, datetime: DateTime<Utc>) -> Result<SignUpResult> {\r
+        let mut con = self.pool.get()?;\r
+        let tx = con.transaction()?;\r
+        let token =\r
+            match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {\r
+                Ok((r.get::<&str, i32>("id")?, r.get::<&str, Option<String>>("validation_token")?))\r
+            }).optional()? {\r
+                Some((id, validation_token)) => {\r
+                    if validation_token.is_none() {\r
+                        return Ok(SignUpResult::UserAlreadyExists)\r
+                    }\r
+                    let token = generate_token();\r
+                    let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;\r
+                    tx.execute("UPDATE [User] SET [validation_token] = ?2, [creation_datetime] = ?3, [password] = ?4 WHERE [id] = ?1", params![id, token, datetime, hashed_password])?;\r
+                    token\r
+                },\r
+                None => {\r
+                    let token = generate_token();\r
+                    let hashed_password = hash(password).map_err(|e| DBError::from_dyn_error(e))?;\r
+                    tx.execute("INSERT INTO [User] ([email], [validation_token], [creation_datetime], [password]) VALUES (?1, ?2, ?3, ?4)", params![email, token, datetime, hashed_password])?;\r
+                    token\r
+                },\r
+            };\r
+        tx.commit()?;\r
+        Ok(SignUpResult::UserCreatedWaitingForValidation(token))\r
+    }\r
+\r
+    pub fn validation(&self, token: &str, validation_time: Duration) -> Result<ValidationResult> {\r
+        todo!()\r
+    }\r
+\r
+    pub fn sign_in(&self, password: &str, email: String) -> Result<SignInResult> {\r
+        todo!()\r
+    }\r
+\r
+    pub fn authentication(&self, token: &str) -> Result<AuthenticationResult> {\r
+        todo!()\r
+    }\r
+\r
+    pub fn logout(&self, token: &str) -> Result<()> {\r
+        todo!()\r
+    }\r
+\r
+    /// Execute a given SQL file.\r
+    pub fn execute_file<P: AsRef<Path> + Display>(&self, file: P) -> Result<()> {\r
+        let con = self.pool.get()?;\r
+        let sql = load_sql_file(file)?;\r
+        con.execute_batch(&sql).map_err(DBError::from)\r
+    }\r
+\r
+    /// Execute any SQL statement.\r
+    /// Mainly used for testing.\r
+    pub fn execute_sql<P: Params>(&self, sql: &str, params: P) -> Result<usize> {\r
+        let con = self.pool.get()?;\r
+        con.execute(sql, params).map_err(DBError::from)\r
+    }\r
 }\r
 \r
-fn load_sql_file(version: u32) -> Result<String> {\r
-    let sql_file = consts::SQL_FILENAME.replace("{VERSION}", &version.to_string());\r
+fn load_sql_file<P: AsRef<Path> + Display>(sql_file: P) -> Result<String> {\r
     let mut file = File::open(&sql_file).map_err(|err| DBError::Other(format!("Cannot open SQL file ({}): {}", &sql_file, err.to_string())))?;\r
     let mut sql = String::new();\r
     file.read_to_string(&mut sql).map_err(|err| DBError::Other(format!("Cannot read SQL file ({}) : {}", &sql_file, err.to_string())))?;\r
     Ok(sql)\r
-}
\ No newline at end of file
+}\r
+\r
+fn generate_token() -> String {\r
+    Alphanumeric.sample_string(&mut rand::thread_rng(), 24)\r
+}\r
+\r
+#[cfg(test)]\r
+mod tests {\r
+    use super::*;\r
+\r
+    #[test]\r
+    fn sign_up() -> Result<()> {\r
+        let connection = Connection::new_in_memory()?;\r
+        match connection.sign_up("12345", "paul@test.org")? {\r
+            SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case.\r
+            other => panic!("{:?}", other),\r
+        }\r
+        Ok(())\r
+    }\r
+\r
+    #[test]\r
+    fn sign_up_to_an_already_existing_user() -> Result<()> {\r
+        let connection = Connection::new_in_memory()?;\r
+        connection.execute_sql("\r
+            INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])\r
+                VALUES (\r
+                    1,\r
+                    'paul@test.org',\r
+                    'paul',\r
+                    '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',\r
+                    0,\r
+                    NULL\r
+                );", [])?;\r
+        match connection.sign_up("12345", "paul@test.org")? {\r
+            SignUpResult::UserAlreadyExists => (), // Nominal case.\r
+            other => panic!("{:?}", other),\r
+        }\r
+        Ok(())\r
+    }\r
+\r
+    #[test]\r
+    fn sign_up_to_an_unvalidated_already_existing_user() -> Result<()> {\r
+        todo!()\r
+    }\r
+\r
+    fn sign_up_then_send_validation_at_time() -> Result<()> {\r
+        todo!()\r
+    }\r
+\r
+    fn sign_up_then_send_validation_too_late() -> Result<()> {\r
+        todo!()\r
+    }\r
+\r
+    //fn sign_up_then_send_validation_then_sign_in()\r
+}\r