2.6 KiB · text History 7a00c02
//! Long-lived tokens for the Android app (and scripts), sent as
//! `Authorization: Bearer <token>`. Minted from the Devices page (shown
//! once, as a QR the app scans) or by signing in from the app with a
//! username and password. Only a SHA-256 of each token is stored.
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(ApiTokens::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(ApiTokens::Id).uuid().not_null().primary_key())
                    .col(ColumnDef::new(ApiTokens::UserId).uuid().not_null())
                    // hex SHA-256 of the token
                    .col(ColumnDef::new(ApiTokens::TokenHash).string_len(64).unique_key().not_null())
                    // the first few characters, to tell tokens apart in a list
                    .col(ColumnDef::new(ApiTokens::Prefix).string_len(16).not_null())
                    .col(ColumnDef::new(ApiTokens::Label).string_len(100).null())
                    .col(ColumnDef::new(ApiTokens::LastUsedAt).timestamp_with_time_zone().null())
                    .col(ColumnDef::new(ApiTokens::ExpiresAt).timestamp_with_time_zone().null())
                    .col(
                        ColumnDef::new(ApiTokens::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_api_tokens_user_id")
                            .from(ApiTokens::Table, ApiTokens::UserId)
                            .to(Users::Table, Users::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;
        manager
            .create_index(
                Index::create().name("idx_api_tokens_user_id").table(ApiTokens::Table).col(ApiTokens::UserId).to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(ApiTokens::Table).to_owned()).await
    }
}

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

#[derive(DeriveIden)]
enum ApiTokens {
    Table,
    Id,
    UserId,
    TokenHash,
    Prefix,
    Label,
    LastUsedAt,
    ExpiresAt,
    CreatedAt,
}