Skip to content

Commit

Permalink
pref(email): Use redis for email verification
Browse files Browse the repository at this point in the history
  • Loading branch information
abdulrahman1s committed Jun 28, 2022
1 parent 49b9272 commit 03e105e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 29 deletions.
6 changes: 0 additions & 6 deletions assets/migrations/00001_init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,6 @@ CREATE TABLE IF NOT EXISTS bots (
FOREIGN KEY (owner_id) REFERENCES users(id)
);

CREATE TABLE IF NOT EXISTS pending_accounts (
user_id BIGINT PRIMARY KEY,
code TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS account_invites (
code TEXT NOT NULL,
used BOOLEAN DEFAULT FALSE,
Expand Down
34 changes: 11 additions & 23 deletions src/utils/email.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
use crate::config::*;
use crate::database::redis::{connection, AsyncCommands};
use crate::database::DB as db;
use crate::structures::{Base, User};
use nanoid::nanoid;
use rbatis::crud::CRUD;
use regex::Regex;
use serde_json::json;

const THREE_HOURS_IN_SECONDS: usize = 10800;

lazy_static! {
static ref SPLIT_REGEX: Regex = Regex::new("([^@]+)(@.+)").unwrap();
static ref SYMBOL_REGEX: Regex = Regex::new("\\+.+|\\.").unwrap();
}

#[crud_table(table_name:pending_accounts)]
struct PendingVerification {
user_id: u64,
code: String,
}

#[crud_table(table_name:account_invites)]
pub struct Invite {
pub code: String,
Expand Down Expand Up @@ -74,30 +71,21 @@ pub async fn send(user: &User) -> bool {
.unwrap();

if res.status().is_success() {
let p = PendingVerification {
user_id: user.id,
code,
};
db.save(&p, &[]).await.is_ok()
let mut con = connection().await;
con.set_ex::<String, String, u32>(user.id.to_string(), code, THREE_HOURS_IN_SECONDS)
.await
.is_ok()
} else {
false
}
}

pub async fn verify(user_id: u64, code: &str) -> bool {
let p: Option<PendingVerification> = db
.fetch(
"SELECT * FROM pending_accounts WHERE user_id = $1 AND code = $2",
vec![user_id.into(), code.into()],
)
.await
.ok();
let mut con = connection().await;

match p {
Some(_) => {
db.remove_by_column::<PendingVerification, u64>("user_id", user_id)
.await
.ok();
match con.get::<String, String>(user_id.to_string()).await {
Ok(token) if code == token => {
con.del::<String, u32>(user_id.to_string()).await.ok();
true
}
_ => false,
Expand Down

0 comments on commit 03e105e

Please sign in to comment.