misuzu/database/2025_02_08_000526_create_users_totp_table.php

33 lines
1.3 KiB
PHP

<?php
use Index\Base32;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class CreateUsersTotpTable_20250208_000526 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute(<<<SQL
CREATE TABLE msz_users_totp (
user_id INT UNSIGNED NOT NULL,
totp_secret BINARY(16) NOT NULL,
totp_created TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (user_id),
INDEX users_totp_created_index (totp_created),
CONSTRAINT users_totp_users_foreign
FOREIGN KEY (user_id)
REFERENCES msz_users (user_id)
ON UPDATE CASCADE
ON DELETE CASCADE
) COLLATE='utf8mb4_bin';
SQL);
$result = $conn->query('SELECT user_id, user_totp_key FROM msz_users WHERE user_totp_key IS NOT NULL');
$stmt = $conn->prepare('INSERT INTO msz_users_totp (user_id, totp_secret) VALUES (?, ?)');
while($result->next()) {
$stmt->addParameter(1, $result->getString(0));
$stmt->addParameter(2, Base32::decode($result->getString(1)));
$stmt->execute();
}
$conn->execute('ALTER TABLE msz_users DROP COLUMN user_totp_key');
}
}