Sign up/in/out and authentication.
[recipes.git] / backend / src / db.rs
index 4ef37fe..28bf62c 100644 (file)
@@ -2,14 +2,15 @@ use std::{fmt::Display, fs::{self, File}, path::Path, io::Read};
 \r
 use itertools::Itertools;\r
 use chrono::{prelude::*, Duration};\r
-use rusqlite::{params, Params, OptionalExtension};\r
+use rusqlite::{named_params, OptionalExtension, params, Params};\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::hash::{hash, verify_password};\r
 use crate::model;\r
+use crate::user::*;\r
 \r
 const CURRENT_DB_VERSION: u32 = 1;\r
 \r
@@ -50,20 +51,22 @@ pub enum SignUpResult {
 \r
 #[derive(Debug)]\r
 pub enum ValidationResult {\r
+    UnknownUser,\r
     ValidationExpired,\r
-    OK,\r
+    Ok(String, i32), // Returns token and user id.\r
 }\r
 \r
 #[derive(Debug)]\r
 pub enum SignInResult {\r
-    NotValidToken,\r
-    OK,\r
+    UserNotFound,\r
+    PasswordsDontMatch,\r
+    Ok(String, i32), // Returns token and user id.\r
 }\r
 \r
 #[derive(Debug)]\r
 pub enum AuthenticationResult {\r
     NotValidToken,\r
-    OK,\r
+    Ok(i32), // Returns user id.\r
 }\r
 \r
 #[derive(Clone)]\r
@@ -92,6 +95,13 @@ impl Connection {
         Self::create_connection(SqliteConnectionManager::file(file))\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
     /// 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
@@ -111,7 +121,7 @@ impl Connection {
             }\r
         };\r
 \r
-        while Connection::update_to_next_version(version, &tx)? {\r
+        while Self::update_to_next_version(version, &tx)? {\r
             version += 1;\r
         }\r
 \r
@@ -120,13 +130,6 @@ 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
@@ -191,6 +194,17 @@ impl Connection {
         }).map_err(DBError::from)\r
     }\r
 \r
+    pub fn get_user_login_info(&self, token: &str) -> Result<UserLoginInfo> {\r
+        let con = self.pool.get()?;\r
+        con.query_row("SELECT [last_login_datetime], [ip], [user_agent] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {\r
+            Ok(UserLoginInfo {\r
+                last_login_datetime: r.get("last_login_datetime")?,\r
+                ip: r.get("ip")?,\r
+                user_agent: r.get("user_agent")?,\r
+            })\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
@@ -223,20 +237,79 @@ impl Connection {
         Ok(SignUpResult::UserCreatedWaitingForValidation(token))\r
     }\r
 \r
-    pub fn validation(&self, token: &str, validation_time: Duration) -> Result<ValidationResult> {\r
-        todo!()\r
+    pub fn validation(&self, token: &str, validation_time: Duration, ip: &str, user_agent: &str) -> Result<ValidationResult> {\r
+        let mut con = self.pool.get()?;\r
+        let tx = con.transaction()?;\r
+        let user_id =\r
+            match tx.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token], |r| {\r
+                Ok((r.get::<&str, i32>("id")?, r.get::<&str, DateTime<Utc>>("creation_datetime")?))\r
+            }).optional()? {\r
+                Some((id, creation_datetime)) => {\r
+                    if Utc::now() - creation_datetime > validation_time {\r
+                        return Ok(ValidationResult::ValidationExpired)\r
+                    }\r
+                    tx.execute("UPDATE [User] SET [validation_token] = NULL WHERE [id] = ?1", [id])?;\r
+                    id\r
+                },\r
+                None => {\r
+                    return Ok(ValidationResult::UnknownUser)\r
+                },\r
+            };\r
+        let token = Connection::create_login_token(&tx, user_id, ip, user_agent)?;\r
+        tx.commit()?;\r
+        Ok(ValidationResult::Ok(token, user_id))\r
     }\r
 \r
-    pub fn sign_in(&self, password: &str, email: String) -> Result<SignInResult> {\r
-        todo!()\r
+    pub fn sign_in(&self, password: &str, email: &str, ip: &str, user_agent: &str) -> Result<SignInResult> {\r
+        let mut con = self.pool.get()?;\r
+        let tx = con.transaction()?;\r
+        match tx.query_row("SELECT [id], [password] FROM [User] WHERE [email] = ?1", [email], |r| {\r
+            Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?))\r
+        }).optional()? {\r
+            Some((id, stored_password)) => {\r
+                if verify_password(password, &stored_password).map_err(DBError::from_dyn_error)? {\r
+                    let token = Connection::create_login_token(&tx, id, ip, user_agent)?;\r
+                    tx.commit()?;\r
+                    Ok(SignInResult::Ok(token, id))\r
+                } else {\r
+                    Ok(SignInResult::PasswordsDontMatch)\r
+                }\r
+            },\r
+            None => {\r
+                Ok(SignInResult::UserNotFound)\r
+            },\r
+        }\r
     }\r
 \r
