Simplify auth setup, centralize environment variable management and fix

create readme
This commit is contained in:
Aman Varshney
2025-03-19 13:33:51 +05:30
parent d0540e41cd
commit 03d9559e55
11 changed files with 170 additions and 222 deletions

View File

@@ -1,116 +1,9 @@
import path from "node:path";
import { log } from "@clack/prompts";
import fs from "fs-extra";
import pc from "picocolors";
import type { ProjectConfig } from "../types";
import { addPackageDependency } from "../utils/add-package-deps";
export async function setupAuth(
projectDir: string,
enableAuth: boolean,
options: ProjectConfig,
): Promise<void> {
const serverDir = path.join(projectDir, "packages/server");
const clientDir = path.join(projectDir, "packages/client");
try {
if (!enableAuth) {
return;
}
addPackageDependency({
dependencies: ["better-auth"],
devDependencies: false,
projectDir: serverDir,
});
const envPath = path.join(serverDir, ".env");
// Create or update the .env file directly with required variables
let envContent = "";
if (await fs.pathExists(envPath)) {
envContent = await fs.readFile(envPath, "utf8");
}
// Only add variables that don't already exist
if (!envContent.includes("BETTER_AUTH_SECRET")) {
envContent += `\nBETTER_AUTH_SECRET=${generateAuthSecret()}`;
}
if (!envContent.includes("BETTER_AUTH_URL")) {
envContent += "\nBETTER_AUTH_URL=http://localhost:3000";
}
if (!envContent.includes("CORS_ORIGIN")) {
envContent += "\nCORS_ORIGIN=http://localhost:3001";
}
if (
options.database === "sqlite" &&
!envContent.includes("TURSO_CONNECTION_URL")
) {
envContent += "\nTURSO_CONNECTION_URL=http://127.0.0.1:8080";
}
if (options.orm === "prisma" && !envContent.includes("DATABASE_URL")) {
if (options.database === "sqlite") {
envContent += '\nDATABASE_URL="file:./dev.db"';
} else if (options.database === "postgres") {
envContent +=
'\nDATABASE_URL="postgresql://postgres:postgres@localhost:5432/mydb?schema=public"';
}
}
// Write the updated content
await fs.writeFile(envPath, envContent.trim());
// Create client .env file if it doesn't exist
const clientEnvPath = path.join(clientDir, ".env");
if (!(await fs.pathExists(clientEnvPath))) {
const clientEnvContent = "VITE_SERVER_URL=http://localhost:3000\n";
await fs.writeFile(clientEnvPath, clientEnvContent);
}
if (options.orm === "prisma") {
const packageJsonPath = path.join(projectDir, "package.json");
if (await fs.pathExists(packageJsonPath)) {
const packageJson = await fs.readJson(packageJsonPath);
packageJson.scripts["prisma:generate"] =
"cd packages/server && npx prisma generate";
packageJson.scripts["prisma:push"] =
"cd packages/server && npx prisma db push";
packageJson.scripts["prisma:studio"] =
"cd packages/server && npx prisma studio";
packageJson.scripts["db:setup"] =
"npm run auth:generate && npm run prisma:generate && npm run prisma:push";
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
}
} else if (options.orm === "drizzle") {
const packageJsonPath = path.join(projectDir, "package.json");
if (await fs.pathExists(packageJsonPath)) {
const packageJson = await fs.readJson(packageJsonPath);
packageJson.scripts["db:push"] =
"cd packages/server && npx @better-auth/cli migrate";
packageJson.scripts["db:setup"] =
"npm run auth:generate && npm run db:push";
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
}
}
} catch (error) {
log.error(pc.red("Failed to configure authentication"));
if (error instanceof Error) {
log.error(pc.red(error.message));
}
throw error;
}
}
function generateAuthSecret(length = 32): string {
export function generateAuthSecret(length = 32): string {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
@@ -120,3 +13,33 @@ function generateAuthSecret(length = 32): string {
}
return result;
}
export async function setupAuth(
projectDir: string,
enableAuth: boolean,
): Promise<void> {
const serverDir = path.join(projectDir, "packages/server");
const clientDir = path.join(projectDir, "packages/client");
try {
if (!enableAuth) {
return;
}
addPackageDependency({
dependencies: ["better-auth"],
devDependencies: false,
projectDir: serverDir,
});
addPackageDependency({
dependencies: ["better-auth"],
devDependencies: false,
projectDir: clientDir,
});
} catch (error) {
log.error(pc.red("Failed to configure authentication"));
if (error instanceof Error) {
log.error(pc.red(error.message));
}
throw error;
}
}