+\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], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| {\r
+ Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?))\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
+ pub fn load_user(&self, user_id: i32) -> Result<User> {\r
+ let con = self.pool.get()?;\r
+ con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| {\r
+ Ok(User {\r
+ email: r.get("email")?,\r
+ })\r
+ }).map_err(DBError::from)\r
+ }\r
+\r
+ ///\r
+ pub fn sign_up(&self, email: &str, password: &str) -> Result<SignUpResult> {\r
+ self.sign_up_with_given_time(email, password, Utc::now())\r
+ }\r
+\r
+ fn sign_up_with_given_time(&self, email: &str, password: &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, email: &str, password: &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], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {\r
+ Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option<String>>("validation_token")?))\r
+ }).optional()? {\r
+ Some((id, stored_password, validation_token)) => {\r
+ if validation_token.is_some() {\r
+ Ok(SignInResult::AccountNotValidated)\r
+ } else 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::WrongPassword)\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> + fmt::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> + fmt::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