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 From
<ron
::error
::SpannedError
> for ServiceError
{
98 fn from(error
: ron
::error
::SpannedError
) -> Self {
100 status_code
: StatusCode
::INTERNAL_SERVER_ERROR
,
101 message
: Some(format!("{:?}", error
)),
106 impl std
::fmt
::Display
for ServiceError
{
107 fn fmt(&self, f
: &mut std
::fmt
::Formatter
<'_
>) -> std
::result
::Result
<(), std
::fmt
::Error
> {
108 if let Some(ref m
) = self.message
{
109 write!(f
, "**{}**\n\n", m
)?
;
111 write!(f
, "Code: {}", self.status_code
)
115 impl actix_web
::error
::ResponseError
for ServiceError
{
116 fn error_response(&self) -> HttpResponse
{
117 MessageBaseTemplate
{
118 message
: &self.to_string(),
122 fn status_code(&self) -> StatusCode
{
130 #[template(path = "home.html")]
131 struct HomeTemplate
{
133 recipes
: Vec
<(i64, String
)>,
134 current_recipe_id
: Option
<i64>,
138 pub async
fn home_page(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
139 let user
= get_current_user(&req
, connection
.clone()).await
;
140 let recipes
= connection
.get_all_recipe_titles_async().await?
;
142 Ok(HomeTemplate
{ user
, current_recipe_id
: None
, recipes
}.to_response())
145 ///// VIEW RECIPE /////
148 #[template(path = "view_recipe.html")]
149 struct ViewRecipeTemplate
{
151 recipes
: Vec
<(i64, String
)>,
152 current_recipe_id
: Option
<i64>,
153 current_recipe
: model
::Recipe
,
156 #[get("/recipe/view/{id}")]
157 pub async
fn view_recipe(req
: HttpRequest
, path
: web
::Path
<(i64,)>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
158 let (id
,)= path
.into_inner();
159 let user
= get_current_user(&req
, connection
.clone()).await
;
160 let recipes
= connection
.get_all_recipe_titles_async().await?
;
161 let recipe
= connection
.get_recipe_async(id
).await?
;
163 Ok(ViewRecipeTemplate
{
165 current_recipe_id
: Some(recipe
.id
),
167 current_recipe
: recipe
,
171 ///// EDIT RECIPE /////
174 #[template(path = "edit_recipe.html")]
175 struct EditRecipeTemplate
{
177 recipes
: Vec
<(i64, String
)>,
178 current_recipe_id
: Option
<i64>,
179 current_recipe
: model
::Recipe
,
182 #[get("/recipe/edit/{id}")]
183 pub async
fn edit_recipe(req
: HttpRequest
, path
: web
::Path
<(i64,)>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
184 let (id
,)= path
.into_inner();
185 let user
= get_current_user(&req
, connection
.clone()).await
;
186 let recipes
= connection
.get_all_recipe_titles_async().await?
;
187 let recipe
= connection
.get_recipe_async(id
).await?
;
189 Ok(EditRecipeTemplate
{
191 current_recipe_id
: Some(recipe
.id
),
193 current_recipe
: recipe
,
200 #[template(path = "message_base.html")]
201 struct MessageBaseTemplate
<'a
> {
206 #[template(path = "message.html")]
207 struct MessageTemplate
<'a
> {
215 #[template(path = "sign_up_form.html")]
216 struct SignUpFormTemplate
{
220 message_email
: String
,
221 message_password
: String
,
225 pub async
fn sign_up_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
226 let user
= get_current_user(&req
, connection
.clone()).await
;
227 SignUpFormTemplate
{ user
, email
: String
::new(), message
: String
::new(), message_email
: String
::new(), message_password
: String
::new() }
230 #[derive(Deserialize)]
231 pub struct SignUpFormData
{
247 pub async
fn sign_up_post(req
: HttpRequest
, form
: web
::Form
<SignUpFormData
>, connection
: web
::Data
<db
::Connection
>, config
: web
::Data
<Config
>) -> Result
<HttpResponse
> {
248 fn error_response(error
: SignUpError
, form
: &web
::Form
<SignUpFormData
>, user
: Option
<User
>) -> Result
<HttpResponse
> {
249 Ok(SignUpFormTemplate
{
251 email
: form
.email
.clone(),
254 SignUpError
::InvalidEmail
=> "Invalid email",
259 SignUpError
::PasswordsNotEqual
=> "Passwords don't match",
260 SignUpError
::InvalidPassword
=> "Password must have at least eight characters",
265 SignUpError
::UserAlreadyExists
=> "This email is already taken",
266 SignUpError
::DatabaseError
=> "Database error",
267 SignUpError
::UnableSendEmail
=> "Unable to send the validation email",
273 let user
= get_current_user(&req
, connection
.clone()).await
;
275 // Validation of email and password.
276 if let common
::utils
::EmailValidation
::NotValid
= common
::utils
::validate_email(&form
.email
) {
277 return error_response(SignUpError
::InvalidEmail
, &form
, user
);
280 if form
.password_1
!= form
.password_2
{
281 return error_response(SignUpError
::PasswordsNotEqual
, &form
, user
);
284 if let common
::utils
::PasswordValidation
::TooShort
= common
::utils
::validate_password(&form
.password_1
) {
285 return error_response(SignUpError
::InvalidPassword
, &form
, user
);
288 match connection
.sign_up_async(&form
.email
, &form
.password_1
).await
{
289 Ok(db
::SignUpResult
::UserAlreadyExists
) => {
290 error_response(SignUpError
::UserAlreadyExists
, &form
, user
)
292 Ok(db
::SignUpResult
::UserCreatedWaitingForValidation(token
)) => {
294 let host
= req
.headers().get(header
::HOST
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default();
295 let port
: Option
<u16> = 'p
: {
296 let split_port
: Vec
<&str> = host
.split('
:'
).collect();
297 if split_port
.len() == 2 {
298 if let Ok(p
) = split_port
[1].parse
::<u16>() {
304 format!("http{}://{}", if port
.is_some() && port
.unwrap() != 443 { "" } else { "s" }, host
)
307 let email
= form
.email
.clone();
309 match web
::block(move || { email
::send_validation(&url
, &email
, &token
, &config
.smtp_login
, &config
.smtp_password
) }).await?
{
311 Ok(HttpResponse
::Found()
312 .insert_header((header
::LOCATION
, "/signup_check_email"))
315 error!("Email validation error: {}", error
);
316 error_response(SignUpError
::UnableSendEmail
, &form
, user
)
321 error!("Signup database error: {}", error
);
322 error_response(SignUpError
::DatabaseError
, &form
, user
)
327 #[get("/signup_check_email")]
328 pub async
fn sign_up_check_email(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
329 let user
= get_current_user(&req
, connection
.clone()).await
;
332 message
: "An email has been sent, follow the link to validate your account.",
336 #[get("/validation")]
337 pub async
fn sign_up_validation(req
: HttpRequest
, query
: web
::Query
<HashMap
<String
, String
>>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
338 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
339 let user
= get_current_user(&req
, connection
.clone()).await
;
341 match query
.get("token") {
343 match connection
.validation_async(token
, Duration
::seconds(consts
::VALIDATION_TOKEN_DURATION
), &client_ip
, &client_user_agent
).await?
{
344 db
::ValidationResult
::Ok(token
, user_id
) => {
345 let cookie
= Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, token
);
347 match connection
.load_user(user_id
) {
351 error!("Error retrieving user by id: {}", error
);
359 message
: "Email validation successful, your account has been created",
362 if let Err(error
) = response
.add_cookie(&cookie
) {
363 error!("Unable to set cookie after validation: {}", error
);
368 db
::ValidationResult
::ValidationExpired
=>
371 message
: "The validation has expired. Try to sign up again.",
373 db
::ValidationResult
::UnknownUser
=>
376 message
: "Validation error.",
383 message
: &format!("No token provided"),
392 #[template(path = "sign_in_form.html")]
393 struct SignInFormTemplate
{
400 pub async
fn sign_in_get(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
401 let user
= get_current_user(&req
, connection
.clone()).await
;
404 email
: String
::new(),
405 message
: String
::new(),
409 #[derive(Deserialize)]
410 pub struct SignInFormData
{
417 AuthenticationFailed
,
421 pub async
fn sign_in_post(req
: HttpRequest
, form
: web
::Form
<SignInFormData
>, connection
: web
::Data
<db
::Connection
>) -> Result
<HttpResponse
> {
422 fn error_response(error
: SignInError
, form
: &web
::Form
<SignInFormData
>, user
: Option
<User
>) -> Result
<HttpResponse
> {
423 Ok(SignInFormTemplate
{
425 email
: form
.email
.clone(),
428 SignInError
::AccountNotValidated
=> "This account must be validated first",
429 SignInError
::AuthenticationFailed
=> "Wrong email or password",
434 let user
= get_current_user(&req
, connection
.clone()).await
;
435 let (client_ip
, client_user_agent
) = get_ip_and_user_agent(&req
);
437 match connection
.sign_in_async(&form
.email
, &form
.password
, &client_ip
, &client_user_agent
).await
{
438 Ok(db
::SignInResult
::AccountNotValidated
) =>
439 error_response(SignInError
::AccountNotValidated
, &form
, user
),
440 Ok(db
::SignInResult
::UserNotFound
) | Ok(db
::SignInResult
::WrongPassword
) => {
441 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
443 Ok(db
::SignInResult
::Ok(token
, user_id
)) => {
444 let cookie
= Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, token
);
446 HttpResponse
::Found()
447 .insert_header((header
::LOCATION
, "/"))
449 if let Err(error
) = response
.add_cookie(&cookie
) {
450 error!("Unable to set cookie after sign in: {}", error
);
455 error!("Signin error: {}", error
);
456 error_response(SignInError
::AuthenticationFailed
, &form
, user
)
465 pub async
fn sign_out(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
467 HttpResponse
::Found()
468 .insert_header((header
::LOCATION
, "/"))
471 if let Some(token_cookie
) = req
.cookie(consts
::COOKIE_AUTH_TOKEN_NAME
) {
472 if let Err(error
) = connection
.sign_out_async(token_cookie
.value()).await
{
473 error!("Unable to sign out: {}", error
);
476 if let Err(error
) = response
.add_removal_cookie(&Cookie
::new(consts
::COOKIE_AUTH_TOKEN_NAME
, "")) {
477 error!("Unable to set a removal cookie after sign out: {}", error
);
483 pub async
fn not_found(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
484 let user
= get_current_user(&req
, connection
.clone()).await
;
487 message
: "404: Not found",