X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=backend%2Fsrc%2Fdb.rs;h=e38aae7f2715174855c435c992ae7201d5eb8d7e;hb=b6235fb76ce82f96503cda83eebe8106320b2a0d;hp=28bf62c657725fd7fd3fb9297d0f35b4a562cfd4;hpb=aedfae1d17d2fd39b3b1f4889723d627fcc79218;p=recipes.git diff --git a/backend/src/db.rs b/backend/src/db.rs index 28bf62c..e38aae7 100644 --- a/backend/src/db.rs +++ b/backend/src/db.rs @@ -1,4 +1,4 @@ -use std::{fmt::Display, fs::{self, File}, path::Path, io::Read}; +use std::{fmt, fs::{self, File}, path::Path, io::Read}; use itertools::Itertools; use chrono::{prelude::*, Duration}; @@ -7,7 +7,7 @@ use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use rand::distributions::{Alphanumeric, DistString}; -use crate::consts; +use crate::{consts, user}; use crate::hash::{hash, verify_password}; use crate::model; use crate::user::*; @@ -22,6 +22,14 @@ pub enum DBError { Other(String), } +impl fmt::Display for DBError { + fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { + write!(f, "{:?}", self) + } +} + +impl std::error::Error for DBError { } + impl From for DBError { fn from(error: rusqlite::Error) -> Self { DBError::SqliteError(error) @@ -59,7 +67,8 @@ pub enum ValidationResult { #[derive(Debug)] pub enum SignInResult { UserNotFound, - PasswordsDontMatch, + WrongPassword, + AccountNotValidated, Ok(String, i32), // Returns token and user id. } @@ -95,7 +104,7 @@ impl Connection { Self::create_connection(SqliteConnectionManager::file(file)) } - fn create_connection(manager: SqliteConnectionManager) -> Result {; + fn create_connection(manager: SqliteConnectionManager) -> Result { let pool = r2d2::Pool::new(manager).unwrap(); let connection = Connection { pool }; connection.create_or_update()?; @@ -189,8 +198,8 @@ impl Connection { pub fn get_recipe(&self, id: i32) -> Result { let con = self.pool.get()?; - con.query_row("SELECT [id], [title] FROM [Recipe] WHERE [id] = ?1", [id], |row| { - Ok(model::Recipe::new(row.get(0)?, row.get(1)?)) + 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) } @@ -205,12 +214,21 @@ impl Connection { }).map_err(DBError::from) } + pub fn load_user(&self, user_id: i32) -> Result { + let con = self.pool.get()?; + 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, password: &str, email: &str) -> Result { - self.sign_up_with_given_time(password, email, Utc::now()) + 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, password: &str, email: &str, datetime: DateTime) -> Result { + fn sign_up_with_given_time(&self, email: &str, password: &str, datetime: DateTime) -> Result { let mut con = self.pool.get()?; let tx = con.transaction()?; let token = @@ -260,19 +278,21 @@ impl Connection { Ok(ValidationResult::Ok(token, user_id)) } - pub fn sign_in(&self, password: &str, email: &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.pool.get()?; let tx = con.transaction()?; - match tx.query_row("SELECT [id], [password] FROM [User] WHERE [email] = ?1", [email], |r| { - Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?)) + match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| { + Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option>("validation_token")?)) }).optional()? { - Some((id, stored_password)) => { - if verify_password(password, &stored_password).map_err(DBError::from_dyn_error)? { + 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)? { let token = Connection::create_login_token(&tx, id, ip, user_agent)?; tx.commit()?; Ok(SignInResult::Ok(token, id)) } else { - Ok(SignInResult::PasswordsDontMatch) + Ok(SignInResult::WrongPassword) } }, None => { @@ -313,7 +333,7 @@ impl Connection { } /// Execute a given SQL file. - pub fn execute_file + Display>(&self, file: P) -> Result<()> { + pub fn execute_file + fmt::Display>(&self, file: P) -> Result<()> { let con = self.pool.get()?; let sql = load_sql_file(file)?; con.execute_batch(&sql).map_err(DBError::from) @@ -334,7 +354,7 @@ impl Connection { } } -fn load_sql_file + Display>(sql_file: P) -> Result { +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 sql = String::new(); file.read_to_string(&mut sql).map_err(|err| DBError::Other(format!("Cannot read SQL file ({}) : {}", &sql_file, err.to_string())))?; @@ -352,7 +372,7 @@ mod tests { #[test] fn sign_up() -> Result<()> { let connection = Connection::new_in_memory()?; - match connection.sign_up("12345", "paul@test.org")? { + match connection.sign_up("paul@test.org", "12345")? { SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case. other => panic!("{:?}", other), } @@ -372,13 +392,33 @@ mod tests { 0, NULL );", [])?; - match connection.sign_up("12345", "paul@test.org")? { + match connection.sign_up("paul@test.org", "12345")? { SignUpResult::UserAlreadyExists => (), // Nominal case. other => panic!("{:?}", other), } Ok(()) } + #[test] + fn sign_up_and_sign_in_without_validation() -> Result<()> { + let connection = Connection::new_in_memory()?; + + let email = "paul@test.org"; + let password = "12345"; + + match connection.sign_up(email, password)? { + SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case. + other => panic!("{:?}", other), + } + + match connection.sign_in(email, password, "127.0.0.1", "Mozilla/5.0")? { + SignInResult::AccountNotValidated => (), // Nominal case. + other => panic!("{:?}", other), + } + + Ok(()) + } + #[test] fn sign_up_to_an_unvalidated_already_existing_user() -> Result<()> { let connection = Connection::new_in_memory()?; @@ -393,7 +433,7 @@ mod tests { 0, :token );", named_params! { ":token": token })?; - match connection.sign_up("12345", "paul@test.org")? { + match connection.sign_up("paul@test.org", "12345")? { SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case. other => panic!("{:?}", other), } @@ -404,7 +444,7 @@ mod tests { fn sign_up_then_send_validation_at_time() -> Result<()> { let connection = Connection::new_in_memory()?; let validation_token = - match connection.sign_up("12345", "paul@test.org")? { + match connection.sign_up("paul@test.org", "12345")? { SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. other => panic!("{:?}", other), }; @@ -419,7 +459,7 @@ mod tests { 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("12345", "paul@test.org", Utc::now() - Duration::days(1))? { + match connection.sign_up_with_given_time("paul@test.org", "12345", Utc::now() - Duration::days(1))? { SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. other => panic!("{:?}", other), }; @@ -434,7 +474,7 @@ mod tests { fn sign_up_then_send_validation_with_bad_token() -> Result<()> { let connection = Connection::new_in_memory()?; let _validation_token = - match connection.sign_up("12345", "paul@test.org")? { + match connection.sign_up("paul@test.org", "12345")? { SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. other => panic!("{:?}", other), }; @@ -450,12 +490,12 @@ mod tests { fn sign_up_then_send_validation_then_sign_in() -> Result<()> { let connection = Connection::new_in_memory()?; - let password = "12345"; let email = "paul@test.org"; + let password = "12345"; // Sign up. let validation_token = - match connection.sign_up(password, email)? { + match connection.sign_up(email, password)? { SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. other => panic!("{:?}", other), }; @@ -467,7 +507,7 @@ mod tests { }; // Sign in. - match connection.sign_in(password, email, "127.0.0.1", "Mozilla/5.0")? { + match connection.sign_in(email, password, "127.0.0.1", "Mozilla/5.0")? { SignInResult::Ok(_, _) => (), // Nominal case. other => panic!("{:?}", other), } @@ -479,12 +519,12 @@ mod tests { fn sign_up_then_send_validation_then_authentication() -> Result<()> { let connection = Connection::new_in_memory()?; - let password = "12345"; let email = "paul@test.org"; + let password = "12345"; // Sign up. let validation_token = - match connection.sign_up(password, email)? { + match connection.sign_up(email, password)? { SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. other => panic!("{:?}", other), }; @@ -519,12 +559,12 @@ mod tests { fn sign_up_then_send_validation_then_sign_out_then_sign_in() -> Result<()> { let connection = Connection::new_in_memory()?; - let password = "12345"; let email = "paul@test.org"; + let password = "12345"; // Sign up. let validation_token = - match connection.sign_up(password, email)? { + match connection.sign_up(email, password)? { SignUpResult::UserCreatedWaitingForValidation(token) => token, // Nominal case. other => panic!("{:?}", other), }; @@ -546,7 +586,7 @@ mod tests { // Sign in. let (authentication_token_2, user_id_2) = - match connection.sign_in(password, email, "192.168.1.1", "Chrome")? { + match connection.sign_in(email, password, "192.168.1.1", "Chrome")? { SignInResult::Ok(token, user_id) => (token, user_id), other => panic!("{:?}", other), };