+++ /dev/null
-use std::{fmt::Display, fs::{self, File}, path::Path, io::Read};\r
-\r
-use itertools::Itertools;\r
-use chrono::{prelude::*, Duration};\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, verify_password};\r
-use crate::model;\r
-use crate::user::*;\r
-\r
-const CURRENT_DB_VERSION: u32 = 1;\r
-\r
-#[derive(Debug)]\r
-pub enum DBError {\r
- SqliteError(rusqlite::Error),\r
- R2d2Error(r2d2::Error),\r
- UnsupportedVersion(u32),\r
- Other(String),\r
-}\r
-\r
-impl From<rusqlite::Error> for DBError {\r
- fn from(error: rusqlite::Error) -> Self {\r
- DBError::SqliteError(error)\r
- }\r
-}\r
-\r
-impl From<r2d2::Error> for DBError {\r
- fn from(error: r2d2::Error) -> Self {\r
- DBError::R2d2Error(error)\r
- }\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
- UnknownUser,\r
- ValidationExpired,\r
- Ok(String, i32), // Returns token and user id.\r
-}\r
-\r
-#[derive(Debug)]\r
-pub enum SignInResult {\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(i32), // Returns user id.\r
-}\r
-\r
-#[derive(Clone)]\r
-pub struct Connection {\r
- //con: rusqlite::Connection\r
- pool: Pool<SqliteConnectionManager>\r
-}\r
-\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
- pub fn new_in_memory() -> Result<Connection> {\r
- Self::create_connection(SqliteConnectionManager::memory())\r
- }\r
-\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
- 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
- // Check the Database version.\r
- let mut con = self.pool.get()?;\r
- let tx = con.transaction()?;\r
-\r
- // Version 0 corresponds to an empty database.\r
- let mut version = {\r
- match tx.query_row(\r
- "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",\r
- [],\r
- |row| row.get::<usize, String>(0)\r
- ) {\r
- Ok(_) => tx.query_row("SELECT [version] FROM [Version] ORDER BY [id] DESC", [], |row| row.get(0)).unwrap_or_default(),\r
- Err(_) => 0\r
- }\r
- };\r
-\r
- while Self::update_to_next_version(version, &tx)? {\r
- version += 1;\r
- }\r
-\r
- tx.commit()?;\r
-\r
- Ok(())\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
- if next_version <= CURRENT_DB_VERSION {\r
- println!("Update to version {}...", next_version);\r
- }\r
-\r
- fn update_version(to_version: u32, tx: &rusqlite::Transaction) -> Result<()> {\r
- tx.execute("INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", [to_version]).map(|_| ()).map_err(DBError::from)\r
- }\r
-\r
- fn ok(updated: bool) -> Result<bool> {\r
- if updated {\r
- println!("Version updated");\r
- }\r
- Ok(updated)\r
- }\r
-\r
- match next_version {\r
- 1 => {\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
- }\r
-\r
- // Version 1 doesn't exist yet.\r
- 2 =>\r
- ok(false),\r
-\r
- v =>\r
- Err(DBError::UnsupportedVersion(v)),\r
- }\r
- }\r
-\r
- pub fn get_all_recipe_titles(&self) -> Result<Vec<(i32, String)>> {\r
- let con = self.pool.get()?;\r
- let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;\r
- let titles =\r
- stmt.query_map([], |row| {\r
- Ok((row.get(0)?, row.get(1)?))\r
- })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.\r
- 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
- let recipes =\r
- stmt.query_map([], |row| {\r
- 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
- pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {\r
- let con = self.pool.get()?;\r
- con.query_row("SELECT [id], [title] FROM [Recipe] WHERE [id] = ?1", [id], |row| {\r
- Ok(model::Recipe::new(row.get(0)?, row.get(1)?))\r
- }).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
- }\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, 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: &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, 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 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
- 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
- // 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
- 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
-}\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
- 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
- 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
- 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
- #[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