4.0 KiB · text History 263b40b
use sea_orm_migration::prelude::*;

/// Email verification: `users.email_verified_at` plus single-use, expiring
/// verification tokens (only a SHA-256 of each token is stored).
///
/// Every account that exists when this runs is marked verified (as of its
/// creation), so turning verification on locks nobody out.
#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .alter_table(
                Table::alter()
                    .table(Users::Table)
                    .add_column(
                        ColumnDef::new(Users::EmailVerifiedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .get_connection()
            .execute_unprepared("UPDATE users SET email_verified_at = created_at WHERE email_verified_at IS NULL")
            .await?;

        manager
            .create_table(
                Table::create()
                    .table(EmailVerificationTokens::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(EmailVerificationTokens::Id).uuid().not_null().primary_key())
                    .col(ColumnDef::new(EmailVerificationTokens::UserId).uuid().not_null())
                    // Hex SHA-256 of the token sent in the link.
                    .col(
                        ColumnDef::new(EmailVerificationTokens::TokenHash)
                            .string_len(64)
                            .not_null()
                            .unique_key(),
                    )
                    // The address the link verifies: it only counts while it is
                    // still the account's address.
                    .col(ColumnDef::new(EmailVerificationTokens::Email).string().not_null())
                    .col(
                        ColumnDef::new(EmailVerificationTokens::ExpiresAt)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .col(ColumnDef::new(EmailVerificationTokens::UsedAt).timestamp_with_time_zone().null())
                    .col(
                        ColumnDef::new(EmailVerificationTokens::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_email_verification_tokens_user_id")
                            .from(EmailVerificationTokens::Table, EmailVerificationTokens::UserId)
                            .to(Users::Table, Users::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_email_verification_tokens_user_id")
                    .table(EmailVerificationTokens::Table)
                    .col(EmailVerificationTokens::UserId)
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(EmailVerificationTokens::Table).to_owned())
            .await?;
        manager
            .alter_table(
                Table::alter()
                    .table(Users::Table)
                    .drop_column(Users::EmailVerifiedAt)
                    .to_owned(),
            )
            .await
    }
}

#[derive(DeriveIden)]
enum Users {
    Table,
    Id,
    EmailVerifiedAt,
}

#[derive(DeriveIden)]
enum EmailVerificationTokens {
    Table,
    Id,
    UserId,
    TokenHash,
    Email,
    ExpiresAt,
    UsedAt,
    CreatedAt,
}