#11 signup email #36

Merged
silver merged 5 commits from #11_signup_email into main 2023-08-06 12:02:40 +00:00
6 changed files with 420 additions and 372 deletions

View file

@ -10,9 +10,6 @@ name = "update_data"
[[bin]] [[bin]]
name = "update_groups" name = "update_groups"
[[bin]]
name = "new_users"
[dependencies] [dependencies]
# for the ldap # for the ldap
ldap3="0.11.1" ldap3="0.11.1"

View file

@ -44,7 +44,20 @@ Each value is either a string or ``null``.
Changing ``userPassword`` requires the existing password in teh apssword field and the new one in teh value field. Changing ``userPassword`` requires the existing password in teh apssword field and the new one in teh value field.
### POST /ldap/new ### POST /ldap/new/email
Kickstarts teh process of signing up to Skynet
```json
{
"email" : "User's wolves email"
}
```
### POST /ldap/new/account
Verifies teh user has access to this email
```json ```json
{ {

View file

@ -102,7 +102,7 @@
# modify these # modify these
scripts = { scripts = {
"update_data" = "*:0,15,30,45"; "update_data" = "*:0,15,30,45";
"new_users" = "*:5,20,35,50"; #"new_users" = "*:5,20,35,50";
"update_groups" = "*:10"; "update_groups" = "*:10";
}; };

View file

@ -1,197 +0,0 @@
use lettre::{
message::{header, MultiPart, SinglePart},
transport::smtp::{authentication::Credentials, response::Response},
Message, SmtpTransport, Transport,
};
use maud::html;
use skynet_ldap_backend::{db_init, get_config, get_now_iso, get_wolves, random_string, AccountWolves, Accounts, AccountsNew, Config};
use sqlx::{Pool, Sqlite};
#[async_std::main]
async fn main() {
let config = get_config();
let db = db_init(&config).await.unwrap();
for record in get_wolves(&db).await {
// skynet emails not permitted
if record.email.trim().ends_with("@skynet.ie") {
continue;
}
// check if the email is already in the db
if !check(&db, &record.email).await {
continue;
}
// generate a auth key
let auth = random_string(50);
match send_mail(&config, &record, &auth) {
Ok(_) => match save_to_db(&db, &record, &auth).await {
Ok(_) => {}
Err(e) => {
println!("Unable to save to db {} {e:?}", &record.email);
}
},
Err(e) => {
println!("Unable to send mail to {} {e:?}", &record.email);
}
}
}
}
async fn check(db: &Pool<Sqlite>, mail: &str) -> bool {
check_pending(db, mail).await && check_users(db, mail).await
}
async fn check_users(db: &Pool<Sqlite>, mail: &str) -> bool {
sqlx::query_as::<_, Accounts>(
r#"
SELECT *
FROM accounts
WHERE mail == ?
"#,
)
.bind(mail)
.fetch_all(db)
.await
.unwrap_or(vec![])
.is_empty()
}
async fn check_pending(db: &Pool<Sqlite>, mail: &str) -> bool {
sqlx::query_as::<_, AccountsNew>(
r#"
SELECT *
FROM accounts_new
WHERE mail == ?
"#,
)
.bind(mail)
.fetch_all(db)
.await
.unwrap_or(vec![])
.is_empty()
}
// using https://github.com/lettre/lettre/blob/57886c367d69b4d66300b322c94bd910b1eca364/examples/maud_html.rs
fn send_mail(config: &Config, record: &AccountWolves, auth: &str) -> Result<Response, lettre::transport::smtp::Error> {
let recipient = &record.name_first;
let mail = &record.email;
let url_base = "https://sso.skynet.ie";
let link_new = format!("{url_base}/register?auth={auth}");
let link_mod = format!("{url_base}/modify");
let discord = "https://discord.gg/mkuKJkCuyM";
let sender = format!("UL Computer Society <{}>", &config.mail_user);
// Create the html we want to send.
let html = html! {
head {
title { "Hello from Skynet!" }
style type="text/css" {
"h2, h4 { font-family: Arial, Helvetica, sans-serif; }"
}
}
div style="display: flex; flex-direction: column; align-items: center;" {
h2 { "Hello from Skynet!" }
// Substitute in the name of our recipient.
p { "Hi " (recipient) "," }
p {
"As part of the UL Computer Society you get an account on our Skynet cluster."
br;
"This gives you access to some of teh various services we offer:"
ul {
li { "Email" }
li { "Gitlab" }
li { "Linux Webhost" }
}
br;
"The following invite will remain active until the end of year."
}
p {
"If you are a new member please use the following link:"
br;
a href=(link_new) { (link_new) }
}
p {
"If you are a returning user please set an email for your account at:"
br;
a href=(link_mod) { (link_mod) }
}
p {
"If you have issues please refer to our Discord server:"
br;
a href=(discord) { (discord) }
}
p {
"Skynet Team"
br;
"UL Computer Society"
}
}
};
let body_text = format!(
r#"
Hi {recipient}
As part of the UL Computer Society you get an account on our Skynet cluster.
This gives you access to some of teh various services we offer:
* Email
* Gitlab
* Linux Webhost
The following invite will remain active until the end of year.
If you are a new member please use the following link:
{link_new}
If you are a returning user please set an email for your account at:
{link_mod}
If you have issues please refer to our Discord server:
{discord}
Skynet Team
UL Computer Society
"#
);
// Build the message.
let email = Message::builder()
.from(sender.parse().unwrap())
.to(mail.parse().unwrap())
.subject("Skynet: New Account.")
.multipart(
// This is composed of two parts.
// also helps not trip spam settings (uneven number of url's
MultiPart::alternative()
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text))
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())),
)
.expect("failed to build email");
let creds = Credentials::new(config.mail_user.clone(), config.mail_pass.clone());
// Open a remote connection to gmail using STARTTLS
let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build();
// Send the email
mailer.send(&email)
}
async fn save_to_db(db: &Pool<Sqlite>, record: &AccountWolves, auth: &str) -> Result<Option<AccountsNew>, sqlx::Error> {
sqlx::query_as::<_, AccountsNew>(
"
INSERT OR REPLACE INTO accounts_new (mail, auth_code, date_iso, date_expiry, name_first, name_surname, id_student)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
",
)
.bind(record.email.to_owned())
.bind(auth.to_owned())
.bind(get_now_iso(false))
.bind(record.expiry.to_owned())
.bind(record.name_first.to_owned())
.bind(record.name_second.to_owned())
.bind(record.id_student.to_owned())
.fetch_optional(db)
.await
}

