feat: simplified the signup

This commit is contained in:
silver 2023-07-30 02:50:13 +01:00
parent 970e566dea
commit 63b59432a3
7 changed files with 136 additions and 313 deletions

View file

@ -34,10 +34,9 @@ Changing ``userPassword`` requires the existing password in teh apssword field a
```json ```json
{ {
"auth" : "Authcode from the email",
"user" : "username the user wants", "user" : "username the user wants",
"mail" : "An email account that matches what is on wolves", "pass" : "password teh user wants"
"name_first": "Firstname",
"name_second": "Surname"
} }
``` ```
@ -46,26 +45,11 @@ Username taken:
{"result": "error", "error": "username not available"} {"result": "error", "error": "username not available"}
``` ```
Email used: Invalid Auth:
```json ```json
{"result": "error", "error": "email in use"} {"result": "error", "error": "Invalid auth"}
``` ```
### POST /ldap/new/verify
```json
{
"auth_code": "Auth code that got send in the email",
"password": "Password the user wants to use"
}
```
Auth code non existent:
```json
{"result": "error"}
```
## Responses ## Responses
Generic responses which is used unless otherwise specified above. Generic responses which is used unless otherwise specified above.

View file

@ -4,7 +4,7 @@ use lettre::{
Message, SmtpTransport, Transport, Message, SmtpTransport, Transport,
}; };
use maud::html; use maud::html;
use skynet_ldap_backend::{db_init, get_config, read_csv, Accounts, AccountsNew, Config, Record, get_now_iso, random_string}; use skynet_ldap_backend::{db_init, get_config, get_now_iso, random_string, read_csv, Accounts, AccountsNew, Config, Record};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
#[async_std::main] #[async_std::main]
@ -164,8 +164,8 @@ fn send_mail(config: &Config, record: &Record, auth: &str) -> Result<Response, l
async fn save_to_db(db: &Pool<Sqlite>, record: &Record, auth: &str) -> Result<Option<AccountsNew>, sqlx::Error> { async fn save_to_db(db: &Pool<Sqlite>, record: &Record, auth: &str) -> Result<Option<AccountsNew>, sqlx::Error> {
sqlx::query_as::<_, AccountsNew>( sqlx::query_as::<_, AccountsNew>(
" "
INSERT OR REPLACE INTO accounts_new (mail, auth_code, date_iso, date_expiry, name_first, name_surname) 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) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
", ",
) )
.bind(record.email.to_owned()) .bind(record.email.to_owned())
@ -174,6 +174,7 @@ async fn save_to_db(db: &Pool<Sqlite>, record: &Record, auth: &str) -> Result<Op
.bind(record.expiry.to_owned()) .bind(record.expiry.to_owned())
.bind(record.name_first.to_owned()) .bind(record.name_first.to_owned())
.bind(record.name_second.to_owned()) .bind(record.name_second.to_owned())
.bind(record.id_student.to_owned())
.fetch_optional(db) .fetch_optional(db)
.await .await
} }

View file

@ -1,6 +1,6 @@
use dotenvy::dotenv; use dotenvy::dotenv;
use ldap3::{LdapConn, Mod}; use ldap3::{LdapConn, Mod};
use skynet_ldap_backend::{db_init, get_config, read_csv, Accounts, Config, get_now_iso}; use skynet_ldap_backend::{db_init, get_config, get_now_iso, read_csv, Accounts, Config};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use std::{collections::HashSet, env, error::Error}; use std::{collections::HashSet, env, error::Error};

View file

