|
| 1 | +use crate::repositories::user_repository::UserRepository; |
| 2 | +use diesel::prelude::*; |
| 3 | +use payego_primitives::error::{ApiError, AuthError}; |
| 4 | +use payego_primitives::models::entities::verification_token::{ |
| 5 | + NewVerificationToken, VerificationToken, |
| 6 | +}; |
| 7 | +use payego_primitives::schema::verification_tokens; |
| 8 | +use uuid::Uuid; |
| 9 | + |
| 10 | +pub struct VerificationRepository; |
| 11 | + |
| 12 | +impl VerificationRepository { |
| 13 | + pub fn create( |
| 14 | + conn: &mut PgConnection, |
| 15 | + new_token: NewVerificationToken, |
| 16 | + ) -> Result<VerificationToken, ApiError> { |
| 17 | + diesel::insert_into(verification_tokens::table) |
| 18 | + .values(&new_token) |
| 19 | + .get_result(conn) |
| 20 | + .map_err(ApiError::Database) |
| 21 | + } |
| 22 | + |
| 23 | + pub fn find_by_token( |
| 24 | + conn: &mut PgConnection, |
| 25 | + token_hash: &str, |
| 26 | + ) -> Result<Option<VerificationToken>, ApiError> { |
| 27 | + verification_tokens::table |
| 28 | + .filter(verification_tokens::token_hash.eq(token_hash)) |
| 29 | + .first::<VerificationToken>(conn) |
| 30 | + .optional() |
| 31 | + .map_err(ApiError::Database) |
| 32 | + } |
| 33 | + |
| 34 | + pub fn delete_for_user(conn: &mut PgConnection, user_id: Uuid) -> Result<(), ApiError> { |
| 35 | + diesel::delete(verification_tokens::table.filter(verification_tokens::user_id.eq(user_id))) |
| 36 | + .execute(conn) |
| 37 | + .map(|_| ()) |
| 38 | + .map_err(ApiError::Database) |
| 39 | + } |
| 40 | + |
| 41 | + pub fn consume_token( |
| 42 | + conn: &mut PgConnection, |
| 43 | + token_hash: &str, |
| 44 | + ) -> Result<VerificationToken, ApiError> { |
| 45 | + let token = Self::find_by_token(conn, token_hash)?.ok_or_else(|| { |
| 46 | + ApiError::Auth(AuthError::VerificationError( |
| 47 | + "Invalid or expired verification token".into(), |
| 48 | + )) |
| 49 | + })?; |
| 50 | + |
| 51 | + if token.expires_at < chrono::Utc::now().naive_utc() { |
| 52 | + return Err(ApiError::Auth(AuthError::VerificationError( |
| 53 | + "Verification token has expired".into(), |
| 54 | + ))); |
| 55 | + } |
| 56 | + |
| 57 | + // Verify user and delete token |
| 58 | + UserRepository::mark_email_verified(conn, token.user_id)?; |
| 59 | + Self::delete_for_user(conn, token.user_id)?; |
| 60 | + |
| 61 | + Ok(token) |
| 62 | + } |
| 63 | +} |
0 commit comments