View file

@ -1,6 +1,9 @@
use skynet_ldap_backend::{ use skynet_ldap_backend::{
db_init, get_config, db_init, get_config,
methods::{account_new::post_new_account, account_update::post_update_ldap}, methods::{
account_new::post::{account, email},
account_update::post_update_ldap,
},
State, State,
}; };
@ -21,7 +24,8 @@ async fn main() -> tide::Result<()> {
let mut app = tide::with_state(state); let mut app = tide::with_state(state);
app.at("/ldap/update").post(post_update_ldap); app.at("/ldap/update").post(post_update_ldap);
app.at("/ldap/new").post(post_new_account); app.at("/ldap/new/email").post(email::submit);
app.at("/ldap/new/account").post(account::submit);
app.listen(host_port).await?; app.listen(host_port).await?;
Ok(()) Ok(())

View file

@ -1,5 +1,11 @@
use crate::{get_now_iso, random_string, Accounts, AccountsNew, Config, State}; use crate::{get_now_iso, random_string, AccountWolves, Accounts, AccountsNew, Config, State};
use ldap3::{exop::PasswordModify, LdapConn, Scope}; use ldap3::{exop::PasswordModify, LdapConn, Scope};
use lettre::{
message::{header, MultiPart, SinglePart},
transport::smtp::authentication::Credentials,
Message, SmtpTransport, Transport,
};
use maud::html;
use sqlx::{Error, Pool, Sqlite}; use sqlx::{Error, Pool, Sqlite};
use std::collections::HashSet; use std::collections::HashSet;
use tide::{ use tide::{
@ -7,17 +13,240 @@ use tide::{
Request, Request,
}; };
#[derive(Debug, Deserialize)] pub mod post {
pub struct LdapNewUser { use super::*;
pub mod email {
use super::*;
#[derive(Debug, Deserialize)]
struct SignupEmail {
email: String,
}
pub async fn submit(mut req: Request<State>) -> tide::Result {
let SignupEmail {
email,
} = req.body_json().await?;
let config = &req.state().config;
let db = &req.state().db;
for record in get_wolves_mail(db, &email).await {
// skynet emails not permitted
if record.email.trim().ends_with("@skynet.ie") {
continue;
}
// check if the email is already in the db
if !check(db, &record.email).await {
continue;
}
// generate a auth key
let auth = random_string(75);
match send_mail(config, &record, &auth) {
Ok(_) => match save_to_db(db, &record, &auth).await {
Ok(_) => {}
Err(e) => {
println!("Unable to save to db {} {e:?}", &record.email);
}
},
Err(e) => {
println!("Unable to send mail to {} {e:?}", &record.email);
}
}
}
Ok(json!({"result": "success"}).into())
}
async fn get_wolves_mail(db: &Pool<Sqlite>, mail: &str) -> Vec<AccountWolves> {
sqlx::query_as::<_, AccountWolves>(
r#"
SELECT *
FROM accounts_wolves
WHERE email = ?
"#,
)
.bind(mail)
.fetch_all(db)
.await
.unwrap_or(vec![])
}
async fn check(db: &Pool<Sqlite>, mail: &str) -> bool {
check_pending(db, mail).await && check_users(db, mail).await
}
async fn check_users(db: &Pool<Sqlite>, mail: &str) -> bool {
sqlx::query_as::<_, Accounts>(
r#"
SELECT *
FROM accounts
WHERE mail == ?
"#,
)
.bind(mail)
.fetch_all(db)
.await
.unwrap_or(vec![])
.is_empty()
}
async fn check_pending(db: &Pool<Sqlite>, mail: &str) -> bool {
sqlx::query_as::<_, AccountsNew>(
r#"
SELECT *
FROM accounts_new
WHERE mail == ?
"#,
)
.bind(mail)
.fetch_all(db)
.await
.unwrap_or(vec![])
.is_empty()
}
// using https://github.com/lettre/lettre/blob/57886c367d69b4d66300b322c94bd910b1eca364/examples/maud_html.rs
fn send_mail(config: &Config, record: &AccountWolves, auth: &str) -> Result<lettre::transport::smtp::response::Response, lettre::transport::smtp::Error> {
let recipient = &record.name_first;
let mail = &record.email;
let url_base = "https://sso.skynet.ie";
let link_new = format!("{url_base}/register?auth={auth}");
let link_mod = format!("{url_base}/modify");
let discord = "https://discord.gg/mkuKJkCuyM";
let sender = format!("UL Computer Society <{}>", &config.mail_user);
// Create the html we want to send.
let html = html! {
head {
title { "Hello from Skynet!" }
style type="text/css" {
"h2, h4 { font-family: Arial, Helvetica, sans-serif; }"
}
}
div style="display: flex; flex-direction: column; align-items: center;" {
h2 { "Hello from Skynet!" }
// Substitute in the name of our recipient.
p { "Hi " (recipient) "," }
p {
"As part of the UL Computer Society you get an account on our Skynet cluster."
br;
"This gives you access to some of teh various services we offer:"
ul {
li { "Email" }
li { "Gitlab" }
li { "Linux Webhost" }
}
br;
"The following invite will remain active until the end of year."
}
p {
"If you are a new member please use the following link:"
br;
a href=(link_new) { (link_new) }
}
p {
"If you are a returning user please set an email for your account at:"
br;
a href=(link_mod) { (link_mod) }
}
p {
"If you have issues please refer to our Discord server:"
br;
a href=(discord) { (discord) }
}
p {
"Skynet Team"
br;
"UL Computer Society"
}
}
};
let body_text = format!(
r#"
Hi {recipient}
As part of the UL Computer Society you get an account on our Skynet cluster.
This gives you access to some of teh various services we offer:
* Email
* Gitlab
* Linux Webhost
The following invite will remain active until the end of year.
If you are a new member please use the following link:
{link_new}
If you are a returning user please set an email for your account at:
{link_mod}
If you have issues please refer to our Discord server:
{discord}
Skynet Team
UL Computer Society
"#
);
// Build the message.
let email = Message::builder()
.from(sender.parse().unwrap())
.to(mail.parse().unwrap())
.subject("Skynet: New Account.")
.multipart(
// This is composed of two parts.
// also helps not trip spam settings (uneven number of url's
MultiPart::alternative()
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text))
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())),
)
.expect("failed to build email");
let creds = Credentials::new(config.mail_user.clone(), config.mail_pass.clone());
// Open a remote connection to gmail using STARTTLS
let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build();
// Send the email
mailer.send(&email)
}
async fn save_to_db(db: &Pool<Sqlite>, record: &AccountWolves, auth: &str) -> Result<Option<AccountsNew>, sqlx::Error> {
sqlx::query_as::<_, AccountsNew>(
"
INSERT OR REPLACE INTO accounts_new (mail, auth_code, date_iso, date_expiry, name_first, name_surname, id_student)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
",
)
.bind(record.email.to_owned())
.bind(auth.to_owned())
.bind(get_now_iso(false))
.bind(record.expiry.to_owned())
.bind(record.name_first.to_owned())
.bind(record.name_second.to_owned())
.bind(record.id_student.to_owned())
.fetch_optional(db)
.await
}
}
pub mod account {
use super::*;
#[derive(Debug, Deserialize)]
struct LdapNewUser {
auth: String, auth: String,
user: String, user: String,
pass: String, pass: String,
} }
/// Handles initial detail entering page /// Handles initial detail entering page
/// Verify users have access to said email /// Verify users have access to said email
/// Get users to set username and password. /// Get users to set username and password.
pub async fn post_new_account(mut req: Request<State>) -> tide::Result { pub async fn submit(mut req: Request<State>) -> tide::Result {
let LdapNewUser { let LdapNewUser {
auth, auth,
user, user,
@ -64,10 +293,10 @@ pub async fn post_new_account(mut req: Request<State>) -> tide::Result {
account_verification_clear_pending(db, &auth).await?; account_verification_clear_pending(db, &auth).await?;
Ok(json!({"result": "success"}).into()) Ok(json!({"result": "success"}).into())
} }
// clear the db of expired ones before checking for username and validating inputs // clear the db of expired ones before checking for username and validating inputs
async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsNew>, Error> { async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsNew>, Error> {
sqlx::query_as::<_, AccountsNew>( sqlx::query_as::<_, AccountsNew>(
r#" r#"
DELETE DELETE
@ -78,9 +307,9 @@ async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsNew
.bind(get_now_iso(true)) .bind(get_now_iso(true))
.fetch_all(pool) .fetch_all(pool)
.await .await
} }
fn is_valid_name(name: &str) -> Option<String> { fn is_valid_name(name: &str) -> Option<String> {
// max length is 31 chars // max length is 31 chars
if name.len() >= 32 { if name.len() >= 32 {
return Some(String::from("Too long, max len 31")); return Some(String::from("Too long, max len 31"));
@ -106,9 +335,9 @@ fn is_valid_name(name: &str) -> Option<String> {
} }
None None
} }
async fn db_get_user(pool: &Pool<Sqlite>, auth: &str) -> Option<AccountsNew> { async fn db_get_user(pool: &Pool<Sqlite>, auth: &str) -> Option<AccountsNew> {
if let Ok(res) = sqlx::query_as::<_, AccountsNew>( if let Ok(res) = sqlx::query_as::<_, AccountsNew>(
r#" r#"
SELECT * SELECT *
@ -126,9 +355,9 @@ async fn db_get_user(pool: &Pool<Sqlite>, auth: &str) -> Option<AccountsNew> {
} }
None None
} }
async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsNew, username: &str, pass: &str) -> Result<(), ldap3::LdapError> { async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsNew, username: &str, pass: &str) -> Result<(), ldap3::LdapError> {
let mut ldap = LdapConn::new(&config.ldap_host)?; let mut ldap = LdapConn::new(&config.ldap_host)?;
ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?; ldap.simple_bind(&config.ldap_admin, &config.ldap_admin_pw)?.success()?;
@ -185,16 +414,16 @@ async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsN
ldap.unbind()?; ldap.unbind()?;
Ok(()) Ok(())
} }
fn get_sk_created() -> String { fn get_sk_created() -> String {
use chrono::Utc; use chrono::Utc;
let now = Utc::now(); let now = Utc::now();
format!("{}", now.format("%Y%m%d%H%M%SZ")) format!("{}", now.format("%Y%m%d%H%M%SZ"))
} }
async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 { async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 {
if let Ok(results) = sqlx::query_as::<_, Accounts>( if let Ok(results) = sqlx::query_as::<_, Accounts>(
r#" r#"
SELECT * SELECT *
@ -212,9 +441,9 @@ async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 {
} }
9999 9999
} }
async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsNew>, Error> { async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsNew>, Error> {
sqlx::query_as::<_, AccountsNew>( sqlx::query_as::<_, AccountsNew>(
r#" r#"
DELETE FROM accounts_new DELETE FROM accounts_new
@ -224,4 +453,6 @@ async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str)
.bind(auth_code) .bind(auth_code)
.fetch_all(db) .fetch_all(db)
.await .await
}
}
} }