Replace Rusqlite by Sqlx and Actix by Axum (A lot of changes)

This commit is contained in:
Greg Burri 2024-11-03 10:13:31 +01:00
parent 57d7e7a3ce
commit 980c5884a4
28 changed files with 2860 additions and 2262 deletions

View file

@ -1,145 +1,29 @@
use std::collections::HashMap;
use std::{collections::HashMap, net::SocketAddr};
use actix_web::{
cookie::Cookie,
get,
http::{header, header::ContentType, StatusCode},
post, web, HttpRequest, HttpResponse, Responder,
use askama::Template;
use axum::{
body::Body,
debug_handler,
extract::{ConnectInfo, Extension, Host, Path, Query, Request, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Redirect, Response, Result},
Form,
};
use askama_actix::{Template, TemplateToResponse};
use axum_extra::extract::cookie::{Cookie, CookieJar};
use chrono::Duration;
use log::{debug, error, info, log_enabled, Level};
use serde::Deserialize;
use crate::{
config::Config,
consts,
data::{asynchronous, db},
email, model, utils,
};
use crate::{config::Config, consts, data::db, email, model, utils, AppState};
pub mod webapi;
///// UTILS /////
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
let ip = match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
Some(v) => v.to_str().unwrap_or_default().to_string(),
None => req
.peer_addr()
.map(|addr| addr.ip().to_string())
.unwrap_or_default(),
};
let user_agent = req
.headers()
.get(header::USER_AGENT)
.map(|v| v.to_str().unwrap_or_default())
.unwrap_or_default()
.to_string();
(ip, user_agent)
}
async fn get_current_user(
req: &HttpRequest,
connection: web::Data<db::Connection>,
) -> Option<model::User> {
let (client_ip, client_user_agent) = get_ip_and_user_agent(req);
match req.cookie(consts::COOKIE_AUTH_TOKEN_NAME) {
Some(token_cookie) => match connection
.authentication_async(token_cookie.value(), &client_ip, &client_user_agent)
.await
{
Ok(db::AuthenticationResult::NotValidToken) =>
// TODO: remove cookie?
{
None
}
Ok(db::AuthenticationResult::Ok(user_id)) => {
match connection.load_user_async(user_id).await {
Ok(user) => Some(user),
Err(error) => {
error!("Error during authentication: {}", error);
None
}
}
}
Err(error) => {
error!("Error during authentication: {}", error);
None
}
},
None => None,
}
}
type Result<T> = std::result::Result<T, ServiceError>;
///// ERROR /////
#[derive(Debug)]
pub struct ServiceError {
status_code: StatusCode,
message: Option<String>,
}
impl From<asynchronous::DBAsyncError> for ServiceError {
fn from(error: asynchronous::DBAsyncError) -> Self {
ServiceError {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
message: Some(format!("{:?}", error)),
}
}
}
impl From<email::Error> for ServiceError {
fn from(error: email::Error) -> Self {
ServiceError {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
message: Some(format!("{:?}", error)),
}
}
}
impl From<actix_web::error::BlockingError> for ServiceError {
fn from(error: actix_web::error::BlockingError) -> Self {
ServiceError {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
message: Some(format!("{:?}", error)),
}
}
}
impl From<ron::error::SpannedError> for ServiceError {
fn from(error: ron::error::SpannedError) -> Self {
ServiceError {
status_code: StatusCode::INTERNAL_SERVER_ERROR,
message: Some(format!("{:?}", error)),
}
}
}
impl std::fmt::Display for ServiceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
if let Some(ref m) = self.message {
write!(f, "**{}**\n\n", m)?;
}
write!(f, "Code: {}", self.status_code)
}
}
impl actix_web::error::ResponseError for ServiceError {
fn error_response(&self) -> HttpResponse {
MessageBaseTemplate {
impl axum::response::IntoResponse for db::DBError {
fn into_response(self) -> Response {
let body = MessageTemplate {
user: None,
message: &self.to_string(),
}
.to_response()
}
fn status_code(&self) -> StatusCode {
self.status_code
};
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}
}
@ -153,20 +37,18 @@ struct HomeTemplate {
current_recipe_id: Option<i64>,
}
#[get("/")]
#[debug_handler]
pub async fn home_page(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let user = get_current_user(&req, connection.clone()).await;
let recipes = connection.get_all_recipe_titles_async().await?;
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
) -> Result<impl IntoResponse> {
let recipes = connection.get_all_recipe_titles().await?;
Ok(HomeTemplate {
user,
current_recipe_id: None,
recipes,
}
.to_response())
})
}
///// VIEW RECIPE /////
@ -177,115 +59,117 @@ struct ViewRecipeTemplate {
user: Option<model::User>,
recipes: Vec<(i64, String)>,
current_recipe_id: Option<i64>,
current_recipe: model::Recipe,
}
#[get("/recipe/view/{id}")]
#[debug_handler]
pub async fn view_recipe(
req: HttpRequest,
path: web::Path<(i64,)>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let (id,) = path.into_inner();
let user = get_current_user(&req, connection.clone()).await;
let recipes = connection.get_all_recipe_titles_async().await?;
let recipe = connection.get_recipe_async(id).await?;
Ok(ViewRecipeTemplate {
user,
current_recipe_id: Some(recipe.id),
recipes,
current_recipe: recipe,
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Path(recipe_id): Path<i64>,
) -> Result<Response> {
let recipes = connection.get_all_recipe_titles().await?;
match connection.get_recipe(recipe_id).await? {
Some(recipe) => Ok(ViewRecipeTemplate {
user,
current_recipe_id: Some(recipe.id),
recipes,
current_recipe: recipe,
}
.into_response()),
None => Ok(MessageTemplate {
user,
message: &format!("Cannot find the recipe {}", recipe_id),
}
.into_response()),
}
.to_response())
}
///// EDIT/NEW RECIPE /////
#[derive(Template)]
#[template(path = "edit_recipe.html")]
struct EditRecipeTemplate {
user: Option<model::User>,
recipes: Vec<(i64, String)>,
current_recipe_id: Option<i64>,
// #[derive(Template)]
// #[template(path = "edit_recipe.html")]
// struct EditRecipeTemplate {
// user: Option<model::User>,
// recipes: Vec<(i64, String)>,
// current_recipe_id: Option<i64>,
current_recipe: model::Recipe,
}
// current_recipe: model::Recipe,
// }
#[get("/recipe/edit/{id}")]
pub async fn edit_recipe(
req: HttpRequest,
path: web::Path<(i64,)>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let (id,) = path.into_inner();
let user = match get_current_user(&req, connection.clone()).await {
Some(u) => u,
None => {
return Ok(MessageTemplate {
user: None,
message: "Cannot edit a recipe without being logged in",
}
.to_response())
}
};
// #[get("/recipe/edit/{id}")]
// pub async fn edit_recipe(
// req: HttpRequest,
// path: web::Path<(i64,)>,
// connection: web::Data<db::Connection>,
// ) -> Result<HttpResponse> {
// let (id,) = path.into_inner();
// let user = match get_current_user(&req, connection.clone()).await {
// Some(u) => u,
// None => {
// return Ok(MessageTemplate {
// user: None,
// message: "Cannot edit a recipe without being logged in",
// }
// .to_response())
// }
// };
let recipe = connection.get_recipe_async(id).await?;
// let recipe = connection.get_recipe_async(id).await?;
if recipe.user_id != user.id {
return Ok(MessageTemplate {
message: "Cannot edit a recipe you don't own",
user: Some(user),
}
.to_response());
}
// if recipe.user_id != user.id {
// return Ok(MessageTemplate {
// message: "Cannot edit a recipe you don't own",
// user: Some(user),
// }
// .to_response());
// }
let recipes = connection.get_all_recipe_titles_async().await?;
// let recipes = connection.get_all_recipe_titles_async().await?;
Ok(EditRecipeTemplate {
user: Some(user),
current_recipe_id: Some(recipe.id),
recipes,
current_recipe: recipe,
}
.to_response())
}
// Ok(EditRecipeTemplate {
// user: Some(user),
// current_recipe_id: Some(recipe.id),
// recipes,
// current_recipe: recipe,
// }
// .to_response())
// }
#[get("/recipe/new")]
pub async fn new_recipe(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let user = match get_current_user(&req, connection.clone()).await {
Some(u) => u,
None => {
return Ok(MessageTemplate {
message: "Cannot create a recipe without being logged in",
user: None,
}
.to_response())
}
};
// #[get("/recipe/new")]
// pub async fn new_recipe(
// req: HttpRequest,
// connection: web::Data<db::Connection>,
// ) -> Result<HttpResponse> {
// let user = match get_current_user(&req, connection.clone()).await {
// Some(u) => u,
// None => {
// return Ok(MessageTemplate {
// message: "Cannot create a recipe without being logged in",
// user: None,
// }
// .to_response())
// }
// };
let recipe_id = connection.create_recipe_async(user.id).await?;
let recipes = connection.get_all_recipe_titles_async().await?;
let user_id = user.id;
// let recipe_id = connection.create_recipe_async(user.id).await?;
// let recipes = connection.get_all_recipe_titles_async().await?;
// let user_id = user.id;
Ok(EditRecipeTemplate {
user: Some(user),
current_recipe_id: Some(recipe_id),
recipes,
current_recipe: model::Recipe::empty(recipe_id, user_id),
}
.to_response())
}
// Ok(EditRecipeTemplate {
// user: Some(user),
// current_recipe_id: Some(recipe_id),
// recipes,
// current_recipe: model::Recipe::empty(recipe_id, user_id),
// }
// .to_response())
// }
///// MESSAGE /////
#[derive(Template)]
#[template(path = "message_base.html")]
struct MessageBaseTemplate<'a> {
#[template(path = "message_without_user.html")]
struct MessageWithoutUser<'a> {
message: &'a str,
}
@ -308,22 +192,20 @@ struct SignUpFormTemplate {
message_password: String,
}
#[get("/signup")]
#[debug_handler]
pub async fn sign_up_get(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> impl Responder {
let user = get_current_user(&req, connection.clone()).await;
SignUpFormTemplate {
Extension(user): Extension<Option<model::User>>,
) -> Result<impl IntoResponse> {
Ok(SignUpFormTemplate {
user,
email: String::new(),
message: String::new(),
message_email: String::new(),
message_password: String::new(),
}
})
}
#[derive(Deserialize)]
#[derive(Deserialize, Debug)]
pub struct SignUpFormData {
email: String,
password_1: String,
@ -339,21 +221,22 @@ enum SignUpError {
UnableSendEmail,
}
#[post("/signup")]
#[debug_handler(state = AppState)]
pub async fn sign_up_post(
req: HttpRequest,
form: web::Form<SignUpFormData>,
connection: web::Data<db::Connection>,
config: web::Data<Config>,
) -> Result<HttpResponse> {
Host(host): Host,
State(connection): State<db::Connection>,
State(config): State<Config>,
Extension(user): Extension<Option<model::User>>,
Form(form_data): Form<SignUpFormData>,
) -> Result<Response> {
fn error_response(
error: SignUpError,
form: &web::Form<SignUpFormData>,
form_data: &SignUpFormData,
user: Option<model::User>,
) -> Result<HttpResponse> {
) -> Result<Response> {
Ok(SignUpFormTemplate {
user,
email: form.email.clone(),
email: form_data.email.clone(),
message_email: match error {
SignUpError::InvalidEmail => "Invalid email",
_ => "",
@ -373,40 +256,35 @@ pub async fn sign_up_post(
}
.to_string(),
}
.to_response())
.into_response())
}
let user = get_current_user(&req, connection.clone()).await;
// Validation of email and password.
if let common::utils::EmailValidation::NotValid = common::utils::validate_email(&form.email) {
return error_response(SignUpError::InvalidEmail, &form, user);
if let common::utils::EmailValidation::NotValid =
common::utils::validate_email(&form_data.email)
{
return error_response(SignUpError::InvalidEmail, &form_data, user);
}
if form.password_1 != form.password_2 {
return error_response(SignUpError::PasswordsNotEqual, &form, user);
if form_data.password_1 != form_data.password_2 {
return error_response(SignUpError::PasswordsNotEqual, &form_data, user);
}
if let common::utils::PasswordValidation::TooShort =
common::utils::validate_password(&form.password_1)
common::utils::validate_password(&form_data.password_1)
{
return error_response(SignUpError::InvalidPassword, &form, user);
return error_response(SignUpError::InvalidPassword, &form_data, user);
}
match connection
.sign_up_async(&form.email, &form.password_1)
.sign_up(&form_data.email, &form_data.password_1)
.await
{
Ok(db::SignUpResult::UserAlreadyExists) => {
error_response(SignUpError::UserAlreadyExists, &form, user)
error_response(SignUpError::UserAlreadyExists, &form_data, user)
}
Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => {
let url = {
let host = req
.headers()
.get(header::HOST)
.map(|v| v.to_str().unwrap_or_default())
.unwrap_or_default();
let port: Option<u16> = 'p: {
let split_port: Vec<&str> = host.split(':').collect();
if split_port.len() == 2 {
@ -427,60 +305,61 @@ pub async fn sign_up_post(
)
};
let email = form.email.clone();
println!("{}", &url);
match web::block(move || {
email::send_validation(
&url,
&email,
&token,
&config.smtp_login,
&config.smtp_password,
)
})
.await?
let email = form_data.email.clone();
match email::send_validation(
&url,
&email,
&token,
&config.smtp_relay_address,
&config.smtp_login,
&config.smtp_password,
)
.await
{
Ok(()) => Ok(HttpResponse::Found()
.insert_header((header::LOCATION, "/signup_check_email"))
.finish()),
Err(error) => {
error!("Email validation error: {}", error);
error_response(SignUpError::UnableSendEmail, &form, user)
Ok(()) => Ok(MessageTemplate {
user,
message: "An email has been sent, follow the link to validate your account.",
}
.into_response()),
Err(_) => {
// error!("Email validation error: {}", error); // TODO: log
error_response(SignUpError::UnableSendEmail, &form_data, user)
}
}
}
Err(error) => {
error!("Signup database error: {}", error);
error_response(SignUpError::DatabaseError, &form, user)
Err(_) => {
// error!("Signup database error: {}", error);
error_response(SignUpError::DatabaseError, &form_data, user)
}
}
}
#[get("/signup_check_email")]
pub async fn sign_up_check_email(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> impl Responder {
let user = get_current_user(&req, connection.clone()).await;
MessageTemplate {
user,
message: "An email has been sent, follow the link to validate your account.",
}
}
#[get("/validation")]
#[debug_handler]
pub async fn sign_up_validation(
req: HttpRequest,
query: web::Query<HashMap<String, String>>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
let user = get_current_user(&req, connection.clone()).await;
match query.get("token") {
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
Query(query): Query<HashMap<String, String>>,
headers: HeaderMap,
) -> Result<(CookieJar, impl IntoResponse)> {
let mut jar = CookieJar::from_headers(&headers);
if user.is_some() {
return Ok((
jar,
MessageTemplate {
user,
message: "User already exists",
},
));
}
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(&headers, addr);
match query.get("validation_token") {
// 'validation_token' exists only when a user tries to validate a new account.
Some(token) => {
match connection
.validation_async(
.validation(
token,
Duration::seconds(consts::VALIDATION_TOKEN_DURATION),
&client_ip,
@ -490,43 +369,39 @@ pub async fn sign_up_validation(
{
db::ValidationResult::Ok(token, user_id) => {
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
let user = match connection.load_user(user_id) {
Ok(user) => Some(user),
Err(error) => {
error!("Error retrieving user by id: {}", error);
None
}
};
let mut response = MessageTemplate {
jar = jar.add(cookie);
let user = connection.load_user(user_id).await?;
Ok((
jar,
MessageTemplate {
user,
message: "Email validation successful, your account has been created",
},
))
}
db::ValidationResult::ValidationExpired => Ok((
jar,
MessageTemplate {
user,
message: "Email validation successful, your account has been created",
}
.to_response();
if let Err(error) = response.add_cookie(&cookie) {
error!("Unable to set cookie after validation: {}", error);
};
Ok(response)
}
db::ValidationResult::ValidationExpired => Ok(MessageTemplate {
user,
message: "The validation has expired. Try to sign up again.",
}
.to_response()),
db::ValidationResult::UnknownUser => Ok(MessageTemplate {
user,
message: "Validation error.",
}
.to_response()),
message: "The validation has expired. Try to sign up again",
},
)),
db::ValidationResult::UnknownUser => Ok((
jar,
MessageTemplate {
user,
message: "Validation error. Try to sign up again",
},
)),
}
}
None => Ok(MessageTemplate {
user,
message: &format!("No token provided"),
}
.to_response()),
None => Ok((
jar,
MessageTemplate {
user,
message: "Validation error",
},
)),
}
}
@ -540,109 +415,89 @@ struct SignInFormTemplate {
message: String,
}
#[get("/signin")]
#[debug_handler]
pub async fn sign_in_get(
req: HttpRequest,
connection: web::Data<db::Connection>,
) -> impl Responder {
let user = get_current_user(&req, connection.clone()).await;
SignInFormTemplate {
Extension(user): Extension<Option<model::User>>,
) -> Result<impl IntoResponse> {
Ok(SignInFormTemplate {
user,
email: String::new(),
message: String::new(),
}
})
}
#[derive(Deserialize)]
#[derive(Deserialize, Debug)]
pub struct SignInFormData {
email: String,
password: String,
}
enum SignInError {
AccountNotValidated,
AuthenticationFailed,
}
#[post("/signin")]
#[debug_handler]
pub async fn sign_in_post(
req: HttpRequest,
form: web::Form<SignInFormData>,
connection: web::Data<db::Connection>,
) -> Result<HttpResponse> {
fn error_response(
error: SignInError,
form: &web::Form<SignInFormData>,
user: Option<model::User>,
) -> Result<HttpResponse> {
Ok(SignInFormTemplate {
user,
email: form.email.clone(),
message: match error {
SignInError::AccountNotValidated => "This account must be validated first",
SignInError::AuthenticationFailed => "Wrong email or password",
}
.to_string(),
}
.to_response())
}
let user = get_current_user(&req, connection.clone()).await;
let (client_ip, client_user_agent) = get_ip_and_user_agent(&req);
ConnectInfo(addr): ConnectInfo<SocketAddr>,
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
headers: HeaderMap,
Form(form_data): Form<SignInFormData>,
) -> Result<(CookieJar, Response)> {
let jar = CookieJar::from_headers(&headers);
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(&headers, addr);
match connection
.sign_in_async(&form.email, &form.password, &client_ip, &client_user_agent)
.await
.sign_in(
&form_data.email,
&form_data.password,
&client_ip,
&client_user_agent,
)
.await?
{
Ok(db::SignInResult::AccountNotValidated) => {
error_response(SignInError::AccountNotValidated, &form, user)
}
Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => {
error_response(SignInError::AuthenticationFailed, &form, user)
}
Ok(db::SignInResult::Ok(token, user_id)) => {
db::SignInResult::AccountNotValidated => Ok((
jar,
SignInFormTemplate {
user,
email: form_data.email,
message: "This account must be validated first".to_string(),
}
.into_response(),
)),
db::SignInResult::UserNotFound | db::SignInResult::WrongPassword => Ok((
jar,
SignInFormTemplate {
user,
email: form_data.email,
message: "Wrong email or password".to_string(),
}
.into_response(),
)),
db::SignInResult::Ok(token, _user_id) => {
let cookie = Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, token);
let mut response = HttpResponse::Found()
.insert_header((header::LOCATION, "/"))
.finish();
if let Err(error) = response.add_cookie(&cookie) {
error!("Unable to set cookie after sign in: {}", error);
};
Ok(response)
}
Err(error) => {
error!("Signin error: {}", error);
error_response(SignInError::AuthenticationFailed, &form, user)
Ok((jar.add(cookie), Redirect::to("/").into_response()))
}
}
}
///// SIGN OUT /////
#[get("/signout")]
pub async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
let mut response = HttpResponse::Found()
.insert_header((header::LOCATION, "/"))
.finish();
if let Some(token_cookie) = req.cookie(consts::COOKIE_AUTH_TOKEN_NAME) {
if let Err(error) = connection.sign_out_async(token_cookie.value()).await {
error!("Unable to sign out: {}", error);
};
if let Err(error) =
response.add_removal_cookie(&Cookie::new(consts::COOKIE_AUTH_TOKEN_NAME, ""))
{
error!("Unable to set a removal cookie after sign out: {}", error);
};
};
response
}
pub async fn not_found(req: HttpRequest, connection: web::Data<db::Connection>) -> impl Responder {
let user = get_current_user(&req, connection.clone()).await;
MessageTemplate {
user,
message: "404: Not found",
#[debug_handler]
pub async fn sign_out(
State(connection): State<db::Connection>,
req: Request<Body>,
) -> Result<(CookieJar, Redirect)> {
let mut jar = CookieJar::from_headers(req.headers());
if let Some(token_cookie) = jar.get(consts::COOKIE_AUTH_TOKEN_NAME) {
let token = token_cookie.value().to_string();
jar = jar.remove(consts::COOKIE_AUTH_TOKEN_NAME);
connection.sign_out(&token).await?;
}
Ok((jar, Redirect::to("/")))
}
///// 404 /////
#[debug_handler]
pub async fn not_found() -> Result<impl IntoResponse> {
Ok(MessageWithoutUser {
message: "404: Not found",
})
}