Update dependencies and implement email service integration
- Refactor app and email modules to include email service - Add tests for user sign-up and mock email service
This commit is contained in:
parent
f31167dd95
commit
3626f8a11b
10 changed files with 291 additions and 151 deletions
|
|
@ -38,6 +38,7 @@ rand_core = { version = "0.9", features = ["std"] }
|
|||
rand = "0.9"
|
||||
strum = "0.27"
|
||||
strum_macros = "0.27"
|
||||
async-trait = "0.1"
|
||||
|
||||
lettre = { version = "0.11", default-features = false, features = [
|
||||
"smtp-transport",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use std::net::SocketAddr;
|
||||
use std::{net::SocketAddr, sync::Arc};
|
||||
|
||||
use axum::{
|
||||
BoxError, Router, ServiceExt,
|
||||
|
|
@ -27,6 +27,7 @@ use crate::{
|
|||
config::Config,
|
||||
consts,
|
||||
data::{db, model},
|
||||
email,
|
||||
log::Log,
|
||||
ron_utils, services,
|
||||
translation::{self, Tr},
|
||||
|
|
@ -38,6 +39,7 @@ pub struct AppState {
|
|||
pub config: Config,
|
||||
pub db_connection: db::Connection,
|
||||
pub log: Log,
|
||||
pub email_service: Arc<dyn email::EmailServiceTrait>,
|
||||
}
|
||||
|
||||
impl FromRef<AppState> for Config {
|
||||
|
|
@ -58,6 +60,12 @@ impl FromRef<AppState> for Log {
|
|||
}
|
||||
}
|
||||
|
||||
impl FromRef<AppState> for Arc<dyn email::EmailServiceTrait> {
|
||||
fn from_ref(app_state: &AppState) -> Arc<dyn email::EmailServiceTrait> {
|
||||
app_state.email_service.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl axum::response::IntoResponse for db::DBError {
|
||||
fn into_response(self) -> Response {
|
||||
ron_utils::ron_error(StatusCode::INTERNAL_SERVER_ERROR, &self.to_string()).into_response()
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use lettre::{
|
||||
AsyncTransport, Message, Tokio1Executor,
|
||||
transport::smtp::{AsyncSmtpTransport, authentication::Credentials},
|
||||
|
|
@ -18,33 +20,52 @@ pub enum Error {
|
|||
Email(#[from] lettre::error::Error),
|
||||
}
|
||||
|
||||
/// A function to send an email using the given SMTP address.
|
||||
/// It may timeout if the SMTP server is not reachable, see [consts::SEND_EMAIL_TIMEOUT].
|
||||
pub async fn send_email(
|
||||
email: &str,
|
||||
title: &str,
|
||||
message: &str,
|
||||
smtp_relay_address: &str,
|
||||
smtp_login: &str,
|
||||
smtp_password: &str,
|
||||
) -> Result<(), Error> {
|
||||
let email = Message::builder()
|
||||
.message_id(None)
|
||||
.from(consts::EMAIL_ADDRESS.parse()?)
|
||||
.to(email.parse()?)
|
||||
.subject(title)
|
||||
.body(message.to_string())?;
|
||||
|
||||
let credentials = Credentials::new(smtp_login.to_string(), smtp_password.to_string());
|
||||
|
||||
let mailer = AsyncSmtpTransport::<Tokio1Executor>::relay(smtp_relay_address)?
|
||||
.credentials(credentials)
|
||||
.timeout(Some(consts::SEND_EMAIL_TIMEOUT))
|
||||
.build();
|
||||
|
||||
if let Err(error) = mailer.send(email).await {
|
||||
error!("Error when sending E-mail: {}", &error);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
#[async_trait::async_trait]
|
||||
pub trait EmailServiceTrait: Send + Sync {
|
||||
async fn send_email(&self, email: &str, title: &str, message: &str) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
pub struct EmailService {
|
||||
smtp_relay_address: String,
|
||||
smtp_login: String,
|
||||
smtp_password: String,
|
||||
}
|
||||
|
||||
impl EmailService {
|
||||
pub fn create_service(
|
||||
smtp_relay_address: &str,
|
||||
smtp_login: &str,
|
||||
smtp_password: &str,
|
||||
) -> Arc<dyn EmailServiceTrait> {
|
||||
Arc::new(Self {
|
||||
smtp_relay_address: smtp_relay_address.to_string(),
|
||||
smtp_login: smtp_login.to_string(),
|
||||
smtp_password: smtp_password.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl EmailServiceTrait for EmailService {
|
||||
/// A function to send an email using the given SMTP address.
|
||||
/// It may timeout if the SMTP server is not reachable, see [consts::SEND_EMAIL_TIMEOUT].
|
||||
async fn send_email(&self, email: &str, title: &str, message: &str) -> Result<(), Error> {
|
||||
let email = Message::builder()
|
||||
.message_id(None)
|
||||
.from(consts::EMAIL_ADDRESS.parse()?)
|
||||
.to(email.parse()?)
|
||||
.subject(title)
|
||||
.body(message.to_string())?;
|
||||
|
||||
let credentials = Credentials::new(self.smtp_login.clone(), self.smtp_password.clone());
|
||||
|
||||
let mailer = AsyncSmtpTransport::<Tokio1Executor>::relay(&self.smtp_relay_address)?
|
||||
.credentials(credentials)
|
||||
.timeout(Some(consts::SEND_EMAIL_TIMEOUT))
|
||||
.build();
|
||||
|
||||
mailer.send(email).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@ pub mod app;
|
|||
pub mod config;
|
||||
pub mod consts;
|
||||
pub mod data;
|
||||
pub mod email;
|
||||
pub mod log;
|
||||
|
||||
mod email;
|
||||
mod hash;
|
||||
mod html_templates;
|
||||
mod ron_extractor;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use tracing::{error, info};
|
|||
use recipes::{
|
||||
app, config, consts,
|
||||
data::{backup, db},
|
||||
email,
|
||||
log::Log,
|
||||
};
|
||||
|
||||
|
|
@ -17,13 +18,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
let config = config::load();
|
||||
let log = Log::new_to_directory(&config.logs_directory);
|
||||
|
||||
info!("Configuration: {:?}", config);
|
||||
|
||||
if !process_args(&config.database_directory).await {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
info!("Starting Recipes as web server...");
|
||||
info!("Configuration: {:?}", config);
|
||||
|
||||
let db_connection = db::Connection::new(&config.database_directory)
|
||||
.await
|
||||
|
|
@ -42,9 +42,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
let port = config.port;
|
||||
|
||||
let state = app::AppState {
|
||||
config,
|
||||
db_connection,
|
||||
log,
|
||||
email_service: email::EmailService::create_service(
|
||||
&config.smtp_relay_address,
|
||||
&config.smtp_login,
|
||||
&config.smtp_password,
|
||||
),
|
||||
config,
|
||||
};
|
||||
|
||||
let make_service = app::make_service(state);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use std::{collections::HashMap, net::SocketAddr};
|
||||
use std::{collections::HashMap, net::SocketAddr, sync::Arc};
|
||||
|
||||
use askama::Template;
|
||||
use axum::{
|
||||
|
|
@ -16,12 +16,10 @@ use axum_extra::extract::{
|
|||
use chrono::Duration;
|
||||
use lettre::Address;
|
||||
use serde::Deserialize;
|
||||
use strum_macros::Display;
|
||||
use tracing::{error, warn};
|
||||
|
||||
use crate::{
|
||||
app::{AppState, Context, Result},
|
||||
config::Config,
|
||||
consts,
|
||||
data::db,
|
||||
email,
|
||||
|
|
@ -66,21 +64,32 @@ pub struct SignUpFormData {
|
|||
password_2: String,
|
||||
}
|
||||
|
||||
#[derive(Display)]
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum SignUpError {
|
||||
#[error("Invalid email")]
|
||||
InvalidEmail,
|
||||
|
||||
#[error("Password not equal")]
|
||||
PasswordsNotEqual,
|
||||
|
||||
#[error("Invalid password")]
|
||||
InvalidPassword,
|
||||
|
||||
#[error("User already exists")]
|
||||
UserAlreadyExists,
|
||||
DatabaseError,
|
||||
UnableSendEmail,
|
||||
|
||||
#[error("Database error: {0}")]
|
||||
DatabaseError(db::DBError),
|
||||
|
||||
#[error("Unable to send email: {0}")]
|
||||
UnableToSendEmail(email::Error),
|
||||
}
|
||||
|
||||
#[debug_handler(state = AppState)]
|
||||
pub async fn sign_up_post(
|
||||
Host(host): Host,
|
||||
State(connection): State<db::Connection>,
|
||||
State(config): State<Config>,
|
||||
State(email_service): State<Arc<dyn email::EmailServiceTrait>>,
|
||||
Extension(context): Extension<Context>,
|
||||
Form(form_data): Form<SignUpFormData>,
|
||||
) -> Result<Response> {
|
||||
|
|
@ -89,8 +98,8 @@ pub async fn sign_up_post(
|
|||
form_data: &SignUpFormData,
|
||||
context: Context,
|
||||
) -> Result<Response> {
|
||||
warn!(
|
||||
"Unable to sign up with email {}: {}",
|
||||
error!(
|
||||
"Error during sign up (email={}): {}",
|
||||
form_data.email, error
|
||||
);
|
||||
|
||||
|
|
@ -112,8 +121,9 @@ pub async fn sign_up_post(
|
|||
},
|
||||
message: match error {
|
||||
SignUpError::UserAlreadyExists => context.tr.t(Sentence::EmailAlreadyTaken),
|
||||
SignUpError::DatabaseError => context.tr.t(Sentence::DatabaseError),
|
||||
SignUpError::UnableSendEmail => context.tr.t(Sentence::UnableToSendEmail),
|
||||
// The error is not shown to the user (it is logged above).
|
||||
SignUpError::DatabaseError(_) => context.tr.t(Sentence::DatabaseError),
|
||||
SignUpError::UnableToSendEmail(_) => context.tr.t(Sentence::UnableToSendEmail),
|
||||
_ => "",
|
||||
},
|
||||
context,
|
||||
|
|
@ -159,31 +169,31 @@ pub async fn sign_up_post(
|
|||
Ok(db::user::SignUpResult::UserCreatedWaitingForValidation(token)) => {
|
||||
let url = utils::get_url_from_host(&host);
|
||||
let email = form_data.email.clone();
|
||||
match email::send_email(
|
||||
&email,
|
||||
context.tr.t(Sentence::SignUpEmailTitle),
|
||||
&context.tr.tp(
|
||||
Sentence::SignUpFollowEmailLink,
|
||||
&[Box::new(format!(
|
||||
"{}/validation?{}={}",
|
||||
url, VALIDATION_TOKEN_KEY, token
|
||||
))],
|
||||
),
|
||||
&config.smtp_relay_address,
|
||||
&config.smtp_login,
|
||||
&config.smtp_password,
|
||||
)
|
||||
.await
|
||||
match email_service
|
||||
.send_email(
|
||||
&email,
|
||||
context.tr.t(Sentence::SignUpEmailTitle),
|
||||
&context.tr.tp(
|
||||
Sentence::SignUpFollowEmailLink,
|
||||
&[Box::new(format!(
|
||||
"{}/validation?{}={}",
|
||||
url, VALIDATION_TOKEN_KEY, token
|
||||
))],
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => Ok(Html(
|
||||
MessageTemplate::new(context.tr.t(Sentence::SignUpEmailSent), context)
|
||||
.render()?,
|
||||
)
|
||||
.into_response()),
|
||||
Err(_) => error_response(SignUpError::UnableSendEmail, &form_data, context),
|
||||
Err(error) => {
|
||||
error_response(SignUpError::UnableToSendEmail(error), &form_data, context)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => error_response(SignUpError::DatabaseError, &form_data, context),
|
||||
Err(error) => error_response(SignUpError::DatabaseError(error), &form_data, context),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -415,19 +425,29 @@ pub struct AskResetPasswordForm {
|
|||
email: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum AskResetPasswordError {
|
||||
#[error("Invalid email")]
|
||||
InvalidEmail,
|
||||
|
||||
#[error("Email already reset")]
|
||||
EmailAlreadyReset,
|
||||
|
||||
#[error("Email unknown")]
|
||||
EmailUnknown,
|
||||
UnableSendEmail,
|
||||
DatabaseError,
|
||||
|
||||
#[error("Database Error: {0}")]
|
||||
DatabaseError(db::DBError),
|
||||
|
||||
#[error("Unable to send email: {0}")]
|
||||
UnableSendEmail(email::Error),
|
||||
}
|
||||
|
||||
#[debug_handler(state = AppState)]
|
||||
pub async fn ask_reset_password_post(
|
||||
Host(host): Host,
|
||||
State(connection): State<db::Connection>,
|
||||
State(config): State<Config>,
|
||||
State(email_service): State<Arc<dyn email::EmailServiceTrait>>,
|
||||
Extension(context): Extension<Context>,
|
||||
Form(form_data): Form<AskResetPasswordForm>,
|
||||
) -> Result<Response> {
|
||||
|
|
@ -436,6 +456,11 @@ pub async fn ask_reset_password_post(
|
|||
email: &str,
|
||||
context: Context,
|
||||
) -> Result<Response> {
|
||||
error!(
|
||||
"Error when asking password reset (email={}): {}",
|
||||
email, error
|
||||
);
|
||||
|
||||
Ok(Html(
|
||||
AskResetPasswordTemplate {
|
||||
email,
|
||||
|
|
@ -448,10 +473,12 @@ pub async fn ask_reset_password_post(
|
|||
context.tr.t(Sentence::AskResetEmailAlreadyResetError)
|
||||
}
|
||||
AskResetPasswordError::EmailUnknown => context.tr.t(Sentence::EmailUnknown),
|
||||
AskResetPasswordError::UnableSendEmail => {
|
||||
AskResetPasswordError::UnableSendEmail(_) => {
|
||||
context.tr.t(Sentence::UnableToSendResetEmail)
|
||||
}
|
||||
AskResetPasswordError::DatabaseError => context.tr.t(Sentence::DatabaseError),
|
||||
AskResetPasswordError::DatabaseError(_) => {
|
||||
context.tr.t(Sentence::DatabaseError)
|
||||
}
|
||||
_ => "",
|
||||
},
|
||||
context,
|
||||
|
|
@ -489,45 +516,37 @@ pub async fn ask_reset_password_post(
|
|||
),
|
||||
Ok(db::user::GetTokenResetPasswordResult::Ok(token)) => {
|
||||
let url = utils::get_url_from_host(&host);
|
||||
match email::send_email(
|
||||
&form_data.email,
|
||||
context.tr.t(Sentence::AskResetEmailTitle),
|
||||
&context.tr.tp(
|
||||
Sentence::AskResetFollowEmailLink,
|
||||
&[Box::new(format!(
|
||||
"{}/reset_password?reset_token={}",
|
||||
url, token
|
||||
))],
|
||||
),
|
||||
&config.smtp_relay_address,
|
||||
&config.smtp_login,
|
||||
&config.smtp_password,
|
||||
)
|
||||
.await
|
||||
match email_service
|
||||
.send_email(
|
||||
&form_data.email,
|
||||
context.tr.t(Sentence::AskResetEmailTitle),
|
||||
&context.tr.tp(
|
||||
Sentence::AskResetFollowEmailLink,
|
||||
&[Box::new(format!(
|
||||
"{}/reset_password?reset_token={}",
|
||||
url, token
|
||||
))],
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => Ok(Html(
|
||||
MessageTemplate::new(context.tr.t(Sentence::AskResetEmailSent), context)
|
||||
.render()?,
|
||||
)
|
||||
.into_response()),
|
||||
Err(error) => {
|
||||
error!("Email validation error: {}", error);
|
||||
error_response(
|
||||
AskResetPasswordError::UnableSendEmail,
|
||||
&form_data.email,
|
||||
context,
|
||||
)
|
||||
}
|
||||
Err(error) => error_response(
|
||||
AskResetPasswordError::UnableSendEmail(error),
|
||||
&form_data.email,
|
||||
context,
|
||||
),
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
error!("{}", error);
|
||||
error_response(
|
||||
AskResetPasswordError::DatabaseError,
|
||||
&form_data.email,
|
||||
context,
|
||||
)
|
||||
}
|
||||
Err(error) => error_response(
|
||||
AskResetPasswordError::DatabaseError(error),
|
||||
&form_data.email,
|
||||
context,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -578,12 +597,19 @@ pub struct ResetPasswordForm {
|
|||
reset_token: String,
|
||||
}
|
||||
|
||||
#[derive(Display)]
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ResetPasswordError {
|
||||
#[error("Password not equal")]
|
||||
PasswordsNotEqual,
|
||||
|
||||
#[error("Invalid password")]
|
||||
InvalidPassword,
|
||||
|
||||
#[error("Token expired")]
|
||||
TokenExpired,
|
||||
DatabaseError,
|
||||
|
||||
#[error("Database error: {0}")]
|
||||
DatabaseError(db::DBError),
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
|
|
@ -597,8 +623,8 @@ pub async fn reset_password_post(
|
|||
form_data: &ResetPasswordForm,
|
||||
context: Context,
|
||||
) -> Result<Response> {
|
||||
warn!(
|
||||
"Email: {}: {}",
|
||||
error!(
|
||||
"Error during password reset (email={}): {}",
|
||||
if let Some(ref user) = context.user {
|
||||
&user.email
|
||||
} else {
|
||||
|
|
@ -624,7 +650,7 @@ pub async fn reset_password_post(
|
|||
ResetPasswordError::TokenExpired => {
|
||||
context.tr.t(Sentence::AskResetTokenExpired)
|
||||
}
|
||||
ResetPasswordError::DatabaseError => context.tr.t(Sentence::DatabaseError),
|
||||
ResetPasswordError::DatabaseError(_) => context.tr.t(Sentence::DatabaseError),
|
||||
_ => "",
|
||||
},
|
||||
context,
|
||||
|
|
@ -659,7 +685,11 @@ pub async fn reset_password_post(
|
|||
Ok(db::user::ResetPasswordResult::ResetTokenExpired) => {
|
||||
error_response(ResetPasswordError::TokenExpired, &form_data, context)
|
||||
}
|
||||
Err(_) => error_response(ResetPasswordError::DatabaseError, &form_data, context),
|
||||
Err(error) => error_response(
|
||||
ResetPasswordError::DatabaseError(error),
|
||||
&form_data,
|
||||
context,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -697,21 +727,32 @@ pub struct EditUserForm {
|
|||
password_2: String,
|
||||
}
|
||||
|
||||
#[derive(Display)]
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ProfileUpdateError {
|
||||
#[error("Invalid email")]
|
||||
InvalidEmail,
|
||||
|
||||
#[error("Email already taken")]
|
||||
EmailAlreadyTaken,
|
||||
|
||||
#[error("Password not equal")]
|
||||
PasswordsNotEqual,
|
||||
|
||||
#[error("Invalid password")]
|
||||
InvalidPassword,
|
||||
DatabaseError,
|
||||
UnableSendEmail,
|
||||
|
||||
#[error("Database error: {0}")]
|
||||
DatabaseError(db::DBError),
|
||||
|
||||
#[error("Unable to send email: {0}")]
|
||||
UnableToSendEmail(email::Error),
|
||||
}
|
||||
|
||||
#[debug_handler(state = AppState)]
|
||||
pub async fn edit_user_post(
|
||||
Host(host): Host,
|
||||
State(connection): State<db::Connection>,
|
||||
State(config): State<Config>,
|
||||
State(email_service): State<Arc<dyn email::EmailServiceTrait>>,
|
||||
Extension(context): Extension<Context>,
|
||||
Form(form_data): Form<EditUserForm>,
|
||||
) -> Result<Response> {
|
||||
|
|
@ -721,8 +762,8 @@ pub async fn edit_user_post(
|
|||
form_data: &EditUserForm,
|
||||
context: Context,
|
||||
) -> Result<Response> {
|
||||
warn!(
|
||||
"Email: {}: {}",
|
||||
error!(
|
||||
"Error during edit user (email={}): {}",
|
||||
if let Some(ref user) = context.user {
|
||||
&user.email
|
||||
} else {
|
||||
|
|
@ -754,8 +795,10 @@ pub async fn edit_user_post(
|
|||
_ => "",
|
||||
},
|
||||
message: match error {
|
||||
ProfileUpdateError::DatabaseError => context.tr.t(Sentence::DatabaseError),
|
||||
ProfileUpdateError::UnableSendEmail => {
|
||||
ProfileUpdateError::DatabaseError(_) => {
|
||||
context.tr.t(Sentence::DatabaseError)
|
||||
}
|
||||
ProfileUpdateError::UnableToSendEmail(_) => {
|
||||
context.tr.t(Sentence::UnableToSendEmail)
|
||||
}
|
||||
_ => "",
|
||||
|
|
@ -805,29 +848,26 @@ pub async fn edit_user_post(
|
|||
Ok(db::user::UpdateUserResult::UserUpdatedWaitingForRevalidation(token)) => {
|
||||
let url = utils::get_url_from_host(&host);
|
||||
let email = form_data.email.clone();
|
||||
match email::send_email(
|
||||
&email,
|
||||
context.tr.t(Sentence::ProfileFollowEmailTitle),
|
||||
&context.tr.tp(
|
||||
Sentence::ProfileFollowEmailLink,
|
||||
&[Box::new(format!(
|
||||
"{}/revalidation?{}={}",
|
||||
url, VALIDATION_TOKEN_KEY, token
|
||||
))],
|
||||
),
|
||||
&config.smtp_relay_address,
|
||||
&config.smtp_login,
|
||||
&config.smtp_password,
|
||||
)
|
||||
.await
|
||||
match email_service
|
||||
.send_email(
|
||||
&email,
|
||||
context.tr.t(Sentence::ProfileFollowEmailTitle),
|
||||
&context.tr.tp(
|
||||
Sentence::ProfileFollowEmailLink,
|
||||
&[Box::new(format!(
|
||||
"{}/revalidation?{}={}",
|
||||
url, VALIDATION_TOKEN_KEY, token
|
||||
))],
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
message = context.tr.t(Sentence::ProfileEmailSent);
|
||||
}
|
||||
Err(error) => {
|
||||
error!("Email validation error: {}", error);
|
||||
return error_response(
|
||||
ProfileUpdateError::UnableSendEmail,
|
||||
ProfileUpdateError::UnableToSendEmail(error),
|
||||
&form_data,
|
||||
context,
|
||||
);
|
||||
|
|
@ -837,8 +877,12 @@ pub async fn edit_user_post(
|
|||
Ok(db::user::UpdateUserResult::Ok) => {
|
||||
message = context.tr.t(Sentence::ProfileSaved);
|
||||
}
|
||||
Err(_) => {
|
||||
return error_response(ProfileUpdateError::DatabaseError, &form_data, context);
|
||||
Err(error) => {
|
||||
return error_response(
|
||||
ProfileUpdateError::DatabaseError(error),
|
||||
&form_data,
|
||||
context,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -914,7 +958,7 @@ pub async fn email_revalidation(
|
|||
))
|
||||
}
|
||||
error @ db::user::ValidationResult::ValidationExpired => {
|
||||
warn!("Token: {}: {}", token, error);
|
||||
error!("Token: {}: {}", token, error);
|
||||
Ok((
|
||||
jar,
|
||||
Html(
|
||||
|
|
@ -927,7 +971,7 @@ pub async fn email_revalidation(
|
|||
))
|
||||
}
|
||||
error @ db::user::ValidationResult::UnknownUser => {
|
||||
warn!("Email: {}: {}", token, error);
|
||||
error!("(email={}): {}", token, error);
|
||||
Ok((
|
||||
jar,
|
||||
Html(
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ use cookie::Cookie;
|
|||
use scraper::{ElementRef, Html, Selector};
|
||||
|
||||
use recipes::app;
|
||||
use serde::Serialize;
|
||||
|
||||
mod utils;
|
||||
|
||||
|
|
@ -92,3 +93,36 @@ async fn user_edit() -> Result<(), Box<dyn Error>> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct SignUpFormData {
|
||||
email: String,
|
||||
password_1: String,
|
||||
password_2: String,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sign_up() -> Result<(), Box<dyn Error>> {
|
||||
// Arrange.
|
||||
let state = utils::common_state().await?;
|
||||
let server = TestServer::new(app::make_service(state))?;
|
||||
|
||||
// Act.
|
||||
let response = server
|
||||
.post("/signup")
|
||||
.form(&SignUpFormData {
|
||||
email: "president@spaceball.planet".into(),
|
||||
password_1: "12345678".into(),
|
||||
password_2: "12345678".into(),
|
||||
})
|
||||
.await;
|
||||
|
||||
// Assert.
|
||||
response.assert_status_ok();
|
||||
|
||||
let document = Html::parse_document(&response.text());
|
||||
assert_eq!(document.errors.len(), 0);
|
||||
dbg!(response);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
23
backend/tests/utils/mock_email.rs
Normal file
23
backend/tests/utils/mock_email.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use recipes::email;
|
||||
|
||||
pub struct MockEmailService;
|
||||
|
||||
impl MockEmailService {
|
||||
pub fn create_service() -> Arc<dyn email::EmailServiceTrait> {
|
||||
Arc::new(Self {})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl email::EmailServiceTrait for MockEmailService {
|
||||
async fn send_email(
|
||||
&self,
|
||||
_email: &str,
|
||||
_title: &str,
|
||||
_message: &str,
|
||||
) -> Result<(), email::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,8 @@ use std::error::Error;
|
|||
|
||||
use recipes::{app, config, data::db, log};
|
||||
|
||||
mod mock_email;
|
||||
|
||||
pub async fn common_state() -> Result<app::AppState, Box<dyn Error>> {
|
||||
let db_connection = db::Connection::new_in_memory().await?;
|
||||
let config = config::Config::default();
|
||||
|
|
@ -10,6 +12,7 @@ pub async fn common_state() -> Result<app::AppState, Box<dyn Error>> {
|
|||
config,
|
||||
db_connection,
|
||||
log,
|
||||
email_service: mock_email::MockEmailService::create_service(),
|
||||
})
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue