63 lines
1.6 KiB
Rust
63 lines
1.6 KiB
Rust
use chrono::TimeDelta;
|
|
use sqlx::{PgPool, query_as};
|
|
|
|
#[derive(Debug)]
|
|
pub struct Registration {
|
|
pub token: String,
|
|
pub userid: i32,
|
|
}
|
|
|
|
use crate::support::{Token, generate_token_and_expiration};
|
|
|
|
use super::Result;
|
|
|
|
impl Registration {
|
|
pub async fn insert_new_for_user(pool: &PgPool, user_id: i32) -> Result<Registration> {
|
|
let (token, expires) = generate_token_and_expiration(64, TimeDelta::days(5));
|
|
|
|
let inserted = query_as!(
|
|
Registration,
|
|
"INSERT INTO registration (token, userId, expires) VALUES ($1, $2, $3) RETURNING token, userId;",
|
|
token,
|
|
user_id,
|
|
expires
|
|
)
|
|
.fetch_one(pool)
|
|
.await?;
|
|
|
|
Ok(inserted)
|
|
}
|
|
|
|
pub async fn does_token_exist(pool: &PgPool, token: &str) -> Result<Option<Registration>> {
|
|
query_as!(
|
|
Registration,
|
|
"SELECT token, userId FROM registration WHERE token = $1 AND expires > NOW();",
|
|
token
|
|
)
|
|
.fetch_optional(pool)
|
|
.await
|
|
}
|
|
|
|
pub async fn delete(pool: &PgPool, token: &str) -> Result<()> {
|
|
sqlx::query!("DELETE FROM registration WHERE token = $1;", token)
|
|
.execute(pool)
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn delete_all_for_user(pool: &PgPool, user_id: i32) -> Result<()> {
|
|
sqlx::query!("DELETE FROM registration WHERE userId = $1;", user_id)
|
|
.execute(pool)
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl Token for Registration {
|
|
async fn delete(&self, pool: &PgPool) -> Result<()> {
|
|
Registration::delete(pool, &self.token).await
|
|
}
|
|
}
|