1 use std
::collections
::HashMap
;
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
};
8 use serde
::Deserialize
;
21 const COOKIE_AUTH_TOKEN_NAME
: &str = "auth_token";
25 fn get_ip_and_user_agent(req
: &HttpRequest
) -> (String
, String
) {
26 let user_agent
= req
.headers().get(header
::USER_AGENT
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default().to_string();
27 let ip
= req
.peer_addr().map(|addr
| addr
.ip().to_string()).unwrap_or_default();
31 fn get_current_user(req
: &HttpRequest
, connection
: &web
::Data
<db
::Connection
>) -> Option
<User
> {
32 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(req
);
34 match req
.cookie(COOKIE_AUTH_TOKEN_NAME
) {
36 match connection
.authentication(token_cookie
.value(), &client_ip
, &client_user_agent
) {
37 Ok(db
::AuthenticationResult
::NotValidToken
) =>
38 // TODO: remove cookie?
40 Ok(db
::AuthenticationResult
::Ok(user_id
)) =>
41 match connection
.load_user(user_id
) {
45 eprintln!("Error during authentication: {:?}", error
);
50 eprintln!("Error during authentication: {:?}", error
);
61 #[template(path = "home.html")]
63 user
: Option
<user
::User
>,
64 recipes
: Vec
<(i32, String
)>,
68 async
fn home_page(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
69 HomeTemplate
{ user
: get_current_user(&req
, &connection
), recipes
: connection
.get_all_recipe_titles().unwrap_or_default() }
72 ///// VIEW RECIPE /////
75 #[template(path = "view_recipe.html")]
76 struct ViewRecipeTemplate
{
77 user
: Option
<user
::User
>,
78 recipes
: Vec
<(i32, String
)>,
79 current_recipe
: model
::Recipe
,
82 #[get("/recipe/view/{id}")]
83 async
fn view_recipe(req
: HttpRequest
, path
: web
::Path
<(i32,)>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
84 let (id
,)= path
.into_inner();
85 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
86 let user
= get_current_user(&req
, &connection
);
88 match connection
.get_recipe(id
) {
93 current_recipe
: recipe
,
99 message
: format!("Unable to get recipe #{}", id
),
107 #[template(path = "message.html")]
108 struct MessageTemplate
{
109 user
: Option
<user
::User
>,
110 recipes
: Vec
<(i32, String
)>,
117 #[template(path = "sign_up_form.html")]
118 struct SignUpFormTemplate
{
119 user
: Option
<user
::User
>,
122 message_email
: String
,
123 message_password
: String
,
127 async
fn sign_up_get(req
: HttpRequest
, query
: web
::Query
<HashMap
<String
, String
>>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
128 SignUpFormTemplate
{ user
: get_current_user(&req
, &connection
), email
: String
::new(), message
: String
::new(), message_email
: String
::new(), message_password
: String
::new() }
131 #[derive(Deserialize)]
132 struct SignUpFormData
{
148 async
fn sign_up_post(req
: HttpRequest
, form
: web
::Form
<SignUpFormData
>, connection
: web
::Data
<db
::Connection
>, config
: web
::Data
<Config
>) -> impl Responder
{
149 println!("Sign up, email: {}, passwords: {}/{}", form
.email
, form
.password_1
, form
.password_2
);
151 fn error_response(error
: SignUpError
, form
: &web
::Form
<SignUpFormData
>, user
: Option
<User
>) -> HttpResponse
{
154 email
: form
.email
.clone(),
157 SignUpError
::InvalidEmail
=> "Invalid email",
162 SignUpError
::PasswordsNotEqual
=> "Passwords don't match",
163 SignUpError
::InvalidPassword
=> "Password must have at least eight characters",
168 SignUpError
::UserAlreadyExists
=> "This email is already taken",
169 SignUpError
::DatabaseError
=> "Database error",
170 SignUpError
::UnableSendEmail
=> "Unable to send the validation email",
176 let user
= get_current_user(&req
, &connection
);
178 // Validation of email and password.
179 if let common
::utils
::EmailValidation
::NotValid
= common
::utils
::validate_email(&form
.email
) {
180 return error_response(SignUpError
::InvalidEmail
, &form
, user
);
183 if form
.password_1
!= form
.password_2
{
184 return error_response(SignUpError
::PasswordsNotEqual
, &form
, user
);
187 if let common
::utils
::PasswordValidation
::TooShort
= common
::utils
::validate_password(&form
.password_1
) {
188 return error_response(SignUpError
::InvalidPassword
, &form
, user
);
191 match connection
.sign_up(&form
.email
, &form
.password_1
) {
192 Ok(db
::SignUpResult
::UserAlreadyExists
) => {
193 error_response(SignUpError
::UserAlreadyExists
, &form
, user
)
195 Ok(db
::SignUpResult
::UserCreatedWaitingForValidation(token
)) => {
197 let host
= req
.headers().get(header
::HOST
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default();
198 let port
: Option
<i32> = 'p
: {
199 let split_port
: Vec
<&str> = host
.split('
:'
).collect();
200 if split_port
.len() == 2 {
201 if let Ok(p
) = split_port
[1].parse
::<i32>() {
207 format!("http{}://{}", if port
.is_some() && port
.unwrap() != 443 { "" } else { "s" }, host
)
209 match email
::send_validation(&url
, &form
.email
, &token
, &config
.smtp_login
, &config
.smtp_password
) {
211 HttpResponse
::Found()
212 .insert_header((header
::LOCATION
, "/signup_check_email"))
215 eprintln!("Email validation error: {:?}", error
);
216 error_response(SignUpError
::UnableSendEmail
, &form
, user
)
221 eprintln!("Signup database error: {:?}", error
);
222 error_response(SignUpError
::DatabaseError
, &form
, user
)
227 #[get("/signup_check_email")]
228 async
fn sign_up_check_email(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
229 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
231 user
: get_current_user(&req
, &connection
),
233 message
: "An email has been sent, follow the link to validate your account.".to_string(),
237 #[get("/validation")]
238 async
fn sign_up_validation(req
: HttpRequest
, query
: web
::Query
<HashMap
<String
, String
>>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
239 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
240 let user
= get_current_user(&req
, &connection
);
242 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
243 match query
.get("token") {
245 match connection
.validation(token
, Duration
::seconds(consts
::VALIDATION_TOKEN_DURATION
), &client_ip
, &client_user_agent
).unwrap() {
246 db
::ValidationResult
::Ok(token
, user_id
) => {
247 let cookie
= Cookie
::new(COOKIE_AUTH_TOKEN_NAME
, token
);
249 match connection
.load_user(user_id
) {
253 eprintln!("Error retrieving user by id: {}", error
);
262 message
: "Email validation successful, your account has been created".to_string(),
265 if let Err(error
) = response
.add_cookie(&cookie
) {
266 eprintln!("Unable to set cookie after validation: {:?}", error
);
271 db
::ValidationResult
::ValidationExpired
=>
275 message
: "The validation has expired. Try to sign up again.".to_string(),
277 db
::ValidationResult
::UnknownUser
=>
281 message
: "Validation error.".to_string(),
289 message
: format!("No token provided"),
298 #[template(path = "sign_in_form.html")]
299 struct SignInFormTemplate
{
300 user
: Option
<user
::User
>,
306 async
fn sign_in_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
308 user
: get_current_user(&req
, &connection
),
309 email
: String
::new(),
310 message
: String
::new(),
314 #[derive(Deserialize)]
315 struct SignInFormData
{
322 AuthenticationFailed
,
326 async
fn sign_in_post(req
: HttpRequest
, form
: web
::Form
<SignInFormData
>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
327 println!("Sign in, email: {}, password: {}", form
.email
, form
.password
);
329 fn error_response(error
: SignInError
, form
: &web
::Form
<SignInFormData
>, user
: Option
<User
>) -> HttpResponse
{
332 email
: form
.email
.clone(),
335 SignInError
::AccountNotValidated
=> "This account must be validated first",
336 SignInError
::AuthenticationFailed
=> "Wrong email or password",
341 let user
= get_current_user(&req
, &connection
);
342 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
344 match connection
.sign_in(&form
.email
, &form
.password
, &client_ip
, &client_user_agent
) {
345 Ok(db
::SignInResult
::AccountNotValidated
) =>
346 error_response(SignInError
::AccountNotValidated
, &form
, user
),
347 Ok(db
::SignInResult
::UserNotFound
) | Ok(db
::SignInResult
::WrongPassword
) => {
348 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
350 Ok(db
::SignInResult
::Ok(token
, user_id
)) => {
351 let cookie
= Cookie
::new(COOKIE_AUTH_TOKEN_NAME
, token
);
353 HttpResponse
::Found()
354 .insert_header((header
::LOCATION
, "/"))
356 if let Err(error
) = response
.add_cookie(&cookie
) {
357 eprintln!("Unable to set cookie after sign in: {:?}", error
);
362 eprintln!("Signin error: {:?}", error
);
363 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
372 async
fn sign_out(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
374 HttpResponse
::Found()
375 .insert_header((header
::LOCATION
, "/"))
378 if let Some(token_cookie
) = req
.cookie(COOKIE_AUTH_TOKEN_NAME
) {
379 if let Err(error
) = connection
.sign_out(token_cookie
.value()) {
380 eprintln!("Unable to sign out: {:?}", error
);
383 if let Err(error
) = response
.add_removal_cookie(&Cookie
::new(COOKIE_AUTH_TOKEN_NAME
, "")) {
384 eprintln!("Unable to set a removal cookie after sign out: {:?}", error
);
390 async
fn not_found(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
391 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
393 user
: get_current_user(&req
, &connection
),
395 message
: "404: Not found".to_string(),
400 async
fn main() -> std
::io
::Result
<()> {
401 if process_args() { return Ok(()) }
403 std
::env
::set_var("RUST_LOG", "actix_web=debug");
406 println!("Starting Recipes as web server...");
408 let config
= web
::Data
::new(config
::load());
409 let port
= config
.as_ref().port
;
411 println!("Configuration: {:?}", config
);
413 let db_connection
= web
::Data
::new(db
::Connection
::new().unwrap());
415 std
::env
::set_var("RUST_LOG", "actix_web=info");
418 HttpServer
::new(move || {
420 .wrap(middleware
::Logger
::default())
421 .wrap(middleware
::Compress
::default())
422 .app_data(db_connection
.clone())
423 .app_data(config
.clone())
425 .service(sign_up_get
)
426 .service(sign_up_post
)
427 .service(sign_up_check_email
)
428 .service(sign_up_validation
)
429 .service(sign_in_get
)
430 .service(sign_in_post
)
432 .service(view_recipe
)
433 .service(fs
::Files
::new("/static", "static"))
434 .default_service(web
::to(not_found
))
437 server
.bind(&format!("0.0.0.0:{}", port
))?
.run().await
440 #[derive(Parser, Debug)]
446 fn process_args() -> bool
{
447 let args
= Args
::parse();
450 match db
::Connection
::new() {
452 if let Err(error
) = con
.execute_file("sql/data_test.sql") {
453 println!("Error: {:?}", error
);
455 // Set the creation datetime to 'now'.
456 con
.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc
::now()]).unwrap();
459 println!("Error: {:?}", error
)