1 use std
::collections
::HashMap
;
3 use actix_web
::{http
::{header
, header
::ContentType
, StatusCode
}, get
, post
, web
, Responder
, HttpRequest
, HttpResponse
, cookie
::Cookie
};
4 use askama_actix
::{Template
, TemplateToResponse
};
6 use serde
::Deserialize
;
7 use log
::{debug
, error
, log_enabled
, info
, Level
};
12 use crate::config
::Config
;
13 use crate::user
::User
;
15 use crate::data
::{db
, asynchronous
};
19 fn get_ip_and_user_agent(req
: &HttpRequest
) -> (String
, String
) {
21 match req
.headers().get(consts
::REVERSE_PROXY_IP_HTTP_FIELD
) {
22 Some(v
) => v
.to_str().unwrap_or_default().to_string(),
23 None
=> req
.peer_addr().map(|addr
| addr
.ip().to_string()).unwrap_or_default()
26 let user_agent
= req
.headers().get(header
::USER_AGENT
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default().to_string();
31 async
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(consts
::COOKIE_AUTH_TOKEN_NAME
) {
36 match connection
.authentication_async(token_cookie
.value(), &client_ip
, &client_user_agent
).await
{
37 Ok(db
::AuthenticationResult
::NotValidToken
) =>
38 // TODO: remove cookie?
40 Ok(db
::AuthenticationResult
::Ok(user_id
)) =>
41 match connection
.load_user_async(user_id
).await
{
45 error!("Error during authentication: {}", error
);
50 error!("Error during authentication: {}", error
);
58 type Result
<T
> = std
::result
::Result
<T
, ServiceError
>;
63 pub struct ServiceError
{
64 status_code
: StatusCode
,
65 message
: Option
<String
>,
68 impl From
<asynchronous
::DBAsyncError
> for ServiceError
{
69 fn from(error
: asynchronous
::DBAsyncError
) -> Self {
71 status_code
: StatusCode
::INTERNAL_SERVER_ERROR
,
72 message
: Some(format!("{:?}", error
)),
77 impl From
<email
::Error
> for ServiceError
{
78 fn from(error
: email
::Error
) -> Self {
80 status_code
: StatusCode
::INTERNAL_SERVER_ERROR
,
81 message
: Some(format!("{:?}", error
)),
86 impl From
<actix_web
::error
::BlockingError
> for ServiceError
{
87 fn from(error
: actix_web
::error
::BlockingError
) -> Self {
89 status_code
: StatusCode
::INTERNAL_SERVER_ERROR
,
90 message
: Some(format!("{:?}", error
)),
95 impl std
::fmt
::Display
for ServiceError
{
96 fn fmt(&self, f
: &mut std
::fmt
::Formatter
<'_
>) -> std
::result
::Result
<(), std
::fmt
::Error
> {
97 if let Some(ref m
) = self.message
{
98 write!(f
, "**{}**\n\n", m
)?
;
100 write!(f
, "Code: {}", self.status_code
)
104 impl actix_web
::error
::ResponseError
for ServiceError
{
105 fn error_response(&self) -> HttpResponse
{
106 MessageBaseTemplate
{
107 message
: &self.to_string(),
111 fn status_code(&self) -> StatusCode
{
119 #[template(path = "home.html")]
120 struct HomeTemplate
{
122 recipes
: Vec
<(i32, String
)>,
123 current_recipe_id
: Option
<i32>,
127 pub async
fn home_page(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
128 let user
= get_current_user(&req
, connection
.clone()).await
;
129 let recipes
= connection
.get_all_recipe_titles_async().await?
;
131 Ok(HomeTemplate
{ user
, current_recipe_id
: None
, recipes
}.to_response())
134 ///// VIEW RECIPE /////
137 #[template(path = "view_recipe.html")]
138 struct ViewRecipeTemplate
{
140 recipes
: Vec
<(i32, String
)>,
141 current_recipe_id
: Option
<i32>,
142 current_recipe
: model
::Recipe
,
145 #[get("/recipe/view/{id}")]
146 pub async
fn view_recipe(req
: HttpRequest
, path
: web
::Path
<(i32,)>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
147 let (id
,)= path
.into_inner();
148 let user
= get_current_user(&req
, connection
.clone()).await
;
149 let recipes
= connection
.get_all_recipe_titles_async().await?
;
150 let recipe
= connection
.get_recipe_async(id
).await?
;
152 Ok(ViewRecipeTemplate
{
154 current_recipe_id
: Some(recipe
.id
),
156 current_recipe
: recipe
,
163 #[template(path = "message_base.html")]
164 struct MessageBaseTemplate
<'a
> {
169 #[template(path = "message.html")]
170 struct MessageTemplate
<'a
> {
178 #[template(path = "sign_up_form.html")]
179 struct SignUpFormTemplate
{
183 message_email
: String
,
184 message_password
: String
,
188 pub async
fn sign_up_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
189 let user
= get_current_user(&req
, connection
.clone()).await
;
190 SignUpFormTemplate
{ user
, email
: String
::new(), message
: String
::new(), message_email
: String
::new(), message_password
: String
::new() }
193 #[derive(Deserialize)]
194 pub struct SignUpFormData
{
210 pub async
fn sign_up_post(req
: HttpRequest
, form
: web
::Form
<SignUpFormData
>, connection
: web
::Data
<db
::Connection
>, config
: web
::Data
<Config
>) -> Result
<HttpResponse
> {
211 fn error_response(error
: SignUpError
, form
: &web
::Form
<SignUpFormData
>, user
: Option
<User
>) -> Result
<HttpResponse
> {
212 Ok(SignUpFormTemplate
{
214 email
: form
.email
.clone(),
217 SignUpError
::InvalidEmail
=> "Invalid email",
222 SignUpError
::PasswordsNotEqual
=> "Passwords don't match",
223 SignUpError
::InvalidPassword
=> "Password must have at least eight characters",
228 SignUpError
::UserAlreadyExists
=> "This email is already taken",
229 SignUpError
::DatabaseError
=> "Database error",
230 SignUpError
::UnableSendEmail
=> "Unable to send the validation email",
236 let user
= get_current_user(&req
, connection
.clone()).await
;
238 // Validation of email and password.
239 if let common
::utils
::EmailValidation
::NotValid
= common
::utils
::validate_email(&form
.email
) {
240 return error_response(SignUpError
::InvalidEmail
, &form
, user
);
243 if form
.password_1
!= form
.password_2
{
244 return error_response(SignUpError
::PasswordsNotEqual
, &form
, user
);
247 if let common
::utils
::PasswordValidation
::TooShort
= common
::utils
::validate_password(&form
.password_1
) {
248 return error_response(SignUpError
::InvalidPassword
, &form
, user
);
251 match connection
.sign_up_async(&form
.email
, &form
.password_1
).await
{
252 Ok(db
::SignUpResult
::UserAlreadyExists
) => {
253 error_response(SignUpError
::UserAlreadyExists
, &form
, user
)
255 Ok(db
::SignUpResult
::UserCreatedWaitingForValidation(token
)) => {
257 let host
= req
.headers().get(header
::HOST
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default();
258 let port
: Option
<i32> = 'p
: {
259 let split_port
: Vec
<&str> = host
.split('
:'
).collect();
260 if split_port
.len() == 2 {
261 if let Ok(p
) = split_port
[1].parse
::<i32>() {
267 format!("http{}://{}", if port
.is_some() && port
.unwrap() != 443 { "" } else { "s" }, host
)
270 let email
= form
.email
.clone();
272 match web
::block(move || { email
::send_validation(&url
, &email
, &token
, &config
.smtp_login
, &config
.smtp_password
) }).await?
{
274 Ok(HttpResponse
::Found()
275 .insert_header((header
::LOCATION
, "/signup_check_email"))
278 error!("Email validation error: {}", error
);
279 error_response(SignUpError
::UnableSendEmail
, &form
, user
)
284 error!("Signup database error: {}", error
);
285 error_response(SignUpError
::DatabaseError
, &form
, user
)
290 #[get("/signup_check_email")]
291 pub async
fn sign_up_check_email(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
292 let user
= get_current_user(&req
, connection
.clone()).await
;
295 message
: "An email has been sent, follow the link to validate your account.",
299 #[get("/validation")]
300 pub async
fn sign_up_validation(req
: HttpRequest
, query
: web
::Query
<HashMap
<String
, String
>>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
301 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
302 let user
= get_current_user(&req
, connection
.clone()).await
;
304 match query
.get("token") {
306 match connection
.validation_async(token
, Duration
::seconds(consts
::VALIDATION_TOKEN_DURATION
), &client_ip
, &client_user_agent
).await?
{
307 db
::ValidationResult
::Ok(token
, user_id
) => {
308 let cookie
= Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, token
);
310 match connection
.load_user(user_id
) {
314 error!("Error retrieving user by id: {}", error
);
322 message
: "Email validation successful, your account has been created",
325 if let Err(error
) = response
.add_cookie(&cookie
) {
326 error!("Unable to set cookie after validation: {}", error
);
331 db
::ValidationResult
::ValidationExpired
=>
334 message
: "The validation has expired. Try to sign up again.",
336 db
::ValidationResult
::UnknownUser
=>
339 message
: "Validation error.",
346 message
: &format!("No token provided"),
355 #[template(path = "sign_in_form.html")]
356 struct SignInFormTemplate
{
363 pub async
fn sign_in_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
364 let user
= get_current_user(&req
, connection
.clone()).await
;
367 email
: String
::new(),
368 message
: String
::new(),
372 #[derive(Deserialize)]
373 pub struct SignInFormData
{
380 AuthenticationFailed
,
384 pub async
fn sign_in_post(req
: HttpRequest
, form
: web
::Form
<SignInFormData
>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
385 fn error_response(error
: SignInError
, form
: &web
::Form
<SignInFormData
>, user
: Option
<User
>) -> Result
<HttpResponse
> {
386 Ok(SignInFormTemplate
{
388 email
: form
.email
.clone(),
391 SignInError
::AccountNotValidated
=> "This account must be validated first",
392 SignInError
::AuthenticationFailed
=> "Wrong email or password",
397 let user
= get_current_user(&req
, connection
.clone()).await
;
398 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
400 match connection
.sign_in_async(&form
.email
, &form
.password
, &client_ip
, &client_user_agent
).await
{
401 Ok(db
::SignInResult
::AccountNotValidated
) =>
402 error_response(SignInError
::AccountNotValidated
, &form
, user
),
403 Ok(db
::SignInResult
::UserNotFound
) | Ok(db
::SignInResult
::WrongPassword
) => {
404 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
406 Ok(db
::SignInResult
::Ok(token
, user_id
)) => {
407 let cookie
= Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, token
);
409 HttpResponse
::Found()
410 .insert_header((header
::LOCATION
, "/"))
412 if let Err(error
) = response
.add_cookie(&cookie
) {
413 error!("Unable to set cookie after sign in: {}", error
);
418 error!("Signin error: {}", error
);
419 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
428 pub async
fn sign_out(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
430 HttpResponse
::Found()
431 .insert_header((header
::LOCATION
, "/"))
434 if let Some(token_cookie
) = req
.cookie(consts
::COOKIE_AUTH_TOKEN_NAME
) {
435 if let Err(error
) = connection
.sign_out_async(token_cookie
.value()).await
{
436 error!("Unable to sign out: {}", error
);
439 if let Err(error
) = response
.add_removal_cookie(&Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, "")) {
440 error!("Unable to set a removal cookie after sign out: {}", error
);
446 pub async
fn not_found(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
447 let user
= get_current_user(&req
, connection
.clone()).await
;
450 message
: "404: Not found",