From: Greg Burri Date: Tue, 22 Nov 2022 16:03:52 +0000 (+0100) Subject: Sign up/in/out and authentication. X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=aedfae1d17d2fd39b3b1f4889723d627fcc79218;p=recipes.git Sign up/in/out and authentication. --- diff --git a/backend/sql/version_1.sql b/backend/sql/version_1.sql index 4457863..aaa8a9f 100644 --- a/backend/sql/version_1.sql +++ b/backend/sql/version_1.sql @@ -25,7 +25,7 @@ CREATE TABLE [UserLoginToken] ( [last_login_datetime] DATETIME, [token] TEXT NOT NULL, -- 24 alphanumeric character token. Can be stored in a cookie to be able to authenticate without a password. - [ip] INTEGER, + [ip] TEXT, -- Can be ipv4 or ipv6 [user_agent] TEXT, FOREIGN KEY([user_id]) REFERENCES [User]([id]) diff --git a/backend/src/db.rs b/backend/src/db.rs index 4ef37fe..28bf62c 100644 --- a/backend/src/db.rs +++ b/backend/src/db.rs @@ -2,14 +2,15 @@ use std::{fmt::Display, fs::{self, File}, path::Path, io::Read}; use itertools::Itertools; use chrono::{prelude::*, Duration}; -use rusqlite::{params, Params, OptionalExtension}; +use rusqlite::{named_params, OptionalExtension, params, Params}; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use rand::distributions::{Alphanumeric, DistString}; use crate::consts; -use crate::hash::hash; +use crate::hash::{hash, verify_password}; use crate::model; +use crate::user::*; const CURRENT_DB_VERSION: u32 = 1; @@ -50,20 +51,22 @@ pub enum SignUpResult { #[derive(Debug)] pub enum ValidationResult { + UnknownUser, ValidationExpired, - OK, + Ok(String, i32), // Returns token and user id. } #[derive(Debug)] pub enum SignInResult { - NotValidToken, - OK, + UserNotFound, + PasswordsDontMatch, + Ok(String, i32), // Returns token and user id. } #[derive(Debug)] pub enum AuthenticationResult { NotValidToken, - OK, + Ok(i32), // Returns user id. } #[derive(Clone)] @@ -92,6 +95,13 @@ impl Connection { Self::create_connection(SqliteConnectionManager::file(file)) } + fn create_connection(manager: SqliteConnectionManager) -> Result {; + let pool = r2d2::Pool::new(manager).unwrap(); + let connection = Connection { pool }; + connection.create_or_update()?; + Ok(connection) + } + /// Called after the connection has been established for creating or updating the database. /// The 'Version' table tracks the current state of the database. fn create_or_update(&self) -> Result<()> { @@ -111,7 +121,7 @@ impl Connection { } }; - while Connection::update_to_next_version(version, &tx)? { + while Self::update_to_next_version(version, &tx)? { version += 1; } @@ -120,13 +130,6 @@ impl Connection { Ok(()) } - fn create_connection(manager: SqliteConnectionManager) -> Result {; - let pool = r2d2::Pool::new(manager).unwrap(); - let connection = Connection { pool }; - connection.create_or_update()?; - Ok(connection) - } - fn update_to_next_version(current_version: u32, tx: &rusqlite::Transaction) -> Result { let next_version = current_version + 1; @@ -191,6 +194,17 @@ impl Connection { }).map_err(DBError::from) } + pub fn get_user_login_info(&self, token: &str) -> Result { + let con = self.pool.get()?; + con.query_row("SELECT [last_login_datetime], [ip], [user_agent] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { + Ok(UserLoginInfo { + last_login_datetime: r.get("last_login_datetime")?, + ip: r.get("ip")?, + user_agent: r.get("user_agent")?, + }) + }).map_err(DBError::from) + } + /// pub fn sign_up(&self, password: &str, email: &str) -> Result { self.sign_up_with_given_time(password, email, Utc::now()) @@ -223,20 +237,79 @@ impl Connection { Ok(SignUpResult::UserCreatedWaitingForValidation(token)) } - pub fn validation(&self, token: &str, validation_time: Duration) -> Result { - todo!() + pub fn validation(&self, token: &str, validation_time: Duration, ip: &str, user_agent: &str) -> Result { + let mut con = self.pool.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, i32>("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, password: &str, email: String) -> Result { - todo!() + pub fn sign_in(&self, password: &str, email: &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")?)) + }).optional()? { + Some((id, stored_password)) => { + 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) + } + }, + None => { + Ok(SignInResult::UserNotFound) + }, + } } - pub fn authentication(&self, token: &str) -> Result { - todo!() + pub fn authentication(&self, token: &str, ip: &str, user_agent: &str) -> Result { + let mut con = self.pool.get()?; + let tx = con.transaction()?; + match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { + Ok((r.get::<&str, i32>("id")?, r.get::<&str, i32>("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) + } } - pub fn logout(&self, token: &str) -> Result<()> { - todo!() + pub fn sign_out(&self, token: &str) -> Result<()> { + let mut con = self.pool.get()?; + let tx = con.transaction()?; + match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { + Ok(r.get::<&str, i32>("id")?) + }).optional()? { + Some(login_id) => { + tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?; + tx.commit()? + }, + None => (), + } + Ok(()) } /// Execute a given SQL file. @@ -252,6 +325,13 @@ impl Connection { let con = self.pool.get()?; con.execute(sql, params).map_err(DBError::from) } + + // Return the token. + fn create_login_token(tx: &rusqlite::Transaction, user_id: i32, 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) + } } fn load_sql_file + Display>(sql_file: P) -> Result { @@ -301,16 +381,185 @@ mod tests { #[test] fn sign_up_to_an_unvalidated_already_existing_user() -> Result<()> { - todo!() + let connection = Connection::new_in_memory()?; + let token = generate_token(); + connection.execute_sql(" + INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token]) + VALUES ( + 1, + 'paul@test.org', + 'paul', + '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY', + 0, + :token + );", named_params! { ":token": token })?; + match connection.sign_up("12345", "paul@test.org")? { + SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case. + other => panic!("{:?}", other), + } + Ok(()) } + #[test] fn sign_up_then_send_validation_at_time() -> Result<()> { - todo!() + let connection = Connection::new_in_memory()?; + let validation_token = + match connection.sign_up("12345", "paul@test.org")? { + 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), + } + Ok(()) } + #[test] fn sign_up_then_send_validation_too_late() -> Result<()> { - todo!() + 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))? { + 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), + } + Ok(()) + } + + #[test] + 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")? { + 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")? { + ValidationResult::UnknownUser => (), // Nominal case. + other => panic!("{:?}", other), + } + Ok(()) } - //fn sign_up_then_send_validation_then_sign_in() + #[test] + fn sign_up_then_send_validation_then_sign_in() -> Result<()> { + let connection = Connection::new_in_memory()?; + + let password = "12345"; + let email = "paul@test.org"; + + // Sign up. + let validation_token = + match connection.sign_up(password, email)? { + 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")? { + ValidationResult::Ok(_, _) => (), + other => panic!("{:?}", other), + }; + + // Sign in. + match connection.sign_in(password, email, "127.0.0.1", "Mozilla/5.0")? { + SignInResult::Ok(_, _) => (), // Nominal case. + other => panic!("{:?}", other), + } + + Ok(()) + } + + #[test] + fn sign_up_then_send_validation_then_authentication() -> Result<()> { + let connection = Connection::new_in_memory()?; + + let password = "12345"; + let email = "paul@test.org"; + + // Sign up. + let validation_token = + match connection.sign_up(password, email)? { + 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")? { + 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)?; + assert_eq!(user_login_info_1.ip, "127.0.0.1"); + assert_eq!(user_login_info_1.user_agent, "Mozilla"); + + // Authentication. + let _user_id = + match connection.authentication(&authentication_token, "192.168.1.1", "Chrome")? { + AuthenticationResult::Ok(user_id) => user_id, // Nominal case. + other => panic!("{:?}", other), + }; + + // Check user login information. + let user_login_info_2 = connection.get_user_login_info(&authentication_token)?; + assert_eq!(user_login_info_2.ip, "192.168.1.1"); + assert_eq!(user_login_info_2.user_agent, "Chrome"); + + Ok(()) + } + + #[test] + 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"; + + // Sign up. + let validation_token = + match connection.sign_up(password, email)? { + 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), + }; + + // Check user login information. + let user_login_info_1 = connection.get_user_login_info(&authentication_token_1)?; + assert_eq!(user_login_info_1.ip, "127.0.0.1"); + assert_eq!(user_login_info_1.user_agent, "Mozilla"); + + // Sign out. + connection.sign_out(&authentication_token_1)?; + + // Sign in. + let (authentication_token_2, user_id_2) = + match connection.sign_in(password, email, "192.168.1.1", "Chrome")? { + SignInResult::Ok(token, user_id) => (token, user_id), + other => panic!("{:?}", other), + }; + + assert_eq!(user_id_1, user_id_2); + assert_ne!(authentication_token_1, authentication_token_2); + + // Check user login information. + let user_login_info_2 = connection.get_user_login_info(&authentication_token_2)?; + + assert_eq!(user_login_info_2.ip, "192.168.1.1"); + assert_eq!(user_login_info_2.user_agent, "Chrome"); + + Ok(()) + } } diff --git a/backend/src/hash.rs b/backend/src/hash.rs index 3dd45a9..ecdaf45 100644 --- a/backend/src/hash.rs +++ b/backend/src/hash.rs @@ -13,4 +13,34 @@ pub fn hash(password: &str) -> Result> { let salt = SaltString::generate(&mut OsRng); let argon2 = Argon2::default(); argon2.hash_password(password.as_bytes(), &salt).map(|h| h.to_string()).map_err(|e| e.into()) +} + +pub fn verify_password(password: &str, hashed_password: &str) -> Result> { + let argon2 = Argon2::default(); + let parsed_hash = PasswordHash::new(hashed_password)?; + Ok(argon2.verify_password(password.as_bytes(), &parsed_hash).is_ok()) +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn simple_case() -> Result<(), Box> { + let password = "12345"; + let hash = hash(password)?; + println!("hash: {}", &hash); + assert!(verify_password(password, &hash)?); + assert!(!verify_password("54321", &hash)?); + Ok(()) + } + + #[test] + fn password_with_special_characters() -> Result<(), Box> { + let password = "éà ä_\\😺🎮🇨🇭"; + let hash = hash(password)?; + println!("hash: {}", &hash); + assert!(verify_password(password, &hash)?); + Ok(()) + } } \ No newline at end of file diff --git a/backend/src/main.rs b/backend/src/main.rs index 1fbfbc5..98bebc9 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -13,6 +13,7 @@ mod consts; mod db; mod hash; mod model; +mod user; #[derive(Template)] #[template(path = "home.html")] diff --git a/backend/src/user.rs b/backend/src/user.rs new file mode 100644 index 0000000..f6b308f --- /dev/null +++ b/backend/src/user.rs @@ -0,0 +1,11 @@ +use chrono::prelude::*; + +pub struct User { + +} + +pub struct UserLoginInfo { + pub last_login_datetime: DateTime, + pub ip: String, + pub user_agent: String, +} \ No newline at end of file