-    pub fn authentication(&self, token: &str) -> Result<AuthenticationResult> {\r
-        todo!()\r
+    pub fn authentication(&self, token: &str, ip: &str, user_agent: &str) -> Result<AuthenticationResult> {\r
+        let mut con = self.pool.get()?;\r
+        let tx = con.transaction()?;\r
+        match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {\r
+            Ok((r.get::<&str, i32>("id")?, r.get::<&str, i32>("user_id")?))\r
+        }).optional()? {\r
+            Some((login_id, user_id)) => {\r
+                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])?;\r
+                tx.commit()?;\r
+                Ok(AuthenticationResult::Ok(user_id))\r
+            },\r
+            None =>\r
+                Ok(AuthenticationResult::NotValidToken)\r
+        }\r
     }\r
 \r
-    pub fn logout(&self, token: &str) -> Result<()> {\r
-        todo!()\r
+    pub fn sign_out(&self, token: &str) -> Result<()> {\r
+        let mut con = self.pool.get()?;\r
+        let tx = con.transaction()?;\r
+        match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {\r
+            Ok(r.get::<&str, i32>("id")?)\r
+        }).optional()? {\r
+            Some(login_id) => {\r
+                tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?;\r
+                tx.commit()?\r
+            },\r
+            None => (),\r
+        }\r
+        Ok(())\r
     }\r
 \r
     /// Execute a given SQL file.\r
@@ -252,6 +325,13 @@ impl Connection {
         let con = self.pool.get()?;\r
         con.execute(sql, params).map_err(DBError::from)\r
     }\r
