X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=backend%2Fsrc%2Fmain.rs;h=4e68de19b84a8a906042a829867e7e05e80110a5;hb=8a3fef096d720666dc8a54789aee02250642d8a1;hp=4c0d6984969e313a9fadca55313bc4ff261172c3;hpb=3ebbe8172b0430bae5c554925a4582c9fec545f3;p=recipes.git diff --git a/backend/src/main.rs b/backend/src/main.rs index 4c0d698..4e68de1 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1,105 +1,467 @@ -use std::io::prelude::*; -use std::{fs::File, env::args}; +use std::collections::HashMap; use actix_files as fs; -use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpResponse, web::Query}; - -use askama::Template; -use listenfd::ListenFd; -use ron::de::from_reader; +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 log::{debug, error, log_enabled, info, Level}; -use itertools::Itertools; +use config::Config; +use user::User; mod consts; mod db; +mod hash; +mod model; +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 ip = + match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) { + Some(v) => v.to_str().unwrap_or_default().to_string(), + None => req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default() + }; + + let user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default().to_string(); + + (ip, user_agent) +} + +fn get_current_user(req: &HttpRequest, connection: &web::Data) -> Option { + 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) => { + error!("Error during authentication: {}", error); + None + } + }, + Err(error) => { + error!("Error during authentication: {}", error); + None + }, + }, + None => None + } +} + +///// HOME ///// + +#[derive(Template)] +#[template(path = "home.html")] +struct HomeTemplate { + user: Option, + recipes: Vec<(i32, String)>, +} + +#[get("/")] +async fn home_page(req: HttpRequest, connection: web::Data) -> impl Responder { + 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, + 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) -> 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, + recipes: Vec<(i32, String)>, + message: String, +} + +//// SIGN UP ///// + +#[derive(Template)] +#[template(path = "sign_up_form.html")] +struct SignUpFormTemplate { + user: Option, + email: String, + message: String, + message_email: String, + message_password: String, +} + +#[get("/signup")] +async fn sign_up_get(req: HttpRequest, query: web::Query>, connection: web::Data) -> 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 { + InvalidEmail, + PasswordsNotEqual, + InvalidPassword, + UserAlreadyExists, + DatabaseError, + UnableSendEmail, +} + +#[post("/signup")] +async fn sign_up_post(req: HttpRequest, form: web::Form, connection: web::Data, config: web::Data) -> impl Responder { + fn error_response(error: SignUpError, form: &web::Form, user: Option) -> HttpResponse { + SignUpFormTemplate { + user, + email: form.email.clone(), + message_email: + match error { + SignUpError::InvalidEmail => "Invalid email", + _ => "", + }.to_string(), + message_password: + match error { + SignUpError::PasswordsNotEqual => "Passwords don't match", + SignUpError::InvalidPassword => "Password must have at least eight characters", + _ => "", + }.to_string(), + message: + match error { + SignUpError::UserAlreadyExists => "This email is already taken", + SignUpError::DatabaseError => "Database error", + SignUpError::UnableSendEmail => "Unable to send the validation email", + _ => "", + }.to_string(), + }.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, user); + } + + if form.password_1 != form.password_2 { + 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, user); + } + + match connection.sign_up(&form.email, &form.password_1) { + Ok(db::SignUpResult::UserAlreadyExists) => { + error_response(SignUpError::UserAlreadyExists, &form, user) + }, + Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => { + let url = { + let host = req.headers().get(header::HOST).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default(); + let port: Option = 'p: { + let split_port: Vec<&str> = host.split(':').collect(); + if split_port.len() == 2 { + if let Ok(p) = split_port[1].parse::() { + break 'p Some(p) + } + } + None + }; + format!("http{}://{}", if port.is_some() && port.unwrap() != 443 { "" } else { "s" }, host) + }; + match email::send_validation(&url, &form.email, &token, &config.smtp_login, &config.smtp_password) { + Ok(()) => + HttpResponse::Found() + .insert_header((header::LOCATION, "/signup_check_email")) + .finish(), + Err(error) => { + error!("Email validation error: {}", error); + error_response(SignUpError::UnableSendEmail, &form, user) + }, + } + }, + Err(error) => { + error!("Signup database error: {}", error); + error_response(SignUpError::DatabaseError, &form, user) + }, + } +} + +#[get("/signup_check_email")] +async fn sign_up_check_email(req: HttpRequest, connection: web::Data) -> 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(), + } +} + +#[get("/validation")] +async fn sign_up_validation(req: HttpRequest, query: web::Query>, connection: web::Data) -> impl Responder { + 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) => { + let cookie = Cookie::new(COOKIE_AUTH_TOKEN_NAME, token); + let user = + match connection.load_user(user_id) { + Ok(user) => + Some(user), + Err(error) => { + error!("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) { + error!("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 { + user, + recipes, + message: "Validation error.".to_string(), + }.to_response(), + } + }, + None => { + MessageTemplate { + user, + recipes, + message: format!("No token provided"), + }.to_response() + }, + } +} + +///// SIGN IN ///// #[derive(Template)] -#[template(path = "main.html")] -struct MainTemplate<'a> { - test: &'a str, +#[template(path = "sign_in_form.html")] +struct SignInFormTemplate { + user: Option, + email: String, + message: String, +} + +#[get("/signin")] +async fn sign_in_get(req: HttpRequest, connection: web::Data) -> impl Responder { + SignInFormTemplate { + user: get_current_user(&req, &connection), + email: String::new(), + message: String::new(), + } } #[derive(Deserialize)] -pub struct Request { - m: Option +struct SignInFormData { + email: String, + password: String, +} + +enum SignInError { + AccountNotValidated, + AuthenticationFailed, } -fn main_page(query: Query) -> HttpResponse { +#[post("/signin")] +async fn sign_in_post(req: HttpRequest, form: web::Form, connection: web::Data) -> impl Responder { + fn error_response(error: SignInError, form: &web::Form, user: Option) -> 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 main_template = MainTemplate { test: &"*** test ***" }; + let user = get_current_user(&req, &connection); + let (client_ip, client_user_agent) = get_ip_and_user_agent(&req); - let s = main_template.render().unwrap(); - HttpResponse::Ok().content_type("text/html").body(s) + 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) { + error!("Unable to set cookie after sign in: {}", error); + }; + response + }, + Err(error) => { + error!("Signin error: {}", error); + error_response(SignInError::AuthenticationFailed, &form, user) + }, + } } -#[derive(Debug, Deserialize)] -struct Config { - port: u16 + +///// SIGN OUT ///// + +#[get("/signout")] +async fn sign_out(req: HttpRequest, connection: web::Data) -> 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()) { + error!("Unable to sign out: {}", error); + }; + + if let Err(error) = response.add_removal_cookie(&Cookie::new(COOKIE_AUTH_TOKEN_NAME, "")) { + error!("Unable to set a removal cookie after sign out: {}", error); + }; + }; + response } -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() +async fn not_found(req: HttpRequest, connection: web::Data) -> 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(), + } } -#[actix_rt::main] +#[actix_web::main] async fn main() -> std::io::Result<()> { if process_args() { return Ok(()) } + std::env::set_var("RUST_LOG", "info,actix_web=info"); + env_logger::init(); + println!("Starting Recipes as web server..."); - let config: Config = { - let f = File::open(consts::FILE_CONF).unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF)); - match from_reader(f) { - Ok(c) => c, - Err(e) => panic!("Failed to load config: {}", e) - } - }; + let config = web::Data::new(config::load()); + let port = config.as_ref().port; println!("Configuration: {:?}", config); - // let database_connection = db::create_or_update(); + let db_connection = web::Data::new(db::Connection::new().unwrap()); - std::env::set_var("RUST_LOG", "actix_web=info"); + let server = + HttpServer::new(move || { + App::new() + .wrap(middleware::Logger::default()) + .wrap(middleware::Compress::default()) + .app_data(db_connection.clone()) + .app_data(config.clone()) + .service(home_page) + .service(sign_up_get) + .service(sign_up_post) + .service(sign_up_check_email) + .service(sign_up_validation) + .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)) + }); - let mut listenfd = ListenFd::from_env(); - let mut server = - HttpServer::new( - || { - App::new() - .wrap(middleware::Compress::default()) - .service(web::resource("/").to(main_page)) - .service(fs::Files::new("/static", "static").show_files_listing()) - } - ); - - server = - if let Some(l) = listenfd.take_tcp_listener(0).unwrap() { - server.listen(l).unwrap() - } else { - server.bind(&format!("0.0.0.0:{}", config.port)).unwrap() - }; + server.bind(&format!("0.0.0.0:{}", port))?.run().await +} - server.run().await +#[derive(Parser, Debug)] +struct Args { + #[arg(long)] + dbtest: bool } fn process_args() -> bool { - fn print_usage() { - println!("Usage:"); - println!(" {} [--help] [--test]", get_exe_name()); - } + let args = Args::parse(); - let args: Vec = args().collect(); + if args.dbtest { + match db::Connection::new() { + Ok(con) => { + if let Err(error) = con.execute_file("sql/data_test.sql") { + error!("{}", error); + } + // Set the creation datetime to 'now'. + con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap(); + }, + Err(error) => { + error!("Error: {}", error) + }, + } - if args.iter().any(|arg| arg == "--help") { - print_usage(); - return true - } else if args.iter().any(|arg| arg == "--test") { - let db_connection = db::Connection::new(); - db_connection.create_or_update(); - return true + return true; } false