This commit is contained in:
Greg Burri 2022-11-26 20:22:45 +01:00
parent 45d4867cb3
commit b6235fb76c
12 changed files with 578 additions and 336 deletions

View file

@ -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::*;
@ -67,7 +67,8 @@ pub enum ValidationResult {
#[derive(Debug)]
pub enum SignInResult {
UserNotFound,
PasswordsDontMatch,
WrongPassword,
AccountNotValidated,
Ok(String, i32), // Returns token and user id.
}
@ -197,8 +198,8 @@ impl Connection {
pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {
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)
}
@ -213,6 +214,15 @@ impl Connection {
}).map_err(DBError::from)
}
pub fn load_user(&self, user_id: i32) -> Result<User> {
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, email: &str, password: &str) -> Result<SignUpResult> {
self.sign_up_with_given_time(email, password, Utc::now())
@ -268,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<SignInResult> {
pub fn sign_in(&self, email: &str, password: &str, ip: &str, user_agent: &str) -> Result<SignInResult> {
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<String>>("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 => {
@ -387,6 +399,26 @@ mod tests {
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()?;
@ -475,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),
}
@ -554,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),
};

View file

@ -1,8 +1,7 @@
use std::{string::String, env::consts::OS};
use std::{string::String};
use argon2::{
password_hash::{
Error,
rand_core::OsRng,
PasswordHash, PasswordHasher, PasswordVerifier, SaltString
},

View file

@ -1,13 +1,14 @@
use std::{collections::HashMap, net::ToSocketAddrs};
use std::collections::HashMap;
use actix_files as fs;
use actix_web::{http::header, get, post, web, Responder, middleware, App, HttpServer, HttpRequest, HttpResponse};
use actix_web::{http::header, get, post, web, Responder, middleware, App, HttpServer, HttpRequest, HttpResponse, cookie::Cookie};
use askama_actix::{Template, TemplateToResponse};
use chrono::{prelude::*, Duration};
use clap::Parser;
use serde::Deserialize;
use config::Config;
use user::User;
mod consts;
mod db;
@ -17,34 +18,97 @@ mod user;
mod email;
mod config;
const COOKIE_AUTH_TOKEN_NAME: &str = "auth_token";
///// UTILS /////
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
let user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default().to_string();
let ip = req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default();
(ip, user_agent)
}
fn get_current_user(req: &HttpRequest, connection: &web::Data<db::Connection>) -> Option<User> {
let (client_ip, client_user_agent) = get_ip_and_user_agent(req);
match req.cookie(COOKIE_AUTH_TOKEN_NAME) {
Some(token_cookie) =>
match connection.authentication(token_cookie.value(), &client_ip, &client_user_agent) {
Ok(db::AuthenticationResult::NotValidToken) =>
// TODO: remove cookie?
None,
Ok(db::AuthenticationResult::Ok(user_id)) =>
match connection.load_user(user_id) {
Ok(user) =>
Some(user),
Err(error) => {
eprintln!("Error during authentication: {:?}", error);
None
}
},
Err(error) => {
eprintln!("Error during authentication: {:?}", error);
None
},
},
None => None
}
}
///// HOME /////
#[derive(Template)]
#[template(path = "home.html")]
struct HomeTemplate {
user: Option<user::User>,
recipes: Vec<(i32, String)>,
}
#[derive(Template)]
#[template(path = "sign_in_form.html")]
struct SignInFormTemplate {
}
#[derive(Template)]
#[template(path = "view_recipe.html")]
struct ViewRecipeTemplate {
recipes: Vec<(i32, String)>,
current_recipe: model::Recipe,
}
#[derive(Template)]
#[template(path = "message.html")]
struct MessageTemplate {
recipes: Vec<(i32, String)>,
message: String,
}
#[get("/")]
async fn home_page(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
HomeTemplate { recipes: connection.get_all_recipe_titles().unwrap_or_default() }
HomeTemplate { user: get_current_user(&req, &connection), recipes: connection.get_all_recipe_titles().unwrap_or_default() }
}
///// VIEW RECIPE /////
#[derive(Template)]
#[template(path = "view_recipe.html")]
struct ViewRecipeTemplate {
user: Option<user::User>,
recipes: Vec<(i32, String)>,
current_recipe: model::Recipe,
}
#[get("/recipe/view/{id}")]
async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data<db::Connection>) -> impl Responder {
let (id,)= path.into_inner();
let recipes = connection.get_all_recipe_titles().unwrap_or_default();
let user = get_current_user(&req, &connection);
match connection.get_recipe(id) {
Ok(recipe) =>
ViewRecipeTemplate {
user,
recipes,
current_recipe: recipe,
}.to_response(),
Err(_error) =>
MessageTemplate {
user,
recipes,
message: format!("Unable to get recipe #{}", id),
}.to_response(),
}
}
///// MESSAGE /////
#[derive(Template)]
#[template(path = "message.html")]
struct MessageTemplate {
user: Option<user::User>,
recipes: Vec<(i32, String)>,
message: String,
}
//// SIGN UP /////
@ -52,16 +116,23 @@ async fn home_page(req: HttpRequest, connection: web::Data<db::Connection>) -> i
#[derive(Template)]
#[template(path = "sign_up_form.html")]
struct SignUpFormTemplate {
user: Option<user::User>,
email: String,
message: String,
message_email: String,
message_password: String,
}
impl SignUpFormTemplate {
fn new() -> Self {
SignUpFormTemplate { email: String::new(), message: String::new(), message_email: String::new(), message_password: String::new() }
}
#[get("/signup")]
async fn sign_up_get(req: HttpRequest, query: web::Query<HashMap<String, String>>, connection: web::Data<db::Connection>) -> impl Responder {
SignUpFormTemplate { user: get_current_user(&req, &connection), email: String::new(), message: String::new(), message_email: String::new(), message_password: String::new() }
}
#[derive(Deserialize)]
struct SignUpFormData {
email: String,
password_1: String,
password_2: String,
}
enum SignUpError {
@ -73,24 +144,13 @@ enum SignUpError {
UnableSendEmail,
}
#[get("/signup")]
async fn sign_up_get(req: HttpRequest, query: web::Query<HashMap<String, String>>, connection: web::Data<db::Connection>) -> impl Responder {
SignUpFormTemplate::new()
}
#[derive(Deserialize)]
struct SignUpFormData {
email: String,
password_1: String,
password_2: String,
}
#[post("/signup")]
async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connection: web::Data<db::Connection>, config: web::Data<Config>) -> impl Responder {
println!("Sign Up, email: {}, passwords: {}/{}", form.email, form.password_1, form.password_2);
println!("Sign up, email: {}, passwords: {}/{}", form.email, form.password_1, form.password_2);
fn error_response(error: SignUpError, form: &web::Form<SignUpFormData>) -> HttpResponse {
fn error_response(error: SignUpError, form: &web::Form<SignUpFormData>, user: Option<User>) -> HttpResponse {
SignUpFormTemplate {
user,
email: form.email.clone(),
message_email:
match error {
@ -113,22 +173,24 @@ async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connect
}.to_response()
}
let user = get_current_user(&req, &connection);
// Validation of email and password.
if let common::utils::EmailValidation::NotValid = common::utils::validate_email(&form.email) {
return error_response(SignUpError::InvalidEmail, &form);
return error_response(SignUpError::InvalidEmail, &form, user);
}
if form.password_1 != form.password_2 {
return error_response(SignUpError::PasswordsNotEqual, &form);
return error_response(SignUpError::PasswordsNotEqual, &form, user);
}
if let common::utils::PasswordValidation::TooShort = common::utils::validate_password(&form.password_1) {
return error_response(SignUpError::InvalidPassword, &form);
return error_response(SignUpError::InvalidPassword, &form, user);
}
match connection.sign_up(&form.email, &form.password_1) {
Ok(db::SignUpResult::UserAlreadyExists) => {
error_response(SignUpError::UserAlreadyExists, &form)
error_response(SignUpError::UserAlreadyExists, &form, user)
},
Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => {
let url = {
@ -151,21 +213,22 @@ async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connect
.finish(),
Err(error) => {
eprintln!("Email validation error: {:?}", error);
error_response(SignUpError::UnableSendEmail, &form)
error_response(SignUpError::UnableSendEmail, &form, user)
},
}
},
Err(error) => {
eprintln!("Signup database error: {:?}", error);
error_response(SignUpError::DatabaseError, &form)
error_response(SignUpError::DatabaseError, &form, user)
},
}
}
#[get("/signup_check_email")]
async fn sign_up_check_email(connection: web::Data<db::Connection>) -> impl Responder {
async fn sign_up_check_email(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
let recipes = connection.get_all_recipe_titles().unwrap_or_default();
MessageTemplate {
user: get_current_user(&req, &connection),
recipes,
message: "An email has been sent, follow the link to validate your account.".to_string(),
}
@ -173,89 +236,166 @@ async fn sign_up_check_email(connection: web::Data<db::Connection>) -> impl Resp
#[get("/validation")]
async fn sign_up_validation(req: HttpRequest, query: web::Query<HashMap<String, String>>, connection: web::Data<db::Connection>) -> impl Responder {
println!("req:\n{:#?}", req);
let client_user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default();
let client_ip = req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default();
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
let user = get_current_user(&req, &connection);
let recipes = connection.get_all_recipe_titles().unwrap_or_default();
match query.get("token") {
Some(token) => {
match connection.validation(token, Duration::seconds(consts::VALIDATION_TOKEN_DURATION), &client_ip, client_user_agent).unwrap() {
db::ValidationResult::Ok(token, user_id) =>
// TODO: set token to cookie.
MessageTemplate {
recipes,
message: "Email validation successful, your account has been created".to_string(),
},
match connection.validation(token, Duration::seconds(consts::VALIDATION_TOKEN_DURATION), &client_ip, &client_user_agent).unwrap() {
db::ValidationResult::Ok(token, user_id) => {
let cookie = Cookie::new(COOKIE_AUTH_TOKEN_NAME, token);
let user =
match connection.load_user(user_id) {
Ok(user) =>
Some(user),
Err(error) => {
eprintln!("Error retrieving user by id: {}", error);
None
}
};
let mut response =
MessageTemplate {
user,
recipes,
message: "Email validation successful, your account has been created".to_string(),
}.to_response();
if let Err(error) = response.add_cookie(&cookie) {
eprintln!("Unable to set cookie after validation: {:?}", error);
};
response
},
db::ValidationResult::ValidationExpired =>
MessageTemplate {
user,
recipes,
message: "The validation has expired. Try to sign up again.".to_string(),
},
}.to_response(),
db::ValidationResult::UnknownUser =>
MessageTemplate {
recipes,
message: "Validation error.".to_string(),
},
MessageTemplate {
user,
recipes,
message: "Validation error.".to_string(),
}.to_response(),
}
},
None => {
MessageTemplate {
user,
recipes,
message: format!("No token provided"),
}
}.to_response()
},
}
}
///// SIGN IN /////
#[get("/signinform")]
async fn sign_in_form(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
#[derive(Template)]
#[template(path = "sign_in_form.html")]
struct SignInFormTemplate {
user: Option<user::User>,
email: String,
message: String,
}
#[get("/signin")]
async fn sign_in_get(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
SignInFormTemplate {
user: get_current_user(&req, &connection),
email: String::new(),
message: String::new(),
}
}
#[derive(Deserialize)]
struct SignInFormData {
email: String,
password: String,
}
enum SignInError {
AccountNotValidated,
AuthenticationFailed,
}
#[post("/signin")]
async fn sign_in(req: HttpRequest) -> impl Responder {
"todo"
async fn sign_in_post(req: HttpRequest, form: web::Form<SignInFormData>, connection: web::Data<db::Connection>) -> impl Responder {
println!("Sign in, email: {}, password: {}", form.email, form.password);
fn error_response(error: SignInError, form: &web::Form<SignInFormData>, user: Option<User>) -> HttpResponse {
SignInFormTemplate {
user,
email: form.email.clone(),
message:
match error {
SignInError::AccountNotValidated => "This account must be validated first",
SignInError::AuthenticationFailed => "Wrong email or password",
}.to_string(),
}.to_response()
}
let user = get_current_user(&req, &connection);
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
match connection.sign_in(&form.email, &form.password, &client_ip, &client_user_agent) {
Ok(db::SignInResult::AccountNotValidated) =>
error_response(SignInError::AccountNotValidated, &form, user),
Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => {
error_response(SignInError::AuthenticationFailed, &form, user)
},
Ok(db::SignInResult::Ok(token, user_id)) => {
let cookie = Cookie::new(COOKIE_AUTH_TOKEN_NAME, token);
let mut response =
HttpResponse::Found()
.insert_header((header::LOCATION, "/"))
.finish();
if let Err(error) = response.add_cookie(&cookie) {
eprintln!("Unable to set cookie after sign in: {:?}", error);
};
response
},
Err(error) => {
eprintln!("Signin error: {:?}", error);
error_response(SignInError::AuthenticationFailed, &form, user)
},
}
}
#[get("/recipe/view/{id}")]
async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data<db::Connection>) -> impl Responder {
let (id,)= path.into_inner();
let recipes = connection.get_all_recipe_titles().unwrap_or_default();
println!("{:?}", recipes);
match connection.get_recipe(id) {
Ok(recipe) =>
ViewRecipeTemplate {
recipes,
current_recipe: recipe,
}.to_response(),
Err(_error) =>
MessageTemplate {
recipes,
message: format!("Unable to get recipe #{}", id),
}.to_response(),
}
///// SIGN OUT /////
#[get("/signout")]
async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
let mut response =
HttpResponse::Found()
.insert_header((header::LOCATION, "/"))
.finish();
if let Some(token_cookie) = req.cookie(COOKIE_AUTH_TOKEN_NAME) {
if let Err(error) = connection.sign_out(token_cookie.value()) {
eprintln!("Unable to sign out: {:?}", error);
};
if let Err(error) = response.add_removal_cookie(&Cookie::new(COOKIE_AUTH_TOKEN_NAME, "")) {
eprintln!("Unable to set a removal cookie after sign out: {:?}", error);
};
};
response
}
async fn not_found(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
let recipes = connection.get_all_recipe_titles().unwrap_or_default();
MessageTemplate {
user: get_current_user(&req, &connection),
recipes,
message: "404: Not found".to_string(),
}
}
fn get_exe_name() -> String {
let first_arg = std::env::args().nth(0).unwrap();
let sep: &[_] = &['\\', '/'];
first_arg[first_arg.rfind(sep).unwrap()+1..].to_string()
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
if process_args() { return Ok(()) }
@ -286,12 +426,12 @@ async fn main() -> std::io::Result<()> {
.service(sign_up_post)
.service(sign_up_check_email)
.service(sign_up_validation)
.service(sign_in_form)
.service(sign_in)
.service(sign_in_get)
.service(sign_in_post)
.service(sign_out)
.service(view_recipe)
.service(fs::Files::new("/static", "static"))
.default_service(web::to(not_found))
//.default_service(not_found)
});
server.bind(&format!("0.0.0.0:{}", port))?.run().await
@ -324,27 +464,4 @@ fn process_args() -> bool {
}
false
/*
fn print_usage() {
println!("Usage:");
println!(" {} [--help] [--test]", get_exe_name());
}
let args: Vec<String> = args().collect();
if args.iter().any(|arg| arg == "--help") {
print_usage();
return true
} else if args.iter().any(|arg| arg == "--test") {
match db::Connection::new() {
Ok(_) => (),
Err(error) => println!("Error: {:?}", error)
}
return true
}
false
*/
}

View file

@ -1,6 +1,7 @@
pub struct Recipe {
pub id: i32,
pub title: String,
pub description: Option<String>,
pub estimate_time: Option<i32>, // [min].
pub difficulty: Option<Difficulty>,
@ -9,10 +10,11 @@ pub struct Recipe {
}
impl Recipe {
pub fn new(id: i32, title: String) -> Recipe {
pub fn new(id: i32, title: String, description: Option<String>) -> Recipe {
Recipe {
id,
title,
description,
estimate_time: None,
difficulty: None,
process: Vec::new(),

View file

@ -1,7 +1,7 @@
use chrono::prelude::*;
pub struct User {
pub email: String,
}
pub struct UserLoginInfo {