+\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, 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> + 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