20241103083933_user-roles.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const { ROLES } = require("../consts");
  2. /**
  3. * @param { import("knex").Knex } knex
  4. * @returns { Promise<void> }
  5. */
  6. async function up(knex) {
  7. const hasRole = await knex.schema.hasColumn("users", "role");
  8. if (!hasRole) {
  9. await knex.transaction(async function(trx) {
  10. await trx.schema.alterTable("users", table => {
  11. table
  12. .enu("role", [ROLES.USER, ROLES.ADMIN])
  13. .notNullable()
  14. .defaultTo(ROLES.USER);
  15. });
  16. if (typeof process.env.ADMIN_EMAILS === "string") {
  17. const adminEmails = process.env.ADMIN_EMAILS.split(",").map((e) => e.trim());
  18. const adminRoleQuery = trx("users").update("role", ROLES.ADMIN);
  19. adminEmails.forEach((adminEmail, index) => {
  20. if (index === 0) {
  21. adminRoleQuery.where("email", adminEmail);
  22. } else {
  23. adminRoleQuery.orWhere("email", adminEmail);
  24. }
  25. });
  26. await adminRoleQuery;
  27. }
  28. });
  29. }
  30. };
  31. /**
  32. * @param { import("knex").Knex } knex
  33. * @returns { Promise<void> }
  34. */
  35. async function down(knex) {};
  36. module.exports = {
  37. up,
  38. down,
  39. }