X-Git-Url: http://git.euphorik.ch/?p=recipes.git;a=blobdiff_plain;f=backend%2Fsrc%2Fdata%2Fdb.rs;fp=backend%2Fsrc%2Fdata%2Fdb.rs;h=10b6f31d7b5870ff0a707190c80dcef136b20dc8;hp=5652ff38aff4bb68748146f4838ad5884a001cc6;hb=0a1631e66c861de2799cd98fc93686ff121c9fce;hpb=cbe276fc0601041b13087a6ffd80c5b126dfbe59 diff --git a/backend/src/data/db.rs b/backend/src/data/db.rs index 5652ff3..10b6f31 100644 --- a/backend/src/data/db.rs +++ b/backend/src/data/db.rs @@ -1,16 +1,21 @@ -use std::{fmt, fs::{self, File}, path::Path, io::Read}; +use std::{ + fmt, + fs::{self, File}, + io::Read, + path::Path, +}; -use itertools::Itertools; use chrono::{prelude::*, Duration}; -use rusqlite::{named_params, OptionalExtension, params, Params}; +use itertools::Itertools; use r2d2::{Pool, PooledConnection}; use r2d2_sqlite::SqliteConnectionManager; use rand::distributions::{Alphanumeric, DistString}; +use rusqlite::{named_params, params, OptionalExtension, Params}; -use crate::{consts, user}; use crate::hash::{hash, verify_password}; use crate::model; use crate::user::*; +use crate::{consts, user}; const CURRENT_DB_VERSION: u32 = 1; @@ -28,15 +33,15 @@ impl fmt::Display for DBError { } } -impl std::error::Error for DBError { } +impl std::error::Error for DBError {} -impl From for DBError { +impl From for DBError { fn from(error: rusqlite::Error) -> Self { DBError::SqliteError(error) } } -impl From for DBError { +impl From for DBError { fn from(error: r2d2::Error) -> Self { DBError::R2d2Error(error) } @@ -79,7 +84,7 @@ pub enum AuthenticationResult { #[derive(Clone)] pub struct Connection { - pool: Pool + pool: Pool, } impl Connection { @@ -127,12 +132,18 @@ impl Connection { // Version 0 corresponds to an empty database. let mut version = { match tx.query_row( - "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'", + "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'", + [], + |row| row.get::(0), + ) { + Ok(_) => tx + .query_row( + "SELECT [version] FROM [Version] ORDER BY [id] DESC", [], - |row| row.get::(0) - ) { - Ok(_) => tx.query_row("SELECT [version] FROM [Version] ORDER BY [id] DESC", [], |row| row.get(0)).unwrap_or_default(), - Err(_) => 0 + |row| row.get(0), + ) + .unwrap_or_default(), + Err(_) => 0, } }; @@ -153,7 +164,12 @@ impl Connection { } fn update_version(to_version: u32, tx: &rusqlite::Transaction) -> Result<()> { - tx.execute("INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", [to_version]).map(|_| ()).map_err(DBError::from) + tx.execute( + "INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", + [to_version], + ) + .map(|_| ()) + .map_err(DBError::from) } fn ok(updated: bool) -> Result { @@ -173,11 +189,9 @@ impl Connection { } // Version 1 doesn't exist yet. - 2 => - ok(false), + 2 => ok(false), - v => - Err(DBError::UnsupportedVersion(v)), + v => Err(DBError::UnsupportedVersion(v)), } } @@ -186,10 +200,9 @@ impl Connection { let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?; - let titles: std::result::Result, rusqlite::Error> = - stmt.query_map([], |row| { - Ok((row.get("id")?, row.get("title")?)) - })?.collect(); + let titles: std::result::Result, rusqlite::Error> = stmt + .query_map([], |row| Ok((row.get("id")?, row.get("title")?)))? + .collect(); titles.map_err(DBError::from) } @@ -207,9 +220,18 @@ impl Connection { pub fn get_recipe(&self, id: i64) -> Result { let con = self.get()?; - con.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| { - Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?)) - }).map_err(DBError::from) + con.query_row( + "SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", + [id], + |row| { + Ok(model::Recipe::new( + row.get("id")?, + row.get("title")?, + row.get("description")?, + )) + }, + ) + .map_err(DBError::from) } pub fn get_user_login_info(&self, token: &str) -> Result { @@ -225,116 +247,185 @@ impl Connection { pub fn load_user(&self, user_id: i64) -> Result { let con = self.get()?; - con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| { - Ok(User { - email: r.get("email")?, - }) - }).map_err(DBError::from) + con.query_row( + "SELECT [email] FROM [User] WHERE [id] = ?1", + [user_id], + |r| { + Ok(User { + email: r.get("email")?, + }) + }, + ) + .map_err(DBError::from) } pub fn sign_up(&self, email: &str, password: &str) -> Result { self.sign_up_with_given_time(email, password, Utc::now()) } - fn sign_up_with_given_time(&self, email: &str, password: &str, datetime: DateTime) -> Result { + fn sign_up_with_given_time( + &self, + email: &str, + password: &str, + datetime: DateTime, + ) -> Result { let mut con = self.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, i64>("id")?, r.get::<&str, Option>("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 + let token = match tx + .query_row( + "SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", + [email], + |r| { + Ok(( + r.get::<&str, i64>("id")?, + r.get::<&str, Option>("validation_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 - }, - }; + ) + .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, ip: &str, user_agent: &str) -> Result { + pub fn validation( + &self, + token: &str, + validation_time: Duration, + ip: &str, + user_agent: &str, + ) -> Result { let mut con = self.get()?; let tx = con.transaction()?; - let user_id = - match tx.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token], |r| { - Ok((r.get::<&str, i64>("id")?, r.get::<&str, DateTime>("creation_datetime")?)) - }).optional()? { - Some((id, creation_datetime)) => { - if Utc::now() - creation_datetime > validation_time { - return Ok(ValidationResult::ValidationExpired) - } - tx.execute("UPDATE [User] SET [validation_token] = NULL WHERE [id] = ?1", [id])?; - id - }, - None => { - return Ok(ValidationResult::UnknownUser) + let user_id = match tx + .query_row( + "SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", + [token], + |r| { + Ok(( + r.get::<&str, i64>("id")?, + r.get::<&str, DateTime>("creation_datetime")?, + )) }, - }; + ) + .optional()? + { + Some((id, creation_datetime)) => { + if Utc::now() - creation_datetime > validation_time { + return Ok(ValidationResult::ValidationExpired); + } + tx.execute( + "UPDATE [User] SET [validation_token] = NULL WHERE [id] = ?1", + [id], + )?; + id + } + None => return Ok(ValidationResult::UnknownUser), + }; let token = Connection::create_login_token(&tx, user_id, ip, user_agent)?; tx.commit()?; Ok(ValidationResult::Ok(token, user_id)) } - pub fn sign_in(&self, email: &str, password: &str, ip: &str, user_agent: &str) -> Result { + pub fn sign_in( + &self, + email: &str, + password: &str, + ip: &str, + user_agent: &str, + ) -> Result { let mut con = self.get()?; let tx = con.transaction()?; - match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| { - Ok((r.get::<&str, i64>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option>("validation_token")?)) - }).optional()? { + match tx + .query_row( + "SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", + [email], + |r| { + Ok(( + r.get::<&str, i64>("id")?, + r.get::<&str, String>("password")?, + r.get::<&str, Option>("validation_token")?, + )) + }, + ) + .optional()? + { Some((id, stored_password, validation_token)) => { if validation_token.is_some() { Ok(SignInResult::AccountNotValidated) - } else if verify_password(password, &stored_password).map_err(DBError::from_dyn_error)? { + } else if verify_password(password, &stored_password) + .map_err(DBError::from_dyn_error)? + { let token = Connection::create_login_token(&tx, id, ip, user_agent)?; tx.commit()?; Ok(SignInResult::Ok(token, id)) } else { Ok(SignInResult::WrongPassword) } - }, - None => { - Ok(SignInResult::UserNotFound) - }, + } + None => Ok(SignInResult::UserNotFound), } } - pub fn authentication(&self, token: &str, ip: &str, user_agent: &str) -> Result { + pub fn authentication( + &self, + token: &str, + ip: &str, + user_agent: &str, + ) -> Result { let mut con = self.get()?; let tx = con.transaction()?; - match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { - Ok((r.get::<&str, i64>("id")?, r.get::<&str, i64>("user_id")?)) - }).optional()? { + match tx + .query_row( + "SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", + [token], + |r| Ok((r.get::<&str, i64>("id")?, r.get::<&str, i64>("user_id")?)), + ) + .optional()? + { Some((login_id, user_id)) => { 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])?; tx.commit()?; Ok(AuthenticationResult::Ok(user_id)) - }, - None => - Ok(AuthenticationResult::NotValidToken) + } + None => Ok(AuthenticationResult::NotValidToken), } } pub fn sign_out(&self, token: &str) -> Result<()> { let mut con = self.get()?; let tx = con.transaction()?; - match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { - Ok(r.get::<&str, i64>("id")?) - }).optional()? { + match tx + .query_row( + "SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", + [token], + |r| Ok(r.get::<&str, i64>("id")?), + ) + .optional()? + { Some(login_id) => { - tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?; + tx.execute( + "DELETE FROM [UserLoginToken] WHERE [id] = ?1", + params![login_id], + )?; tx.commit()? - }, + } None => (), } Ok(()) @@ -364,12 +455,22 @@ impl Connection { pub fn set_recipe_title(&self, recipe_id: i64, title: &str) -> Result<()> { let con = self.get()?; - con.execute("UPDATE [Recipe] SET [title] = ?2 WHERE [id] = ?1", params![recipe_id, title]).map(|_n| ()).map_err(DBError::from) + con.execute( + "UPDATE [Recipe] SET [title] = ?2 WHERE [id] = ?1", + params![recipe_id, title], + ) + .map(|_n| ()) + .map_err(DBError::from) } pub fn set_recipe_description(&self, recipe_id: i64, description: &str) -> Result<()> { let con = self.get()?; - con.execute("UPDATE [Recipe] SET [description] = ?2 WHERE [id] = ?1", params![recipe_id, description]).map(|_n| ()).map_err(DBError::from) + con.execute( + "UPDATE [Recipe] SET [description] = ?2 WHERE [id] = ?1", + params![recipe_id, description], + ) + .map(|_n| ()) + .map_err(DBError::from) } /// Execute a given SQL file. @@ -387,7 +488,12 @@ impl Connection { } // Return the token. - fn create_login_token(tx: &rusqlite::Transaction, user_id: i64, ip: &str, user_agent: &str) -> Result { + fn create_login_token( + tx: &rusqlite::Transaction, + user_id: i64, + ip: &str, + user_agent: &str, + ) -> Result { let token = generate_token(); 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])?; Ok(token) @@ -395,9 +501,21 @@ impl Connection { } fn load_sql_file + fmt::Display>(sql_file: P) -> Result { - 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(); - 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) } @@ -408,7 +526,7 @@ fn generate_token() -> String { #[cfg(test)] mod tests { use super::*; - use rusqlite::{Error, ErrorCode, ffi, types::Value}; + use rusqlite::{ffi, types::Value, Error, ErrorCode}; #[test] fn sign_up() -> Result<()> { @@ -484,12 +602,16 @@ mod tests { #[test] fn sign_up_then_send_validation_at_time() -> Result<()> { let connection = Connection::new_in_memory()?; - let validation_token = - match connection.sign_up("paul@atreides.com", "12345")? { - SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. - other => panic!("{:?}", other), - }; - match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? { + let validation_token = match connection.sign_up("paul@atreides.com", "12345")? { + SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. + other => panic!("{:?}", other), + }; + match connection.validation( + &validation_token, + Duration::hours(1), + "127.0.0.1", + "Mozilla/5.0", + )? { ValidationResult::Ok(_, _) => (), // Nominal case. other => panic!("{:?}", other), } @@ -499,12 +621,20 @@ mod tests { #[test] fn sign_up_then_send_validation_too_late() -> Result<()> { let connection = Connection::new_in_memory()?; - let validation_token = - match connection.sign_up_with_given_time("paul@atreides.com", "12345", Utc::now() - Duration::days(1))? { - SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. - other => panic!("{:?}", other), - }; - match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? { + let validation_token = match connection.sign_up_with_given_time( + "paul@atreides.com", + "12345", + Utc::now() - Duration::days(1), + )? { + SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. + other => panic!("{:?}", other), + }; + match connection.validation( + &validation_token, + Duration::hours(1), + "127.0.0.1", + "Mozilla/5.0", + )? { ValidationResult::ValidationExpired => (), // Nominal case. other => panic!("{:?}", other), } @@ -514,13 +644,17 @@ mod tests { #[test] fn sign_up_then_send_validation_with_bad_token() -> Result<()> { let connection = Connection::new_in_memory()?; - let _validation_token = - match connection.sign_up("paul@atreides.com", "12345")? { - SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. - other => panic!("{:?}", other), - }; + let _validation_token = match connection.sign_up("paul@atreides.com", "12345")? { + SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. + other => panic!("{:?}", other), + }; let random_token = generate_token(); - match connection.validation(&random_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? { + match connection.validation( + &random_token, + Duration::hours(1), + "127.0.0.1", + "Mozilla/5.0", + )? { ValidationResult::UnknownUser => (), // Nominal case. other => panic!("{:?}", other), } @@ -535,14 +669,18 @@ mod tests { let password = "12345"; // Sign up. - let validation_token = - match connection.sign_up(email, password)? { - SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. - other => panic!("{:?}", other), - }; + let validation_token = match connection.sign_up(email, password)? { + SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. + other => panic!("{:?}", other), + }; // Validation. - match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla/5.0")? { + match connection.validation( + &validation_token, + Duration::hours(1), + "127.0.0.1", + "Mozilla/5.0", + )? { ValidationResult::Ok(_, _) => (), other => panic!("{:?}", other), }; @@ -564,14 +702,18 @@ mod tests { let password = "12345"; // Sign up. - let validation_token = - match connection.sign_up(email, password)? { - SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. - other => panic!("{:?}", other), - }; + let validation_token = match connection.sign_up(email, password)? { + SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. + other => panic!("{:?}", other), + }; // Validation. - let (authentication_token, user_id) = match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla")? { + let (authentication_token, user_id) = match connection.validation( + &validation_token, + Duration::hours(1), + "127.0.0.1", + "Mozilla", + )? { ValidationResult::Ok(token, user_id) => (token, user_id), other => panic!("{:?}", other), }; @@ -604,18 +746,21 @@ mod tests { let password = "12345"; // Sign up. - let validation_token = - match connection.sign_up(email, password)? { - SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. - other => panic!("{:?}", other), - }; + let validation_token = match connection.sign_up(email, password)? { + SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. + other => panic!("{:?}", other), + }; // Validation. - let (authentication_token_1, user_id_1) = - match connection.validation(&validation_token, Duration::hours(1), "127.0.0.1", "Mozilla")? { - ValidationResult::Ok(token, user_id) => (token, user_id), - other => panic!("{:?}", other), - }; + let (authentication_token_1, user_id_1) = match connection.validation( + &validation_token, + Duration::hours(1), + "127.0.0.1", + "Mozilla", + )? { + ValidationResult::Ok(token, user_id) => (token, user_id), + other => panic!("{:?}", other), + }; // Check user login information. let user_login_info_1 = connection.get_user_login_info(&authentication_token_1)?; @@ -644,7 +789,6 @@ mod tests { Ok(()) } - #[test] fn create_a_new_recipe_then_update_its_title() -> Result<()> { let connection = Connection::new_in_memory()?; @@ -662,8 +806,17 @@ mod tests { )?; match connection.create_recipe(2) { - Err(DBError::SqliteError(Error::SqliteFailure(ffi::Error { code: ErrorCode::ConstraintViolation, extended_code: _ }, Some(_)))) => (), // Nominal case. - other => panic!("Creating a recipe with an inexistant user must fail: {:?}", other), + Err(DBError::SqliteError(Error::SqliteFailure( + ffi::Error { + code: ErrorCode::ConstraintViolation, + extended_code: _, + }, + Some(_), + ))) => (), // Nominal case. + other => panic!( + "Creating a recipe with an inexistant user must fail: {:?}", + other + ), } let recipe_id = connection.create_recipe(1)?;