1 use std
::{collections
::HashMap
, net
::ToSocketAddrs
};
4 use actix_web
::{http
::header
, get
, post
, web
, Responder
, middleware
, App
, HttpServer
, HttpRequest
, HttpResponse
};
5 use askama_actix
::{Template
, TemplateToResponse
};
6 use chrono
::{prelude
::*, Duration
};
8 use serde
::Deserialize
;
21 #[template(path = "home.html")]
23 recipes
: Vec
<(i32, String
)>,
27 #[template(path = "sign_in_form.html")]
28 struct SignInFormTemplate
{
32 #[template(path = "view_recipe.html")]
33 struct ViewRecipeTemplate
{
34 recipes
: Vec
<(i32, String
)>,
35 current_recipe
: model
::Recipe
,
39 #[template(path = "message.html")]
40 struct MessageTemplate
{
41 recipes
: Vec
<(i32, String
)>,
46 async
fn home_page(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
47 HomeTemplate
{ recipes
: connection
.get_all_recipe_titles().unwrap_or_default() }
53 #[template(path = "sign_up_form.html")]
54 struct SignUpFormTemplate
{
57 message_email
: String
,
58 message_password
: String
,
61 impl SignUpFormTemplate
{
63 SignUpFormTemplate
{ email
: String
::new(), message
: String
::new(), message_email
: String
::new(), message_password
: String
::new() }
77 async
fn sign_up_get(req
: HttpRequest
, query
: web
::Query
<HashMap
<String
, String
>>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
78 SignUpFormTemplate
::new()
81 #[derive(Deserialize)]
82 struct SignUpFormData
{
89 async
fn sign_up_post(req
: HttpRequest
, form
: web
::Form
<SignUpFormData
>, connection
: web
::Data
<db
::Connection
>, config
: web
::Data
<Config
>) -> impl Responder
{
90 println!("Sign Up, email: {}, passwords: {}/{}", form
.email
, form
.password_1
, form
.password_2
);
92 fn error_response(error
: SignUpError
, form
: &web
::Form
<SignUpFormData
>) -> HttpResponse
{
94 email
: form
.email
.clone(),
97 SignUpError
::InvalidEmail
=> "Invalid email",
102 SignUpError
::PasswordsNotEqual
=> "Passwords don't match",
103 SignUpError
::InvalidPassword
=> "Password must have at least eight characters",
108 SignUpError
::UserAlreadyExists
=> "This email is already taken",
109 SignUpError
::DatabaseError
=> "Database error",
110 SignUpError
::UnableSendEmail
=> "Unable to send the validation email",
116 // Validation of email and password.
117 if let common
::utils
::EmailValidation
::NotValid
= common
::utils
::validate_email(&form
.email
) {
118 return error_response(SignUpError
::InvalidEmail
, &form
);
121 if form
.password_1
!= form
.password_2
{
122 return error_response(SignUpError
::PasswordsNotEqual
, &form
);
125 if let common
::utils
::PasswordValidation
::TooShort
= common
::utils
::validate_password(&form
.password_1
) {
126 return error_response(SignUpError
::InvalidPassword
, &form
);
129 match connection
.sign_up(&form
.email
, &form
.password_1
) {
130 Ok(db
::SignUpResult
::UserAlreadyExists
) => {
131 error_response(SignUpError
::UserAlreadyExists
, &form
)
133 Ok(db
::SignUpResult
::UserCreatedWaitingForValidation(token
)) => {
135 let host
= req
.headers().get(header
::HOST
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default();
136 let port
: Option
<i32> = 'p
: {
137 let split_port
: Vec
<&str> = host
.split('
:'
).collect();
138 if split_port
.len() == 2 {
139 if let Ok(p
) = split_port
[1].parse
::<i32>() {
145 format!("http{}://{}", if port
.is_some() && port
.unwrap() != 443 { "" } else { "s" }, host
)
147 match email
::send_validation(&url
, &form
.email
, &token
, &config
.smtp_login
, &config
.smtp_password
) {
149 HttpResponse
::Found()
150 .insert_header((header
::LOCATION
, "/signup_check_email"))
153 eprintln!("Email validation error: {:?}", error
);
154 error_response(SignUpError
::UnableSendEmail
, &form
)
159 eprintln!("Signup database error: {:?}", error
);
160 error_response(SignUpError
::DatabaseError
, &form
)
165 #[get("/signup_check_email")]
166 async
fn sign_up_check_email(connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
167 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
170 message
: "An email has been sent, follow the link to validate your account.".to_string(),
174 #[get("/validation")]
175 async
fn sign_up_validation(req
: HttpRequest
, query
: web
::Query
<HashMap
<String
, String
>>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
177 println!("req:\n{:#?}", req
);
179 let client_user_agent
= req
.headers().get(header
::USER_AGENT
).map(|v
| v
.to_str().unwrap_or_default()).unwrap_or_default();
180 let client_ip
= req
.peer_addr().map(|addr
| addr
.ip().to_string()).unwrap_or_default();
182 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
183 match query
.get("token") {
185 match connection
.validation(token
, Duration
::seconds(consts
::VALIDATION_TOKEN_DURATION
), &client_ip
, client_user_agent
).unwrap() {
186 db
::ValidationResult
::Ok(token
, user_id
) =>
187 // TODO: set token to cookie.
190 message
: "Email validation successful, your account has been created".to_string(),
192 db
::ValidationResult
::ValidationExpired
=>
195 message
: "The validation has expired. Try to sign up again.".to_string(),
197 db
::ValidationResult
::UnknownUser
=>
200 message
: "Validation error.".to_string(),
207 message
: format!("No token provided"),
215 #[get("/signinform")]
216 async
fn sign_in_form(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
222 async
fn sign_in(req
: HttpRequest
) -> impl Responder
{
226 #[get("/recipe/view/{id}")]
227 async
fn view_recipe(req
: HttpRequest
, path
: web
::Path
<(i32,)>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
228 let (id
,)= path
.into_inner();
229 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
230 println!("{:?}", recipes
);
231 match connection
.get_recipe(id
) {
235 current_recipe
: recipe
,
240 message
: format!("Unable to get recipe #{}", id
),
245 async
fn not_found(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
246 let recipes
= connection
.get_all_recipe_titles().unwrap_or_default();
249 message
: "404: Not found".to_string(),
253 fn get_exe_name() -> String
{
254 let first_arg
= std
::env
::args().nth(0).unwrap();
255 let sep
: &[_
] = &['
\\'
, '
/'
];
256 first_arg
[first_arg
.rfind(sep
).unwrap()+1..].to_string()
260 async
fn main() -> std
::io
::Result
<()> {
261 if process_args() { return Ok(()) }
263 std
::env
::set_var("RUST_LOG", "actix_web=debug");
266 println!("Starting Recipes as web server...");
268 let config
= web
::Data
::new(config
::load());
269 let port
= config
.as_ref().port
;
271 println!("Configuration: {:?}", config
);
273 let db_connection
= web
::Data
::new(db
::Connection
::new().unwrap());
275 std
::env
::set_var("RUST_LOG", "actix_web=info");
278 HttpServer
::new(move || {
280 .wrap(middleware
::Logger
::default())
281 .wrap(middleware
::Compress
::default())
282 .app_data(db_connection
.clone())
283 .app_data(config
.clone())
285 .service(sign_up_get
)
286 .service(sign_up_post
)
287 .service(sign_up_check_email
)
288 .service(sign_up_validation
)
289 .service(sign_in_form
)
291 .service(view_recipe
)
292 .service(fs
::Files
::new("/static", "static"))
293 .default_service(web
::to(not_found
))
294 //.default_service(not_found)
297 server
.bind(&format!("0.0.0.0:{}", port
))?
.run().await
300 #[derive(Parser, Debug)]
306 fn process_args() -> bool
{
307 let args
= Args
::parse();
310 match db
::Connection
::new() {
312 if let Err(error
) = con
.execute_file("sql/data_test.sql") {
313 println!("Error: {:?}", error
);
315 // Set the creation datetime to 'now'.
316 con
.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc
::now()]).unwrap();
319 println!("Error: {:?}", error
)
333 println!(" {} [--help] [--test]", get_exe_name());
336 let args: Vec<String> = args().collect();
338 if args.iter().any(|arg| arg == "--help") {
341 } else if args.iter().any(|arg| arg == "--test") {
342 match db::Connection::new() {
344 Err(error) => println!("Error: {:?}", error)