@ -1,14 +1,17 @@
pub mod methods; pub mod methods;
use chrono::{Datelike, SecondsFormat, Utc};
use dotenvy::dotenv; use dotenvy::dotenv;
use ldap3::{LdapConn, Scope, SearchEntry}; use ldap3::{LdapConn, Scope, SearchEntry};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use rand::{distributions::Alphanumeric, thread_rng, Rng};
use sqlx::{Error, Pool, Sqlite}; use sqlx::{
use std::env; sqlite::{SqliteConnectOptions, SqlitePoolOptions},
use std::str::FromStr; Error, Pool, Sqlite,
use std::time::{SystemTime, UNIX_EPOCH}; };
use chrono::{Datelike, SecondsFormat, Utc}; use std::{
use rand::distributions::Alphanumeric; env,
use rand::{Rng, thread_rng}; str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use tide::prelude::*; use tide::prelude::*;
#[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)] #[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)]
@ -19,20 +22,7 @@ pub struct AccountsNew {
pub date_expiry: String, pub date_expiry: String,
pub name_first: String, pub name_first: String,
pub name_surname: String, pub name_surname: String,
} pub id_student: String,
#[derive(Debug, Deserialize, Serialize, sqlx::FromRow)]
pub struct AccountsPending {
user: String,
mail: String,
cn: String,
sn: String,
auth_code: String,
// action will be what to do with it
action: String,
// will only last for a few hours
expiry: i64,
} }
#[derive(Debug, Deserialize, Serialize, sqlx::FromRow)] #[derive(Debug, Deserialize, Serialize, sqlx::FromRow)]
@ -53,20 +43,6 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
.connect_with(SqliteConnectOptions::from_str(&format!("sqlite://{}", database))?.create_if_missing(true)) .connect_with(SqliteConnectOptions::from_str(&format!("sqlite://{}", database))?.create_if_missing(true))
.await?; .await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS accounts_pending (
user text primary key,
mail text not null,
cn text not null,
sn text not null,
action text not null,
auth_code text not null,
expiry integer not null
)",
)
.execute(&pool)
.await?;
sqlx::query( sqlx::query(
"CREATE TABLE IF NOT EXISTS accounts_new ( "CREATE TABLE IF NOT EXISTS accounts_new (
mail text primary key, mail text primary key,
@ -74,7 +50,8 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
date_iso text not null, date_iso text not null,
date_expiry text not null, date_expiry text not null,
name_first text not null, name_first text not null,
name_surname integer not null name_surname integer not null,
id_student text not null
)", )",
) )
.execute(&pool) .execute(&pool)
@ -100,6 +77,10 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
.await?; .await?;
sqlx::query("CREATE INDEX IF NOT EXISTS index_uid_number ON accounts (uid)").execute(&pool).await?; sqlx::query("CREATE INDEX IF NOT EXISTS index_uid_number ON accounts (uid)").execute(&pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS index_mail ON accounts (mail)").execute(&pool).await?;
sqlx::query("CREATE INDEX IF NOT EXISTS index_student_id ON accounts (student_id)")
.execute(&pool)
.await?;
update_accounts(&pool, config).await; update_accounts(&pool, config).await;

View file

@ -1,6 +1,8 @@
use skynet_ldap_backend::methods::account_new::{post_new_account, post_new_account_confirmation}; use skynet_ldap_backend::{
use skynet_ldap_backend::methods::account_update::post_update_ldap; db_init, get_config,
use skynet_ldap_backend::{db_init, get_config, State}; methods::{account_new::post_new_account, account_update::post_update_ldap},
State,
};
#[async_std::main] #[async_std::main]
async fn main() -> tide::Result<()> { async fn main() -> tide::Result<()> {
@ -19,9 +21,7 @@ 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").post(post_new_account);
app.at("/ldap/new/verify").post(post_new_account_confirmation);
app.listen(host_port).await?; app.listen(host_port).await?;
Ok(()) Ok(())

View file

@ -1,42 +1,40 @@
use crate::{Accounts, AccountsPending, State, get_now_iso, AccountsNew, random_string}; use crate::{get_now_iso, random_string, Accounts, AccountsNew, Config, State};
use ldap3::exop::PasswordModify; use ldap3::{exop::PasswordModify, LdapConn, Scope};
use ldap3::result::ExopResult;
use ldap3::{LdapConn, Scope};
use sqlx::{Error, Pool, Sqlite}; use sqlx::{Error, Pool, Sqlite};
use std::collections::HashSet; use std::collections::HashSet;
use tide::prelude::{json, Deserialize}; use tide::{
use tide::Request; prelude::{json, Deserialize},
Request,
};
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct LdapNewUser { pub struct LdapNewUser {
auth: String,
user: String, user: String,
// email that is used on wolves pass: String,
mail: String,
name_first: String,
name_second: String,
} }
/// Handles initial detail entering page /// Handles initial detail entering page
/// Verify users have access to said email
/// Get users to set username and password.
pub async fn post_new_account(mut req: Request<State>) -> tide::Result { pub async fn post_new_account(mut req: Request<State>) -> tide::Result {
// check if username exists
// search ldap and local
// send back that that username is in use
// check local if email exists (periodic sync)
// if not then request info on individual user
// if there is no email matching still send 200 back
// if there is then send email with link to the account
// save user details in the db
let LdapNewUser { let LdapNewUser {
auth,
user, user,
mail, pass,
name_first,
name_second,
} = req.body_json().await?; } = req.body_json().await?;
let config = &req.state().config; let config = &req.state().config;
let db = &req.state().db;
// ensure there are no old requests
db_pending_clear_expired(db).await?;
let user_db = if let Some(x) = db_get_user(db, &auth).await {
x
} else {
return Ok(json!({"result": "error", "error": "Invalid auth"}).into());
};
// easier to give each request its own connection // easier to give each request its own connection
let mut ldap = LdapConn::new(&config.ldap_host)?; let mut ldap = LdapConn::new(&config.ldap_host)?;
@ -53,101 +51,24 @@ pub async fn post_new_account(mut req: Request<State>) -> tide::Result {
} }
} }
let filter_email = format!("(mail={})", mail); // done with anon ldap
if let Ok(x) = ldap.search("ou=users,dc=skynet,dc=ie", Scope::OneLevel, &filter_email, vec!["*"]) {
if let Ok((rs, _res)) = x.success() {
if !rs.is_empty() {
return Ok(json!({"result": "error", "error": "email in use"}).into());
}
}
}
// done with ldap
ldap.unbind()?; ldap.unbind()?;
// setup the pool, going to need it for the rest of it ldap_create_account(config, db, user_db, &user, &pass).await?;
let pool = &req.state().db;
db_pending_clear_expired(pool).await?; // account now created, delete from the new table
account_verification_clear_pending(db, &auth).await?;
// now check local
if let Ok(results) = sqlx::query_as::<_, AccountsPending>(
r#"
SELECT *
FROM accounts_pending
WHERE user == ?
"#,
)
.bind(&user)
.fetch_all(pool)
.await
{
if !results.is_empty() {
return Ok(json!({"result": "error", "error": "username not available"}).into());
}
}
if let Ok(results) = sqlx::query_as::<_, AccountsPending>(
r#"
SELECT *
FROM accounts_pending
WHERE mail == ?
"#,
)
.bind(&mail)
.fetch_all(pool)
.await
{
if !results.is_empty() {
return Ok(json!({"result": "error", "error": "email in use"}).into());
}
}
// frontend now tells user to check their email
/*
TODO:
now check with wolves to see if the email is already activated
use email as primary match
then search up to see if teh wolves ID has a match
if not generate tuhe user and send email
*/
let cn = format!("{} {}", name_first, name_second);
let auth_code = create_random_string(50);
// 1 hour expiry
let expiry = get_now() + (60 * 60);
sqlx::query_as::<_, AccountsPending>(
r#"
INSERT OR REPLACE INTO accounts_pending (user, mail, cn, sn, action, auth_code, expiry)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
"#,
)
.bind(&user)
.bind(&mail)
.bind(&cn)
.bind(&name_second)
.bind("account_new")
.bind(&auth_code)
.bind(expiry)
.fetch_optional(pool)
.await
.ok();
// TODO: Send email with auth_code
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<AccountsPending>, Error> { async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsNew>, Error> {
let now = get_now(); sqlx::query_as::<_, AccountsNew>(
sqlx::query_as::<_, AccountsPending>(
r#" r#"
DELETE DELETE
FROM accounts_pending FROM accounts_new
WHERE expiry < ? WHERE date_expiry < ?
"#, "#,
) )
.bind(get_now_iso(true)) .bind(get_now_iso(true))
@ -155,57 +76,83 @@ async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Result<Vec<AccountsPen
.await .await
} }
async fn db_get_user(pool: &Pool<Sqlite>, auth: &str) -> Option<AccountsNew> {
#[derive(Debug, Deserialize)] if let Ok(res) = sqlx::query_as::<_, AccountsNew>(
pub struct LdapUserVerify { r#"
auth_code: String, SELECT *
password: String, FROM accounts_new
WHERE auth_code == ?
"#,
)
.bind(auth)
.fetch_all(pool)
.await
{
if !res.is_empty() {
return Some(res[0].to_owned());
}
} }
/// Handles the verification that a user has access to the email None
pub async fn post_new_account_confirmation(mut req: Request<State>) -> tide::Result { }
let user_verify: LdapUserVerify = req.body_json().await?;
let State { async fn ldap_create_account(config: &Config, db: &Pool<Sqlite>, user: AccountsNew, username: &str, pass: &str) -> Result<(), ldap3::LdapError> {
db,
config,
..
} = &req.state();
// setup ldap connection
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()?;
// make sure to clear out the expired ones first let dn = format!("uid={},ou=users,dc=skynet,dc=ie", username);
db_pending_clear_expired(db).await?; let cn = format!("{} {}", &user.name_first, &user.name_surname);
let home_directory = format!("/home/{}", username);
// search db for auth_code let password_tmp = random_string(50);
let results = account_verification_find_pending(db, "account_new", &user_verify.auth_code).await; let labeled_uri = format!("ldap:///ou=groups,dc=skynet,dc=ie??sub?(&(objectclass=posixgroup)(memberuid={}))", username);
let sk_mail = format!("{}@skynet.ie", username);
if results.is_empty() { let sk_created = get_sk_created();
return Ok(json!({"result": "error"}).into());
}
let user_details = &results[0];
let uid_number = get_max_uid_number(db).await; let uid_number = get_max_uid_number(db).await;
// create teh new user account in ldap // create user
account_verification_new_account(&mut ldap, user_details, uid_number).await?; ldap.add(
&dn,
vec![
("objectClass", HashSet::from(["top", "person", "posixaccount", "ldapPublicKey", "inetOrgPerson", "skPerson"])),
// top
("ou", HashSet::from(["users"])),
// person
("uid", HashSet::from([username])),
("cn", HashSet::from([cn.as_str()])),
// posixaccount
("uidNumber", HashSet::from([uid_number.to_string().as_str()])),
("gidNumber", HashSet::from(["1001"])),
("homedirectory", HashSet::from([home_directory.as_str()])),
("userpassword", HashSet::from([password_tmp.as_str()])),
// inetOrgPerson
("mail", HashSet::from([user.mail.as_str()])),
("sn", HashSet::from([user.name_surname.as_str()])),
// skPerson
("labeledURI", HashSet::from([labeled_uri.as_str()])),
("skMail", HashSet::from([sk_mail.as_str()])),
("skID", HashSet::from([user.id_student.as_str()])),
("skCreated", HashSet::from([sk_created.as_str()])),
// 1 = secure, automatic since its a new account
("skSecure", HashSet::from(["1"])),
// quotas
("quotaEmail", HashSet::from(["10737418240"])),
("quotaDisk", HashSet::from(["10737418240"])),
],
)?
.success()?;
// now to properly set teh password // now to properly set teh password
account_verification_reset_password_admin(&mut ldap, &user_details.user, &user_verify.password)?; let tmp = PasswordModify {
user_id: Some(&dn),
old_pass: None,
new_pass: Some(pass),
};
ldap.extended(tmp).unwrap();
// done with ldap
ldap.unbind()?; ldap.unbind()?;
// delete from tmp db Ok(())
account_verification_clear_pending(db, &user_verify.auth_code).await?;
// add new users to teh local database
account_verification_add_local(db, &user_details.user, uid_number).await?;
// frontend tells user that initial password ahs been sent to tehm
Ok(json!({"result": "success"}).into())
} }
fn get_sk_created() -> String { fn get_sk_created() -> String {
@ -235,87 +182,10 @@ async fn get_max_uid_number(db: &Pool<Sqlite>) -> i64 {
9999 9999
} }
async fn account_verification_find_pending(db: &Pool<Sqlite>, action: &str, auth_code: &str) -> Vec<AccountsPending> { async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsNew>, Error> {
sqlx::query_as::<_, AccountsPending>( sqlx::query_as::<_, AccountsNew>(
r#" r#"
SELECT * DELETE FROM accounts_new
FROM accounts_pending
WHERE auth_code == ? AND action == ?
"#,
)
.bind(auth_code)
.bind(action)
.fetch_all(db)
.await
.unwrap_or(vec![])
}
async fn account_verification_new_account(ldap: &mut LdapConn, user_details: &AccountsPending, uid_number: i64) -> Result<(), ldap3::LdapError> {
let AccountsPending {
user,
mail,
cn,
sn,
..
} = user_details;
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", user);
let home_directory = format!("/home/{}", user);
let password_tmp = random_string(50);
let labeled_uri = format!("ldap:///ou=groups,dc=skynet,dc=ie??sub?(&(objectclass=posixgroup)(memberuid={}))", user);
let sk_mail = format!("{}@skynet.ie", user);
let sk_created = get_sk_created();
// create user
ldap.add(
&dn,
vec![
("objectClass", HashSet::from(["top", "person", "posixaccount", "ldapPublicKey", "inetOrgPerson", "skPerson"])),
// top
("ou", HashSet::from(["users"])),
// person
("uid", HashSet::from([user.as_str()])),
("cn", HashSet::from([cn.as_str()])),
// posixaccount
("uidNumber", HashSet::from([uid_number.to_string().as_str()])),
("gidNumber", HashSet::from(["1001"])),
("homedirectory", HashSet::from([home_directory.as_str()])),
("userpassword", HashSet::from([password_tmp.as_str()])),
// inetOrgPerson
("mail", HashSet::from([mail.as_str()])),
("sn", HashSet::from([sn.as_str()])),
// skPerson
("labeledURI", HashSet::from([labeled_uri.as_str()])),
("skMail", HashSet::from([sk_mail.as_str()])),
// need to get this from wolves
//("skID", HashSet::from(["12345678"])),
("skCreated", HashSet::from([sk_created.as_str()])),
// 1 = secure, automatic since its a new account
("skSecure", HashSet::from(["1"])),
],
)?
.success()?;
Ok(())
}
fn account_verification_reset_password_admin(ldap: &mut LdapConn, user: &str, pass: &str) -> Result<ExopResult, ldap3::LdapError> {
let dn = format!("uid={},ou=users,dc=skynet,dc=ie", user);
// now to properly set teh password
let tmp = PasswordModify {
user_id: Some(&dn),
old_pass: None,
new_pass: Some(pass),
};
ldap.extended(tmp)
}
async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str) -> Result<Vec<AccountsPending>, Error> {
sqlx::query_as::<_, AccountsPending>(
r#"
DELETE FROM accounts_pending
WHERE auth_code == ? WHERE auth_code == ?
"#, "#,
) )
@ -323,17 +193,3 @@ async fn account_verification_clear_pending(db: &Pool<Sqlite>, auth_code: &str)
.fetch_all(db) .fetch_all(db)
.await .await
} }
async fn account_verification_add_local(db: &Pool<Sqlite>, user: &str, uid_number: i64) -> Result<Option<Accounts>, Error> {
sqlx::query_as::<_, Accounts>(
"
INSERT OR REPLACE INTO accounts (user, uid_number, enabled)
VALUES (?1, ?2, ?3)
",
)
.bind(user)
.bind(uid_number)
.bind(false)
.fetch_optional(db)
.await
}

View file

@ -1,9 +1,10 @@
use crate::State; use crate::State;
use ldap3::exop::PasswordModify; use ldap3::{exop::PasswordModify, LdapConn, Mod, Scope, SearchEntry};
use ldap3::{LdapConn, Mod, Scope, SearchEntry};
use std::collections::HashSet; use std::collections::HashSet;
use tide::prelude::{json, Deserialize}; use tide::{
use tide::Request; prelude::{json, Deserialize},
Request,
};
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct LdapUpdate { pub struct LdapUpdate {