4e68de19b84a8a906042a829867e7e05e80110a5
[recipes.git] / backend / src / main.rs
1 use std::collections::HashMap;
2
3 use actix_files as fs;
4 use actix_web::{http::header, get, post, web, Responder, middleware, App, HttpServer, HttpRequest, HttpResponse, cookie::Cookie};
5 use askama_actix::{Template, TemplateToResponse};
6 use chrono::{prelude::*, Duration};
7 use clap::Parser;
8 use serde::Deserialize;
9 use log::{debug, error, log_enabled, info, Level};
10
11 use config::Config;
12 use user::User;
13
14 mod consts;
15 mod db;
16 mod hash;
17 mod model;
18 mod user;
19 mod email;
20 mod config;
21
22 const COOKIE_AUTH_TOKEN_NAME: &str = "auth_token";
23
24 ///// UTILS /////
25
26 fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
27 let ip =
28 match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
29 Some(v) => v.to_str().unwrap_or_default().to_string(),
30 None => req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default()
31 };
32
33 let user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default().to_string();
34
35 (ip, user_agent)
36 }
37
38 fn get_current_user(req: &HttpRequest, connection: &web::Data<db::Connection>) -> Option<User> {
39 let (client_ip, client_user_agent) = get_ip_and_user_agent(req);
40
41 match req.cookie(COOKIE_AUTH_TOKEN_NAME) {
42 Some(token_cookie) =>
43 match connection.authentication(token_cookie.value(), &client_ip, &client_user_agent) {
44 Ok(db::AuthenticationResult::NotValidToken) =>
45 // TODO: remove cookie?
46 None,
47 Ok(db::AuthenticationResult::Ok(user_id)) =>
48 match connection.load_user(user_id) {
49 Ok(user) =>
50 Some(user),
51 Err(error) => {
52 error!("Error during authentication: {}", error);
53 None
54 }
55 },
56 Err(error) => {
57 error!("Error during authentication: {}", error);
58 None
59 },
60 },
61 None => None
62 }
63 }
64
65 ///// HOME /////
66
67 #[derive(Template)]
68 #[template(path = "home.html")]
69 struct HomeTemplate {
70 user: Option<user::User>,
71 recipes: Vec<(i32, String)>,
72 }
73
74 #[get("/")]
75 async fn home_page(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
76 HomeTemplate { user: get_current_user(&req, &connection), recipes: connection.get_all_recipe_titles().unwrap_or_default() }
77 }
78
79 ///// VIEW RECIPE /////
80
81 #[derive(Template)]
82 #[template(path = "view_recipe.html")]
83 struct ViewRecipeTemplate {
84 user: Option<user::User>,
85 recipes: Vec<(i32, String)>,
86 current_recipe: model::Recipe,
87 }
88
89 #[get("/recipe/view/{id}")]
90 async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data<db::Connection>) -> impl Responder {
91 let (id,)= path.into_inner();
92 let recipes = connection.get_all_recipe_titles().unwrap_or_default();
93 let user = get_current_user(&req, &connection);
94
95 match connection.get_recipe(id) {
96 Ok(recipe) =>
97 ViewRecipeTemplate {
98 user,
99 recipes,
100 current_recipe: recipe,
101 }.to_response(),
102 Err(_error) =>
103 MessageTemplate {
104 user,
105 recipes,
106 message: format!("Unable to get recipe #{}", id),
107 }.to_response(),
108 }
109 }
110
111 ///// MESSAGE /////
112
113 #[derive(Template)]
114 #[template(path = "message.html")]
115 struct MessageTemplate {
116 user: Option<user::User>,
117 recipes: Vec<(i32, String)>,
118 message: String,
119 }
120
121 //// SIGN UP /////
122
123 #[derive(Template)]
124 #[template(path = "sign_up_form.html")]
125 struct SignUpFormTemplate {
126 user: Option<user::User>,
127 email: String,
128 message: String,
129 message_email: String,
130 message_password: String,
131 }
132
133 #[get("/signup")]
134 async fn sign_up_get(req: HttpRequest, query: web::Query<HashMap<String, String>>, connection: web::Data<db::Connection>) -> impl Responder {
135 SignUpFormTemplate { user: get_current_user(&req, &connection), email: String::new(), message: String::new(), message_email: String::new(), message_password: String::new() }
136 }
137
138 #[derive(Deserialize)]
139 struct SignUpFormData {
140 email: String,
141 password_1: String,
142 password_2: String,
143 }
144
145 enum SignUpError {
146 InvalidEmail,
147 PasswordsNotEqual,
148 InvalidPassword,
149 UserAlreadyExists,
150 DatabaseError,
151 UnableSendEmail,
152 }
153
154 #[post("/signup")]
155 async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connection: web::Data<db::Connection>, config: web::Data<Config>) -> impl Responder {
156 fn error_response(error: SignUpError, form: &web::Form<SignUpFormData>, user: Option<User>) -> HttpResponse {
157 SignUpFormTemplate {
158 user,
159 email: form.email.clone(),
160 message_email:
161 match error {
162 SignUpError::InvalidEmail => "Invalid email",
163 _ => "",
164 }.to_string(),
165 message_password:
166 match error {
167 SignUpError::PasswordsNotEqual => "Passwords don't match",
168 SignUpError::InvalidPassword => "Password must have at least eight characters",
169 _ => "",
170 }.to_string(),
171 message:
172 match error {
173 SignUpError::UserAlreadyExists => "This email is already taken",
174 SignUpError::DatabaseError => "Database error",
175 SignUpError::UnableSendEmail => "Unable to send the validation email",
176 _ => "",
177 }.to_string(),
178 }.to_response()
179 }
180
181 let user = get_current_user(&req, &connection);
182
183 // Validation of email and password.
184 if let common::utils::EmailValidation::NotValid = common::utils::validate_email(&form.email) {
185 return error_response(SignUpError::InvalidEmail, &form, user);
186 }
187
188 if form.password_1 != form.password_2 {
189 return error_response(SignUpError::PasswordsNotEqual, &form, user);
190 }
191
192 if let common::utils::PasswordValidation::TooShort = common::utils::validate_password(&form.password_1) {
193 return error_response(SignUpError::InvalidPassword, &form, user);
194 }
195
196 match connection.sign_up(&form.email, &form.password_1) {
197 Ok(db::SignUpResult::UserAlreadyExists) => {
198 error_response(SignUpError::UserAlreadyExists, &form, user)
199 },
200 Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => {
201 let url = {
202 let host = req.headers().get(header::HOST).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default();
203 let port: Option<i32> = 'p: {
204 let split_port: Vec<&str> = host.split(':').collect();
205 if split_port.len() == 2 {
206 if let Ok(p) = split_port[1].parse::<i32>() {
207 break 'p Some(p)
208 }
209 }
210 None
211 };
212 format!("http{}://{}", if port.is_some() && port.unwrap() != 443 { "" } else { "s" }, host)
213 };
214 match email::send_validation(&url, &form.email, &token, &config.smtp_login, &config.smtp_password) {
215 Ok(()) =>
216 HttpResponse::Found()
217 .insert_header((header::LOCATION, "/signup_check_email"))
218 .finish(),
219 Err(error) => {
220 error!("Email validation error: {}", error);
221 error_response(SignUpError::UnableSendEmail, &form, user)
222 },
223 }
224 },
225 Err(error) => {
226 error!("Signup database error: {}", error);
227 error_response(SignUpError::DatabaseError, &form, user)
228 },
229 }
230 }
231
232 #[get("/signup_check_email")]
233 async fn sign_up_check_email(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
234 let recipes = connection.get_all_recipe_titles().unwrap_or_default();
235 MessageTemplate {
236 user: get_current_user(&req, &connection),
237 recipes,
238 message: "An email has been sent, follow the link to validate your account.".to_string(),
239 }
240 }
241
242 #[get("/validation")]
243 async fn sign_up_validation(req: HttpRequest, query: web::Query<HashMap<String, String>>, connection: web::Data<db::Connection>) -> impl Responder {
244 let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
245 let user = get_current_user(&req, &connection);
246
247 let recipes = connection.get_all_recipe_titles().unwrap_or_default();
248 match query.get("token") {
249 Some(token) => {
250 match connection.validation(token, Duration::seconds(consts::VALIDATION_TOKEN_DURATION), &client_ip, &client_user_agent).unwrap() {
251 db::ValidationResult::Ok(token, user_id) => {
252 let cookie = Cookie::new(COOKIE_AUTH_TOKEN_NAME, token);
253 let user =
254 match connection.load_user(user_id) {
255 Ok(user) =>
256 Some(user),
257 Err(error) => {
258 error!("Error retrieving user by id: {}", error);
259 None
260 }
261 };
262
263 let mut response =
264 MessageTemplate {
265 user,
266 recipes,
267 message: "Email validation successful, your account has been created".to_string(),
268 }.to_response();
269
270 if let Err(error) = response.add_cookie(&cookie) {
271 error!("Unable to set cookie after validation: {}", error);
272 };
273
274 response
275 },
276 db::ValidationResult::ValidationExpired =>
277 MessageTemplate {
278 user,
279 recipes,
280 message: "The validation has expired. Try to sign up again.".to_string(),
281 }.to_response(),
282 db::ValidationResult::UnknownUser =>
283 MessageTemplate {
284 user,
285 recipes,
286 message: "Validation error.".to_string(),
287 }.to_response(),
288 }
289 },
290 None => {
291 MessageTemplate {
292 user,
293 recipes,
294 message: format!("No token provided"),
295 }.to_response()
296 },
297 }
298 }
299
300 ///// SIGN IN /////
301
302 #[derive(Template)]
303 #[template(path = "sign_in_form.html")]
304 struct SignInFormTemplate {
305 user: Option<user::User>,
306 email: String,
307 message: String,
308 }
309
310 #[get("/signin")]
311 async fn sign_in_get(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
312 SignInFormTemplate {
313 user: get_current_user(&req, &connection),
314 email: String::new(),
315 message: String::new(),
316 }
317 }
318
319 #[derive(Deserialize)]
320 struct SignInFormData {
321 email: String,
322 password: String,
323 }
324
325 enum SignInError {
326 AccountNotValidated,
327 AuthenticationFailed,
328 }
329
330 #[post("/signin")]
331 async fn sign_in_post(req: HttpRequest, form: web::Form<SignInFormData>, connection: web::Data<db::Connection>) -> impl Responder {
332 fn error_response(error: SignInError, form: &web::Form<SignInFormData>, user: Option<User>) -> HttpResponse {
333 SignInFormTemplate {
334 user,
335 email: form.email.clone(),
336 message:
337 match error {
338 SignInError::AccountNotValidated => "This account must be validated first",
339 SignInError::AuthenticationFailed => "Wrong email or password",
340 }.to_string(),
341 }.to_response()
342 }
343
344 let user = get_current_user(&req, &connection);
345 let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
346
347 match connection.sign_in(&form.email, &form.password, &client_ip, &client_user_agent) {
348 Ok(db::SignInResult::AccountNotValidated) =>
349 error_response(SignInError::AccountNotValidated, &form, user),
350 Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => {
351 error_response(SignInError::AuthenticationFailed, &form, user)
352 },
353 Ok(db::SignInResult::Ok(token, user_id)) => {
354 let cookie = Cookie::new(COOKIE_AUTH_TOKEN_NAME, token);
355 let mut response =
356 HttpResponse::Found()
357 .insert_header((header::LOCATION, "/"))
358 .finish();
359 if let Err(error) = response.add_cookie(&cookie) {
360 error!("Unable to set cookie after sign in: {}", error);
361 };
362 response
363 },
364 Err(error) => {
365 error!("Signin error: {}", error);
366 error_response(SignInError::AuthenticationFailed, &form, user)
367 },
368 }
369 }
370
371
372 ///// SIGN OUT /////
373
374 #[get("/signout")]
375 async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
376 let mut response =
377 HttpResponse::Found()
378 .insert_header((header::LOCATION, "/"))
379 .finish();
380
381 if let Some(token_cookie) = req.cookie(COOKIE_AUTH_TOKEN_NAME) {
382 if let Err(error) = connection.sign_out(token_cookie.value()) {
383 error!("Unable to sign out: {}", error);
384 };
385
386 if let Err(error) = response.add_removal_cookie(&Cookie::new(COOKIE_AUTH_TOKEN_NAME, "")) {
387 error!("Unable to set a removal cookie after sign out: {}", error);
388 };
389 };
390 response
391 }
392
393 async fn not_found(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
394 let recipes = connection.get_all_recipe_titles().unwrap_or_default();
395 MessageTemplate {
396 user: get_current_user(&req, &connection),
397 recipes,
398 message: "404: Not found".to_string(),
399 }
400 }
401
402 #[actix_web::main]
403 async fn main() -> std::io::Result<()> {
404 if process_args() { return Ok(()) }
405
406 std::env::set_var("RUST_LOG", "info,actix_web=info");
407 env_logger::init();
408
409 println!("Starting Recipes as web server...");
410
411 let config = web::Data::new(config::load());
412 let port = config.as_ref().port;
413
414 println!("Configuration: {:?}", config);
415
416 let db_connection = web::Data::new(db::Connection::new().unwrap());
417
418 let server =
419 HttpServer::new(move || {
420 App::new()
421 .wrap(middleware::Logger::default())
422 .wrap(middleware::Compress::default())
423 .app_data(db_connection.clone())
424 .app_data(config.clone())
425 .service(home_page)
426 .service(sign_up_get)
427 .service(sign_up_post)
428 .service(sign_up_check_email)
429 .service(sign_up_validation)
430 .service(sign_in_get)
431 .service(sign_in_post)
432 .service(sign_out)
433 .service(view_recipe)
434 .service(fs::Files::new("/static", "static"))
435 .default_service(web::to(not_found))
436 });
437
438 server.bind(&format!("0.0.0.0:{}", port))?.run().await
439 }
440
441 #[derive(Parser, Debug)]
442 struct Args {
443 #[arg(long)]
444 dbtest: bool
445 }
446
447 fn process_args() -> bool {
448 let args = Args::parse();
449
450 if args.dbtest {
451 match db::Connection::new() {
452 Ok(con) => {
453 if let Err(error) = con.execute_file("sql/data_test.sql") {
454 error!("{}", error);
455 }
456 // Set the creation datetime to 'now'.
457 con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap();
458 },
459 Err(error) => {
460 error!("Error: {}", error)
461 },
462 }
463
464 return true;
465 }
466
467 false
468 }