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
};
21 fn get_ip_and_user_agent(req
: &HttpRequest
) -> (String
, String
) {
23 match req
.headers().get(consts
::REVERSE_PROXY_IP_HTTP_FIELD
) {
24 Some(v
) => v
.to_str().unwrap_or_default().to_string(),
25 None
=> req
.peer_addr().map(|addr
| addr
.ip().to_string()).unwrap_or_default()
28 let user_agent
= req
.headers().get(header
::USER_AGENT
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default().to_string();
33 async
fn get_current_user(req
: &HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> Option
<User
> {
34 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(req
);
36 match req
.cookie(consts
::COOKIE_AUTH_TOKEN_NAME
) {
38 match connection
.authentication_async(token_cookie
.value(), &client_ip
, &client_user_agent
).await
{
39 Ok(db
::AuthenticationResult
::NotValidToken
) =>
40 // TODO: remove cookie?
42 Ok(db
::AuthenticationResult
::Ok(user_id
)) =>
43 match connection
.load_user_async(user_id
).await
{
47 error!("Error during authentication: {}", error
);
52 error!("Error during authentication: {}", error
);
60 type Result
<T
> = std
::result
::Result
<T
, ServiceError
>;
65 pub struct ServiceError
{
66 status_code
: StatusCode
,
67 message
: Option
<String
>,
70 impl From
<asynchronous
::DBAsyncError
> for ServiceError
{
71 fn from(error
: asynchronous
::DBAsyncError
) -> Self {
73 status_code
: StatusCode
::INTERNAL_SERVER_ERROR
,
74 message
: Some(format!("{:?}", error
)),
79 impl From
<email
::Error
> for ServiceError
{
80 fn from(error
: email
::Error
) -> Self {
82 status_code
: StatusCode
::INTERNAL_SERVER_ERROR
,
83 message
: Some(format!("{:?}", error
)),
88 impl From
<actix_web
::error
::BlockingError
> for ServiceError
{
89 fn from(error
: actix_web
::error
::BlockingError
) -> Self {
91 status_code
: StatusCode
::INTERNAL_SERVER_ERROR
,
92 message
: Some(format!("{:?}", error
)),
97 impl std
::fmt
::Display
for ServiceError
{
98 fn fmt(&self, f
: &mut std
::fmt
::Formatter
<'_
>) -> std
::result
::Result
<(), std
::fmt
::Error
> {
99 if let Some(ref m
) = self.message
{
100 write!(f
, "**{}**\n\n", m
)?
;
102 write!(f
, "Code: {}", self.status_code
)
106 impl actix_web
::error
::ResponseError
for ServiceError
{
107 fn error_response(&self) -> HttpResponse
{
108 MessageBaseTemplate
{
109 message
: &self.to_string(),
113 fn status_code(&self) -> StatusCode
{
121 #[template(path = "home.html")]
122 struct HomeTemplate
{
124 recipes
: Vec
<(i64, String
)>,
125 current_recipe_id
: Option
<i64>,
129 pub async
fn home_page(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
130 let user
= get_current_user(&req
, connection
.clone()).await
;
131 let recipes
= connection
.get_all_recipe_titles_async().await?
;
133 Ok(HomeTemplate
{ user
, current_recipe_id
: None
, recipes
}.to_response())
136 ///// VIEW RECIPE /////
139 #[template(path = "view_recipe.html")]
140 struct ViewRecipeTemplate
{
142 recipes
: Vec
<(i64, String
)>,
143 current_recipe_id
: Option
<i64>,
144 current_recipe
: model
::Recipe
,
147 #[get("/recipe/view/{id}")]
148 pub async
fn view_recipe(req
: HttpRequest
, path
: web
::Path
<(i64,)>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
149 let (id
,)= path
.into_inner();
150 let user
= get_current_user(&req
, connection
.clone()).await
;
151 let recipes
= connection
.get_all_recipe_titles_async().await?
;
152 let recipe
= connection
.get_recipe_async(id
).await?
;
154 Ok(ViewRecipeTemplate
{
156 current_recipe_id
: Some(recipe
.id
),
158 current_recipe
: recipe
,
165 #[template(path = "message_base.html")]
166 struct MessageBaseTemplate
<'a
> {
171 #[template(path = "message.html")]
172 struct MessageTemplate
<'a
> {
180 #[template(path = "sign_up_form.html")]
181 struct SignUpFormTemplate
{
185 message_email
: String
,
186 message_password
: String
,
190 pub async
fn sign_up_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
191 let user
= get_current_user(&req
, connection
.clone()).await
;
192 SignUpFormTemplate
{ user
, email
: String
::new(), message
: String
::new(), message_email
: String
::new(), message_password
: String
::new() }
195 #[derive(Deserialize)]
196 pub struct SignUpFormData
{
212 pub async
fn sign_up_post(req
: HttpRequest
, form
: web
::Form
<SignUpFormData
>, connection
: web
::Data
<db
::Connection
>, config
: web
::Data
<Config
>) -> Result
<HttpResponse
> {
213 fn error_response(error
: SignUpError
, form
: &web
::Form
<SignUpFormData
>, user
: Option
<User
>) -> Result
<HttpResponse
> {
214 Ok(SignUpFormTemplate
{
216 email
: form
.email
.clone(),
219 SignUpError
::InvalidEmail
=> "Invalid email",
224 SignUpError
::PasswordsNotEqual
=> "Passwords don't match",
225 SignUpError
::InvalidPassword
=> "Password must have at least eight characters",
230 SignUpError
::UserAlreadyExists
=> "This email is already taken",
231 SignUpError
::DatabaseError
=> "Database error",
232 SignUpError
::UnableSendEmail
=> "Unable to send the validation email",
238 let user
= get_current_user(&req
, connection
.clone()).await
;
240 // Validation of email and password.
241 if let common
::utils
::EmailValidation
::NotValid
= common
::utils
::validate_email(&form
.email
) {
242 return error_response(SignUpError
::InvalidEmail
, &form
, user
);
245 if form
.password_1
!= form
.password_2
{
246 return error_response(SignUpError
::PasswordsNotEqual
, &form
, user
);
249 if let common
::utils
::PasswordValidation
::TooShort
= common
::utils
::validate_password(&form
.password_1
) {
250 return error_response(SignUpError
::InvalidPassword
, &form
, user
);
253 match connection
.sign_up_async(&form
.email
, &form
.password_1
).await
{
254 Ok(db
::SignUpResult
::UserAlreadyExists
) => {
255 error_response(SignUpError
::UserAlreadyExists
, &form
, user
)
257 Ok(db
::SignUpResult
::UserCreatedWaitingForValidation(token
)) => {
259 let host
= req
.headers().get(header
::HOST
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default();
260 let port
: Option
<u16> = 'p
: {
261 let split_port
: Vec
<&str> = host
.split('
:'
).collect();
262 if split_port
.len() == 2 {
263 if let Ok(p
) = split_port
[1].parse
::<u16>() {
269 format!("http{}://{}", if port
.is_some() && port
.unwrap() != 443 { "" } else { "s" }, host
)
272 let email
= form
.email
.clone();
274 match web
::block(move || { email
::send_validation(&url
, &email
, &token
, &config
.smtp_login
, &config
.smtp_password
) }).await?
{
276 Ok(HttpResponse
::Found()
277 .insert_header((header
::LOCATION
, "/signup_check_email"))
280 error!("Email validation error: {}", error
);
281 error_response(SignUpError
::UnableSendEmail
, &form
, user
)
286 error!("Signup database error: {}", error
);
287 error_response(SignUpError
::DatabaseError
, &form
, user
)
292 #[get("/signup_check_email")]
293 pub async
fn sign_up_check_email(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
294 let user
= get_current_user(&req
, connection
.clone()).await
;
297 message
: "An email has been sent, follow the link to validate your account.",
301 #[get("/validation")]
302 pub async
fn sign_up_validation(req
: HttpRequest
, query
: web
::Query
<HashMap
<String
, String
>>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
303 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
304 let user
= get_current_user(&req
, connection
.clone()).await
;
306 match query
.get("token") {
308 match connection
.validation_async(token
, Duration
::seconds(consts
::VALIDATION_TOKEN_DURATION
), &client_ip
, &client_user_agent
).await?
{
309 db
::ValidationResult
::Ok(token
, user_id
) => {
310 let cookie
= Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, token
);
312 match connection
.load_user(user_id
) {
316 error!("Error retrieving user by id: {}", error
);
324 message
: "Email validation successful, your account has been created",
327 if let Err(error
) = response
.add_cookie(&cookie
) {
328 error!("Unable to set cookie after validation: {}", error
);
333 db
::ValidationResult
::ValidationExpired
=>
336 message
: "The validation has expired. Try to sign up again.",
338 db
::ValidationResult
::UnknownUser
=>
341 message
: "Validation error.",
348 message
: &format!("No token provided"),
357 #[template(path = "sign_in_form.html")]
358 struct SignInFormTemplate
{
365 pub async
fn sign_in_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
366 let user
= get_current_user(&req
, connection
.clone()).await
;
369 email
: String
::new(),
370 message
: String
::new(),
374 #[derive(Deserialize)]
375 pub struct SignInFormData
{
382 AuthenticationFailed
,
386 pub async
fn sign_in_post(req
: HttpRequest
, form
: web
::Form
<SignInFormData
>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
387 fn error_response(error
: SignInError
, form
: &web
::Form
<SignInFormData
>, user
: Option
<User
>) -> Result
<HttpResponse
> {
388 Ok(SignInFormTemplate
{
390 email
: form
.email
.clone(),
393 SignInError
::AccountNotValidated
=> "This account must be validated first",
394 SignInError
::AuthenticationFailed
=> "Wrong email or password",
399 let user
= get_current_user(&req
, connection
.clone()).await
;
400 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
402 match connection
.sign_in_async(&form
.email
, &form
.password
, &client_ip
, &client_user_agent
).await
{
403 Ok(db
::SignInResult
::AccountNotValidated
) =>
404 error_response(SignInError
::AccountNotValidated
, &form
, user
),
405 Ok(db
::SignInResult
::UserNotFound
) | Ok(db
::SignInResult
::WrongPassword
) => {
406 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
408 Ok(db
::SignInResult
::Ok(token
, user_id
)) => {
409 let cookie
= Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, token
);
411 HttpResponse
::Found()
412 .insert_header((header
::LOCATION
, "/"))
414 if let Err(error
) = response
.add_cookie(&cookie
) {
415 error!("Unable to set cookie after sign in: {}", error
);
420 error!("Signin error: {}", error
);
421 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
430 pub async
fn sign_out(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
432 HttpResponse
::Found()
433 .insert_header((header
::LOCATION
, "/"))
436 if let Some(token_cookie
) = req
.cookie(consts
::COOKIE_AUTH_TOKEN_NAME
) {
437 if let Err(error
) = connection
.sign_out_async(token_cookie
.value()).await
{
438 error!("Unable to sign out: {}", error
);
441 if let Err(error
) = response
.add_removal_cookie(&Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, "")) {
442 error!("Unable to set a removal cookie after sign out: {}", error
);
448 pub async
fn not_found(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
449 let user
= get_current_user(&req
, connection
.clone()).await
;
452 message
: "404: Not found",