mirror of
https://github.com/RayLabsHQ/gitea-mirror.git
synced 2025-12-09 13:06:45 +03:00
Added Better Auth
This commit is contained in:
109
scripts/generate-better-auth-schema.ts
Normal file
109
scripts/generate-better-auth-schema.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import Database from "bun:sqlite";
|
||||
import { drizzle } from "drizzle-orm/bun-sqlite";
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
|
||||
// Create a minimal auth instance just for schema generation
|
||||
const tempDb = new Database(":memory:");
|
||||
const db = drizzle({ client: tempDb });
|
||||
|
||||
// Minimal auth config for schema generation
|
||||
const auth = betterAuth({
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "sqlite",
|
||||
usePlural: true,
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Generate the schema
|
||||
const schema = auth.$internal.schema;
|
||||
|
||||
console.log("Better Auth Tables Required:");
|
||||
console.log("============================");
|
||||
|
||||
// Convert Better Auth schema to Drizzle schema definitions
|
||||
const drizzleSchemaCode = `// Better Auth Tables - Generated Schema
|
||||
import { sqliteTable, text, integer, index } from "drizzle-orm/sqlite-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
// Sessions table
|
||||
export const sessions = sqliteTable("sessions", {
|
||||
id: text("id").primaryKey(),
|
||||
token: text("token").notNull().unique(),
|
||||
userId: text("user_id").notNull().references(() => users.id),
|
||||
expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
|
||||
ipAddress: text("ip_address"),
|
||||
userAgent: text("user_agent"),
|
||||
createdAt: integer("created_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql\`(unixepoch())\`),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql\`(unixepoch())\`),
|
||||
}, (table) => {
|
||||
return {
|
||||
userIdIdx: index("idx_sessions_user_id").on(table.userId),
|
||||
tokenIdx: index("idx_sessions_token").on(table.token),
|
||||
expiresAtIdx: index("idx_sessions_expires_at").on(table.expiresAt),
|
||||
};
|
||||
});
|
||||
|
||||
// Accounts table (for OAuth providers and credentials)
|
||||
export const accounts = sqliteTable("accounts", {
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id").notNull().references(() => users.id),
|
||||
providerId: text("provider_id").notNull(),
|
||||
providerUserId: text("provider_user_id").notNull(),
|
||||
accessToken: text("access_token"),
|
||||
refreshToken: text("refresh_token"),
|
||||
expiresAt: integer("expires_at", { mode: "timestamp" }),
|
||||
password: text("password"), // For credential provider
|
||||
createdAt: integer("created_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql\`(unixepoch())\`),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql\`(unixepoch())\`),
|
||||
}, (table) => {
|
||||
return {
|
||||
userIdIdx: index("idx_accounts_user_id").on(table.userId),
|
||||
providerIdx: index("idx_accounts_provider").on(table.providerId, table.providerUserId),
|
||||
};
|
||||
});
|
||||
|
||||
// Verification tokens table
|
||||
export const verificationTokens = sqliteTable("verification_tokens", {
|
||||
id: text("id").primaryKey(),
|
||||
token: text("token").notNull().unique(),
|
||||
identifier: text("identifier").notNull(),
|
||||
type: text("type").notNull(), // email, password-reset, etc
|
||||
expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
|
||||
createdAt: integer("created_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql\`(unixepoch())\`),
|
||||
}, (table) => {
|
||||
return {
|
||||
tokenIdx: index("idx_verification_tokens_token").on(table.token),
|
||||
identifierIdx: index("idx_verification_tokens_identifier").on(table.identifier),
|
||||
};
|
||||
});
|
||||
|
||||
// Future: SSO and OIDC Provider tables will be added when we enable those plugins
|
||||
`;
|
||||
|
||||
console.log(drizzleSchemaCode);
|
||||
|
||||
// Output information about the schema
|
||||
console.log("\n\nSummary:");
|
||||
console.log("=========");
|
||||
console.log("- Better Auth will modify the existing 'users' table");
|
||||
console.log("- New tables required: sessions, accounts, verification_tokens");
|
||||
console.log("\nNote: The 'users' table needs emailVerified field added");
|
||||
|
||||
tempDb.close();
|
||||
85
scripts/migrate-to-better-auth.ts
Normal file
85
scripts/migrate-to-better-auth.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { db, users, accounts } from "../src/lib/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
/**
|
||||
* Migrate existing users to Better Auth schema
|
||||
*
|
||||
* This script:
|
||||
* 1. Moves existing password hashes from users table to accounts table
|
||||
* 2. Updates user data to match Better Auth requirements
|
||||
* 3. Creates credential accounts for existing users
|
||||
*/
|
||||
|
||||
async function migrateUsers() {
|
||||
console.log("🔄 Starting user migration to Better Auth...");
|
||||
|
||||
try {
|
||||
// Get all existing users
|
||||
const existingUsers = await db.select().from(users);
|
||||
|
||||
if (existingUsers.length === 0) {
|
||||
console.log("✅ No users to migrate");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Found ${existingUsers.length} users to migrate`);
|
||||
|
||||
for (const user of existingUsers) {
|
||||
console.log(`\nMigrating user: ${user.username} (${user.email})`);
|
||||
|
||||
// Check if user already has a credential account
|
||||
const existingAccount = await db
|
||||
.select()
|
||||
.from(accounts)
|
||||
.where(
|
||||
eq(accounts.userId, user.id) &&
|
||||
eq(accounts.providerId, "credential")
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (existingAccount.length > 0) {
|
||||
console.log("✓ User already migrated");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create credential account with existing password hash
|
||||
await db.insert(accounts).values({
|
||||
id: uuidv4(),
|
||||
userId: user.id,
|
||||
providerId: "credential",
|
||||
providerUserId: user.email, // Use email as provider user ID
|
||||
password: user.password, // Move existing password hash
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
});
|
||||
|
||||
console.log("✓ Created credential account");
|
||||
|
||||
// Update user name field if it's null (Better Auth uses 'name' field)
|
||||
// Note: Better Auth expects a 'name' field, but we're using username
|
||||
// This is handled by our additional fields configuration
|
||||
}
|
||||
|
||||
console.log("\n✅ User migration completed successfully!");
|
||||
|
||||
// Summary
|
||||
const migratedAccounts = await db
|
||||
.select()
|
||||
.from(accounts)
|
||||
.where(eq(accounts.providerId, "credential"));
|
||||
|
||||
console.log(`\nMigration Summary:`);
|
||||
console.log(`- Total users: ${existingUsers.length}`);
|
||||
console.log(`- Migrated accounts: ${migratedAccounts.length}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error("❌ Migration failed:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Run migration
|
||||
migrateUsers();
|
||||
Reference in New Issue
Block a user