|
| 1 | +import type { Knex } from "knex"; |
| 2 | + |
| 3 | +export async function up(knex: Knex): Promise<void> { |
| 4 | + // 1. Add auth_provider and oidc_sub columns to users table |
| 5 | + const hasAuthProvider = await knex.schema.hasColumn("users", "auth_provider"); |
| 6 | + if (!hasAuthProvider) { |
| 7 | + await knex.schema.alterTable("users", (table) => { |
| 8 | + // "local" for password-based accounts, "oidc" for OpenID Connect accounts |
| 9 | + table.string("auth_provider", 20).notNullable().defaultTo("local"); |
| 10 | + }); |
| 11 | + } |
| 12 | + |
| 13 | + const hasOidcSub = await knex.schema.hasColumn("users", "oidc_sub"); |
| 14 | + if (!hasOidcSub) { |
| 15 | + await knex.schema.alterTable("users", (table) => { |
| 16 | + // Subject identifier from the OIDC provider (unique per provider) |
| 17 | + table.string("oidc_sub", 255).nullable().unique(); |
| 18 | + }); |
| 19 | + } |
| 20 | + |
| 21 | + // 2. Make password_hash nullable for OIDC users who have no local password. |
| 22 | + // SQLite does not support ALTER COLUMN, so we store an empty string |
| 23 | + // for OIDC users there. For PostgreSQL/MySQL we properly drop NOT NULL. |
| 24 | + const dbClient = knex.client.config.client; |
| 25 | + if (dbClient === "pg" || dbClient === "postgresql") { |
| 26 | + await knex.schema.raw('ALTER TABLE users ALTER COLUMN password_hash DROP NOT NULL'); |
| 27 | + } else if (dbClient === "mysql" || dbClient === "mysql2") { |
| 28 | + await knex.schema.raw('ALTER TABLE users MODIFY password_hash VARCHAR(255) NULL'); |
| 29 | + } |
| 30 | + |
| 31 | + // 3. Create OIDC group-to-role mapping table |
| 32 | + if (!(await knex.schema.hasTable("oidc_group_role_mappings"))) { |
| 33 | + await knex.schema.createTable("oidc_group_role_mappings", (table) => { |
| 34 | + table.increments("id").primary(); |
| 35 | + table.string("oidc_group", 255).notNullable(); |
| 36 | + table |
| 37 | + .string("role_id", 100) |
| 38 | + .notNullable() |
| 39 | + .references("id") |
| 40 | + .inTable("roles") |
| 41 | + .onDelete("CASCADE"); |
| 42 | + table.timestamp("created_at").defaultTo(knex.fn.now()); |
| 43 | + table.timestamp("updated_at").defaultTo(knex.fn.now()); |
| 44 | + table.unique(["oidc_group"]); |
| 45 | + }); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +export async function down(knex: Knex): Promise<void> { |
| 50 | + await knex.schema.dropTableIfExists("oidc_group_role_mappings"); |
| 51 | + |
| 52 | + const hasOidcSub = await knex.schema.hasColumn("users", "oidc_sub"); |
| 53 | + if (hasOidcSub) { |
| 54 | + await knex.schema.alterTable("users", (table) => { |
| 55 | + table.dropColumn("oidc_sub"); |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + const hasAuthProvider = await knex.schema.hasColumn("users", "auth_provider"); |
| 60 | + if (hasAuthProvider) { |
| 61 | + await knex.schema.alterTable("users", (table) => { |
| 62 | + table.dropColumn("auth_provider"); |
| 63 | + }); |
| 64 | + } |
| 65 | +} |
0 commit comments