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
;
9 use log
::{debug
, error
, log_enabled
, info
, Level
};
22 const COOKIE_AUTH_TOKEN_NAME
: &str = "auth_token";
26 fn get_ip_and_user_agent(req
: &HttpRequest
) -> (String
, String
) {
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()
33 let user_agent
= req
.headers().get(header
::USER_AGENT
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default().to_string();
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
);
41 match req
.cookie(COOKIE_AUTH_TOKEN_NAME
) {
43 match connection
.authentication(token_cookie
.value(), &client_ip
, &client_user_agent
) {
44 Ok(db
::AuthenticationResult
::NotValidToken
) =>
45 // TODO: remove cookie?
47 Ok(db
::AuthenticationResult
::Ok(user_id
)) =>
48 match connection
.load_user(user_id
) {
52 error!("Error during authentication: {}", error
);
57 error!("Error during authentication: {}", error
);
68 #[template(path = "home.html")]
70 user
: Option
<user
::User
>,
71 recipes
: Vec
<(i32, String
)>,
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() }
79 ///// VIEW RECIPE /////
82 #[template(path = "view_recipe.html")]
83 struct ViewRecipeTemplate
{
84 user
: Option
<user
::User
>,
85 recipes
: Vec
<(i32, String
)>,
86 current_recipe
: model
::Recipe
,
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
);
95 match connection
.get_recipe(id
) {
100 current_recipe
: recipe
,
106 message
: format!("Unable to get recipe #{}", id
),
114 #[template(path = "message.html")]
115 struct MessageTemplate
{
116 user
: Option
<user
::User
>,
117 recipes
: Vec
<(i32, String
)>,
124 #[template(path = "sign_up_form.html")]
125 struct SignUpFormTemplate
{
126 user
: Option
<user
::User
>,
129 message_email
: String
,
130 message_password
: String
,
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() }
138 #[derive(Deserialize)]
139 struct SignUpFormData
{
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
{
159 email
: form
.email
.clone(),
162 SignUpError
::InvalidEmail
=> "Invalid email",
167 SignUpError
::PasswordsNotEqual
=> "Passwords don't match",
168 SignUpError
::InvalidPassword
=> "Password must have at least eight characters",
173 SignUpError
::UserAlreadyExists
=> "This email is already taken",
174 SignUpError
::DatabaseError
=> "Database error",
175 SignUpError
::UnableSendEmail
=> "Unable to send the validation email",
181 let user
= get_current_user(&req
, &connection
);
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
);
188 if form
.password_1
!= form
.password_2
{
189 return error_response(SignUpError
::PasswordsNotEqual
, &form
, user
);
192 if let common
::utils
::PasswordValidation
::TooShort
= common
::utils
::validate_password(&form
.password_1
) {
193 return error_response(SignUpError
::InvalidPassword
, &form
, user
);
196 match connection
.sign_up(&form
.email
, &form
.password_1
) {
197 Ok(db
::SignUpResult
::UserAlreadyExists
) => {
198 error_response(SignUpError
::UserAlreadyExists
, &form
, user
)
200 Ok(db
::SignUpResult
::UserCreatedWaitingForValidation(token
)) => {
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>() {
212 format!("http{}://{}", if port
.is_some() && port
.unwrap() != 443 { "" } else { "s" }, host
)
214 match email
::send_validation(&url
, &form
.email
, &token
, &config
.smtp_login
, &config
.smtp_password
) {
216 HttpResponse
::Found()
217 .insert_header((header
::LOCATION
, "/signup_check_email"))
220 error!("Email validation error: {}", error
);
221 error_response(SignUpError
::UnableSendEmail
, &form
, user
)
226 error!("Signup database error: {}", error
);
227 error_response(SignUpError
::DatabaseError
, &form
, user
)
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();
236 user
: get_current_user(&req
, &connection
),
238 message
: "An email has been sent, follow the link to validate your account.".to_string(),
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
);
247 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
248 match query
.get("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
);
254 match connection
.load_user(user_id
) {
258 error!("Error retrieving user by id: {}", error
);
267 message
: "Email validation successful, your account has been created".to_string(),
270 if let Err(error
) = response
.add_cookie(&cookie
) {
271 error!("Unable to set cookie after validation: {}", error
);
276 db
::ValidationResult
::ValidationExpired
=>
280 message
: "The validation has expired. Try to sign up again.".to_string(),
282 db
::ValidationResult
::UnknownUser
=>
286 message
: "Validation error.".to_string(),
294 message
: format!("No token provided"),
303 #[template(path = "sign_in_form.html")]
304 struct SignInFormTemplate
{
305 user
: Option
<user
::User
>,
311 async
fn sign_in_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
313 user
: get_current_user(&req
, &connection
),
314 email
: String
::new(),
315 message
: String
::new(),
319 #[derive(Deserialize)]
320 struct SignInFormData
{
327 AuthenticationFailed
,
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
{
335 email
: form
.email
.clone(),
338 SignInError
::AccountNotValidated
=> "This account must be validated first",
339 SignInError
::AuthenticationFailed
=> "Wrong email or password",
344 let user
= get_current_user(&req
, &connection
);
345 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
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
)
353 Ok(db
::SignInResult
::Ok(token
, user_id
)) => {
354 let cookie
= Cookie
::new(COOKIE_AUTH_TOKEN_NAME
, token
);
356 HttpResponse
::Found()
357 .insert_header((header
::LOCATION
, "/"))
359 if let Err(error
) = response
.add_cookie(&cookie
) {
360 error!("Unable to set cookie after sign in: {}", error
);
365 error!("Signin error: {}", error
);
366 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
375 async
fn sign_out(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
377 HttpResponse
::Found()
378 .insert_header((header
::LOCATION
, "/"))
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
);
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
);
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();
396 user
: get_current_user(&req
, &connection
),
398 message
: "404: Not found".to_string(),
403 async
fn main() -> std
::io
::Result
<()> {
404 if process_args() { return Ok(()) }
406 std
::env
::set_var("RUST_LOG", "info,actix_web=info");
409 println!("Starting Recipes as web server...");
411 let config
= web
::Data
::new(config
::load());
412 let port
= config
.as_ref().port
;
414 println!("Configuration: {:?}", config
);
416 let db_connection
= web
::Data
::new(db
::Connection
::new().unwrap());
419 HttpServer
::new(move || {
421 .wrap(middleware
::Logger
::default())
422 .wrap(middleware
::Compress
::default())
423 .app_data(db_connection
.clone())
424 .app_data(config
.clone())
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
)
433 .service(view_recipe
)
434 .service(fs
::Files
::new("/static", "static"))
435 .default_service(web
::to(not_found
))
438 server
.bind(&format!("0.0.0.0:{}", port
))?
.run().await
441 #[derive(Parser, Debug)]
447 fn process_args() -> bool
{
448 let args
= Args
::parse();
451 match db
::Connection
::new() {
453 if let Err(error
) = con
.execute_file("sql/data_test.sql") {
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();
460 error!("Error: {}", error
)