All files / src/db auth-schema.ts

56% Statements 14/25
100% Branches 0/0
0% Functions 0/11
70% Lines 14/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 1472x 2x           2x         2x                                   2x                                                       2x                   2x                             2x                       2x             2x           2x       2x                     2x             2x                                
import { pgSchema, varchar, uuid, timestamp, boolean, jsonb, primaryKey, unique } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
 
/**
 * Dedicated PostgreSQL schema for all Rebase internal tables.
 * Keeps the user's `public` schema clean.
 */
export const rebaseSchema = pgSchema("rebase");
 
/**
 * Users table - stores both email/password and OAuth users
 */
export const users = rebaseSchema.table("users", {
    id: uuid("id").defaultRandom().primaryKey(),
    email: varchar("email", { length: 255 }).notNull().unique(),
    passwordHash: varchar("password_hash", { length: 255 }), // NULL for OAuth-only users
    displayName: varchar("display_name", { length: 255 }),
    photoUrl: varchar("photo_url", { length: 500 }),
    provider: varchar("provider", { length: 50 }).notNull().default("email"), // 'email' | 'google'
    googleId: varchar("google_id", { length: 255 }).unique(),
    emailVerified: boolean("email_verified").default(false).notNull(),
    emailVerificationToken: varchar("email_verification_token", { length: 255 }),
    emailVerificationSentAt: timestamp("email_verification_sent_at"),
    createdAt: timestamp("created_at").defaultNow().notNull(),
    updatedAt: timestamp("updated_at").defaultNow().notNull()
});
 
/**
 * Roles table - defines permission sets
 */
export const roles = rebaseSchema.table("roles", {
    id: varchar("id", { length: 50 }).primaryKey(), // 'admin', 'editor', 'viewer'
    name: varchar("name", { length: 100 }).notNull(),
    isAdmin: boolean("is_admin").default(false).notNull(),
    defaultPermissions: jsonb("default_permissions").$type<{
        read?: boolean;
        create?: boolean;
        edit?: boolean;
        delete?: boolean;
    }>(),
    collectionPermissions: jsonb("collection_permissions").$type<
        Record<string, {
            read?: boolean;
            create?: boolean;
            edit?: boolean;
            delete?: boolean;
        }>
    >(),
    config: jsonb("config").$type<{
        createCollections?: boolean;
        editCollections?: "own" | "all" | boolean;
        deleteCollections?: "own" | "all" | boolean;
    }>()
});
 
/**
 * User-Role junction table
 */
export const userRoles = rebaseSchema.table("user_roles", {
    userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
    roleId: varchar("role_id", { length: 50 }).notNull().references(() => roles.id, { onDelete: "cascade" })
}, (table) => ({
    pk: primaryKey({ columns: [table.userId, table.roleId] })
}));
 
/**
 * Refresh tokens for long-lived sessions
 */
export const refreshTokens = rebaseSchema.table("refresh_tokens", {
    id: uuid("id").defaultRandom().primaryKey(),
    userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
    tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
    expiresAt: timestamp("expires_at").notNull(),
    userAgent: varchar("user_agent", { length: 500 }),
    ipAddress: varchar("ip_address", { length: 45 }),
    createdAt: timestamp("created_at").defaultNow().notNull()
}, (table) => ({
    uniqueDeviceSession: unique("unique_device_session").on(table.userId, table.userAgent, table.ipAddress)
}));
 
/**
 * Password reset tokens for forgot password flow
 */
export const passwordResetTokens = rebaseSchema.table("password_reset_tokens", {
    id: uuid("id").defaultRandom().primaryKey(),
    userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
    tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
    expiresAt: timestamp("expires_at").notNull(),
    usedAt: timestamp("used_at"),
    createdAt: timestamp("created_at").defaultNow().notNull()
});
 
/**
 * App config - key/value store for custom settings
 */
export const appConfig = rebaseSchema.table("app_config", {
    key: varchar("key", { length: 100 }).primaryKey(),
    value: jsonb("value").notNull(),
    updatedAt: timestamp("updated_at").defaultNow().notNull()
});
 
// Relations
export const usersRelations = relations(users, ({ many }) => ({
    userRoles: many(userRoles),
    refreshTokens: many(refreshTokens),
    passwordResetTokens: many(passwordResetTokens)
}));
 
export const rolesRelations = relations(roles, ({ many }) => ({
    userRoles: many(userRoles)
}));
 
export const userRolesRelations = relations(userRoles, ({ one }) => ({
    user: one(users, {
        fields: [userRoles.userId],
        references: [users.id]
    }),
    role: one(roles, {
        fields: [userRoles.roleId],
        references: [roles.id]
    })
}));
 
export const refreshTokensRelations = relations(refreshTokens, ({ one }) => ({
    user: one(users, {
        fields: [refreshTokens.userId],
        references: [users.id]
    })
}));
 
export const passwordResetTokensRelations = relations(passwordResetTokens, ({ one }) => ({
    user: one(users, {
        fields: [passwordResetTokens.userId],
        references: [users.id]
    })
}));
 
// Type exports
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Role = typeof roles.$inferSelect;
export type NewRole = typeof roles.$inferInsert;
export type UserRole = typeof userRoles.$inferSelect;
export type RefreshToken = typeof refreshTokens.$inferSelect;
export type PasswordResetToken = typeof passwordResetTokens.$inferSelect;
export type AppConfig = typeof appConfig.$inferSelect;