+\r
+    // Return the token.\r
+    fn create_login_token(tx: &rusqlite::Transaction, user_id: i32, ip: &str, user_agent: &str) -> Result<String> {\r
+        let token = generate_token();\r
+        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])?;\r
+        Ok(token)\r
+    }\r
 }\r
 \r
 fn load_sql_file<P: AsRef<Path> + Display>(sql_file: P) -> Result<String> {\r
@@ -301,16 +381,185 @@ mod tests {
 \r
     #[test]\r
     fn sign_up_to_an_unvalidated_already_existing_user() -> Result<()> {\r
-        todo!()\r
+        let connection = Connection::new_in_memory()?;\r
+        let token = generate_token();\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
+                    :token\r
+                );", named_params! { ":token": token })?;\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_then_send_validation_at_time() -> Result<()> {\r
-        todo!()\r
+        let connection = Connection::new_in_memory()?;\r
+        let validation_token =\r
+            match connection.sign_up("12345", "paul@test.org")? {\r
+                SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.\r
+                other => panic!("{:?}", other),\r
+            };\r
+        match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {\r
+            ValidationResult::Ok(_, _) => (), // Nominal case.\r
+            other => panic!("{:?}", other),\r
+        }\r
+        Ok(())\r
     }\r
 \r
+    #[test]\r
     fn sign_up_then_send_validation_too_late() -> Result<()> {\r
-        todo!()\r
+        let connection = Connection::new_in_memory()?;\r
+        let validation_token =\r
+            match connection.sign_up_with_given_time("12345", "paul@test.org", Utc::now() - Duration::days(1))? {\r
+                SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.\r
+                other => panic!("{:?}", other),\r
+            };\r
+        match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {\r
+            ValidationResult::ValidationExpired => (), // Nominal case.\r
+            other => panic!("{:?}", other),\r
+        }\r
+        Ok(())\r
+    }\r
+\r
+    #[test]\r
+    fn sign_up_then_send_validation_with_bad_token() -> Result<()> {\r
+        let connection = Connection::new_in_memory()?;\r
+        let _validation_token =\r
+            match connection.sign_up("12345", "paul@test.org")? {\r
+                SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.\r
+                other => panic!("{:?}", other),\r
+            };\r
+        let random_token = generate_token();\r
+        match connection.validation(&random_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {\r
+            ValidationResult::UnknownUser => (), // Nominal case.\r
+            other => panic!("{:?}", other),\r
+        }\r
+        Ok(())\r
     }\r
 \r
-    //fn sign_up_then_send_validation_then_sign_in()\r
+    #[test]\r
+    fn sign_up_then_send_validation_then_sign_in() -> Result<()> {\r
+        let connection = Connection::new_in_memory()?;\r
+\r
+        let password = "12345";\r
+        let email = "paul@test.org";\r
+\r
+        // Sign up.\r
+        let validation_token =\r
+            match connection.sign_up(password, email)? {\r
+                SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.\r
+                other => panic!("{:?}", other),\r
+            };\r
+\r
+        // Validation.\r
+        match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? {\r
+            ValidationResult::Ok(_, _) => (),\r
+            other => panic!("{:?}", other),\r
+        };\r
+\r
+        // Sign in.\r
+        match connection.sign_in(password, email, "127.0.0.1", "Mozilla/5.0")? {\r
+            SignInResult::Ok(_, _) => (), // Nominal case.\r
+            other => panic!("{:?}", other),\r
+        }\r
+\r
+        Ok(())\r
+    }\r
+\r
+    #[test]\r
+    fn sign_up_then_send_validation_then_authentication() -> Result<()> {\r
+        let connection = Connection::new_in_memory()?;\r
+\r
+        let password = "12345";\r
+        let email = "paul@test.org";\r
+\r
+        // Sign up.\r
+        let validation_token =\r
+            match connection.sign_up(password, email)? {\r
+                SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.\r
+                other => panic!("{:?}", other),\r
+            };\r
+\r
+        // Validation.\r
+        let (authentication_token, user_id) = match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla")? {\r
+            ValidationResult::Ok(token, user_id) => (token, user_id),\r
+            other => panic!("{:?}", other),\r
+        };\r
+\r
+        // Check user login information.\r
+        let user_login_info_1 = connection.get_user_login_info(&authentication_token)?;\r
+        assert_eq!(user_login_info_1.ip, "127.0.0.1");\r
+        assert_eq!(user_login_info_1.user_agent, "Mozilla");\r
+\r
+        // Authentication.\r
+        let _user_id =\r
+            match connection.authentication(&authentication_token, "192.168.1.1", "Chrome")? {\r
+                AuthenticationResult::Ok(user_id) => user_id, // Nominal case.\r
+                other => panic!("{:?}", other),\r
+            };\r
+\r
+        // Check user login information.\r
+        let user_login_info_2 = connection.get_user_login_info(&authentication_token)?;\r
+        assert_eq!(user_login_info_2.ip, "192.168.1.1");\r
+        assert_eq!(user_login_info_2.user_agent, "Chrome");\r
+\r
+        Ok(())\r
+    }\r
+\r
+    #[test]\r
+    fn sign_up_then_send_validation_then_sign_out_then_sign_in() -> Result<()> {\r
+        let connection = Connection::new_in_memory()?;\r
+\r
+        let password = "12345";\r
+        let email = "paul@test.org";\r
+\r
+        // Sign up.\r
+        let validation_token =\r
+            match connection.sign_up(password, email)? {\r
+                SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case.\r
+                other => panic!("{:?}", other),\r
+            };\r
+\r
+        // Validation.\r
+        let (authentication_token_1, user_id_1) =\r
+            match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla")? {\r
+                ValidationResult::Ok(token, user_id) => (token, user_id),\r
+                other => panic!("{:?}", other),\r
+            };\r
+\r
+        // Check user login information.\r
+        let user_login_info_1 = connection.get_user_login_info(&authentication_token_1)?;\r
+        assert_eq!(user_login_info_1.ip, "127.0.0.1");\r
+        assert_eq!(user_login_info_1.user_agent, "Mozilla");\r
+\r
+        // Sign out.\r
+        connection.sign_out(&authentication_token_1)?;\r
+\r
+        // Sign in.\r
+        let (authentication_token_2, user_id_2) =\r
+            match connection.sign_in(password, email, "192.168.1.1", "Chrome")? {\r
+                SignInResult::Ok(token, user_id) => (token, user_id),\r
+                other => panic!("{:?}", other),\r
+            };\r
+\r
+        assert_eq!(user_id_1, user_id_2);\r
+        assert_ne!(authentication_token_1, authentication_token_2);\r
+\r
+        // Check user login information.\r
+        let user_login_info_2 = connection.get_user_login_info(&authentication_token_2)?;\r
+\r
+        assert_eq!(user_login_info_2.ip, "192.168.1.1");\r
+        assert_eq!(user_login_info_2.user_agent, "Chrome");\r
+\r
+        Ok(())\r
+    }\r
 }\r