create email client

This commit is contained in:
realaravinth 2021-06-30 14:16:48 +05:30
parent 8118e73df6
commit 9ed458ebfa
No known key found for this signature in database
GPG key ID: AD9F0F08E855ED88
4 changed files with 180 additions and 129 deletions

View file

@ -14,10 +14,14 @@
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
//! App data: redis cache, database connections, etc.
use std::sync::Arc; use std::sync::Arc;
use actix::prelude::*; use actix::prelude::*;
use argon2_creds::{Config, ConfigBuilder, PasswordPolicy}; use argon2_creds::{Config, ConfigBuilder, PasswordPolicy};
use lettre::{
transport::smtp::authentication::Credentials, AsyncSmtpTransport, Tokio1Executor,
};
use libmcaptcha::cache::hashcache::HashCache; use libmcaptcha::cache::hashcache::HashCache;
use libmcaptcha::cache::redis::RedisCache; use libmcaptcha::cache::redis::RedisCache;
use libmcaptcha::master::redis::master::Master as RedisMaster; use libmcaptcha::master::redis::master::Master as RedisMaster;
@ -39,12 +43,9 @@ use sqlx::PgPool;
use crate::SETTINGS; use crate::SETTINGS;
pub struct Data { /// Represents mCaptcha cache and master system.
pub db: PgPool, /// When Redis is configured, [SystemGroup::Redis] is used and
pub creds: Config, /// in its absense, [SystemGroup::Embedded] is used
pub captcha: SystemGroup,
}
pub enum SystemGroup { pub enum SystemGroup {
Embedded(System<HashCache, EmbeddedMaster>), Embedded(System<HashCache, EmbeddedMaster>),
Redis(System<RedisCache, RedisMaster>), Redis(System<RedisCache, RedisMaster>),
@ -89,10 +90,59 @@ impl SystemGroup {
// }; // };
// Ok(()) // Ok(())
// } // }
fn new_system<A: Save, B: MasterTrait>(m: Addr<B>, c: Addr<A>) -> System<A, B> {
let pow = PoWConfigBuilder::default()
.salt(SETTINGS.pow.salt.clone())
.build()
.unwrap();
SystemBuilder::default().pow(pow).cache(c).master(m).build()
}
// read settings, if Redis is configured then produce a Redis mCaptcha cache
// based SystemGroup
async fn new() -> Self {
match &SETTINGS.redis {
Some(val) => {
let master = RedisMaster::new(RedisConfig::Single(val.url.clone()))
.await
.unwrap()
.start();
let cache = RedisCache::new(RedisConfig::Single(val.url.clone()))
.await
.unwrap()
.start();
let captcha = Self::new_system(master, cache);
SystemGroup::Redis(captcha)
}
None => {
let master = EmbeddedMaster::new(SETTINGS.pow.gc).start();
let cache = HashCache::default().start();
let captcha = Self::new_system(master, cache);
SystemGroup::Embedded(captcha)
}
}
}
}
/// App data
pub struct Data {
/// databse pool
pub db: PgPool,
/// credential management configuration
pub creds: Config,
/// mCaptcha system: Redis cache, etc.
pub captcha: SystemGroup,
/// email client
pub mailer: Option<Mailer>,
} }
impl Data { impl Data {
#[cfg(not(tarpaulin_include))] #[cfg(not(tarpaulin_include))]
/// create new instance of app data
pub async fn new() -> Arc<Self> { pub async fn new() -> Arc<Self> {
let db = PgPoolOptions::new() let db = PgPoolOptions::new()
.max_connections(SETTINGS.database.pool) .max_connections(SETTINGS.database.pool)
@ -112,46 +162,31 @@ impl Data {
creds.init(); creds.init();
log::info!("Initialized credential manager"); log::info!("Initialized credential manager");
let data = match &SETTINGS.redis { let data = Data {
Some(val) => {
let master = RedisMaster::new(RedisConfig::Single(val.url.clone()))
.await
.unwrap()
.start();
let cache = RedisCache::new(RedisConfig::Single(val.url.clone()))
.await
.unwrap()
.start();
let captcha = Self::new_system(master, cache);
Data {
creds, creds,
db, db,
captcha: SystemGroup::Redis(captcha), captcha: SystemGroup::new().await,
} mailer: Self::get_mailer(),
}
None => {
let master = EmbeddedMaster::new(SETTINGS.pow.gc).start();
let cache = HashCache::default().start();
let captcha = Self::new_system(master, cache);
Data {
creds,
db,
captcha: SystemGroup::Embedded(captcha),
}
}
}; };
Arc::new(data) Arc::new(data)
} }
fn new_system<A: Save, B: MasterTrait>(m: Addr<B>, c: Addr<A>) -> System<A, B> { fn get_mailer() -> Option<Mailer> {
let pow = PoWConfigBuilder::default() if let Some(smtp) = SETTINGS.smtp.as_ref() {
.salt(SETTINGS.pow.salt.clone()) let creds =
.build() Credentials::new(smtp.username.to_string(), smtp.password.to_string()); // "smtp_username".to_string(), "smtp_password".to_string());
.unwrap();
SystemBuilder::default().pow(pow).cache(c).master(m).build() let mailer: Mailer = AsyncSmtpTransport::<Tokio1Executor>::relay(&smtp.url) //"smtp.gmail.com")
.unwrap()
.credentials(creds)
.build();
Some(mailer)
} else {
None
}
} }
} }
/// Mailer data type AsyncSmtpTransport<Tokio1Executor>
pub type Mailer = AsyncSmtpTransport<Tokio1Executor>;

View file

@ -1,77 +0,0 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// The html we want to send.
const HTML: &str = r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello from Lettre!</title>
</head>
<body>
<div style="display: flex; flex-direction: column; align-items: center;">
<h2 style="font-family: Arial, Helvetica, sans-serif;">Hello from Lettre!</h2>
<h4 style="font-family: Arial, Helvetica, sans-serif;">A mailer library for Rust</h4>
</div>
</body>
</html>"#;
use lettre::{
message::{header, MultiPart, SinglePart},
transport::smtp::authentication::Credentials,
AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
};
async fn email() {
let email = Message::builder()
.from("NoBody <nobody@domain.tld>".parse().unwrap())
.reply_to("Yuin <yuin@domain.tld>".parse().unwrap())
.to("Hei <hei@domain.tld>".parse().unwrap())
.subject("Happy new async year")
.multipart(
MultiPart::alternative() // This is composed of two parts.
.singlepart(
SinglePart::builder()
.header(header::ContentType::TEXT_PLAIN)
.body(String::from(
"Hello from Lettre! A mailer library for Rust",
)), // Every message should have a plain text fallback.
)
.singlepart(
SinglePart::builder()
.header(header::ContentType::TEXT_HTML)
.body(String::from(HTML)),
),
)
.unwrap();
let creds =
Credentials::new("smtp_username".to_string(), "smtp_password".to_string());
let mailer: AsyncSmtpTransport<Tokio1Executor> =
AsyncSmtpTransport::<Tokio1Executor>::relay("smtp.gmail.com")
.unwrap()
.credentials(creds)
.build();
// Send the email
match mailer.send(email).await {
Ok(_) => println!("Email sent successfully!"),
Err(e) => panic!("Could not send email: {:?}", e),
}
}

18
src/email/mod.rs Normal file
View file

@ -0,0 +1,18 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod verification;

75
src/email/verification.rs Normal file
View file

@ -0,0 +1,75 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//! Email operations: verification, notification, etc
use lettre::{
message::{header, MultiPart, SinglePart},
AsyncTransport, Message,
};
use crate::AppData;
use crate::SETTINGS;
// The html we want to send.
const HTML: &str = r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello from Lettre!</title>
</head>
<body>
<div style="display: flex; flex-direction: column; align-items: center;">
<h2 style="font-family: Arial, Helvetica, sans-serif;">Hello from Lettre!</h2>
<h4 style="font-family: Arial, Helvetica, sans-serif;">A mailer library for Rust</h4>
</div>
</body>
</html>"#;
async fn verification(data: &AppData) {
if let Some(smtp) = SETTINGS.smtp.as_ref() {
let from = format!("mCaptcha Admin <{}>", smtp.from);
const SUBJECT: &str = "[mCaptcha] Please verify your email";
let email = Message::builder()
.from(from.parse().unwrap())
.reply_to("Yuin <yuin@domain.tld>".parse().unwrap())
.to("Hei <hei@domain.tld>".parse().unwrap())
.subject(SUBJECT)
.multipart(
MultiPart::alternative() // This is composed of two parts.
.singlepart(
SinglePart::builder()
.header(header::ContentType::TEXT_PLAIN)
.body(String::from(
"Hello from Lettre! A mailer library for Rust",
)), // Every message should have a plain text fallback.
)
.singlepart(
SinglePart::builder()
.header(header::ContentType::TEXT_HTML)
.body(String::from(HTML)),
),
)
.unwrap();
// unwrap is OK as SETTINGS.smtp is check at the start
match data.mailer.as_ref().unwrap().send(email).await {
Ok(_) => println!("Email sent successfully!"),
Err(e) => panic!("Could not send email: {:?}", e),
}
}
}