First pass

This commit is contained in:
2025-12-25 22:10:06 -07:00
parent a2af6195f9
commit 455c3dbd9a
58 changed files with 10299 additions and 3 deletions

View File

@@ -0,0 +1,80 @@
import type { APIRoute } from 'astro';
import { db } from '../../../db';
import { users, organizations, members, siteSettings } from '../../../db/schema';
import { hashPassword, createSession } from '../../../lib/auth';
import { eq, count, sql } from 'drizzle-orm';
import { nanoid } from 'nanoid';
export const POST: APIRoute = async ({ request, cookies, redirect }) => {
// Check if this is the first user
const userCountResult = await db.select({ count: count() }).from(users).get();
const isFirstUser = userCountResult ? userCountResult.count === 0 : true;
// If not first user, check if registration is enabled
if (!isFirstUser) {
const registrationSetting = await db.select()
.from(siteSettings)
.where(eq(siteSettings.key, 'registration_enabled'))
.get();
const registrationEnabled = registrationSetting?.value === 'true';
if (!registrationEnabled) {
return new Response('Registration is currently disabled', { status: 403 });
}
}
const formData = await request.formData();
const name = formData.get('name')?.toString();
const email = formData.get('email')?.toString();
const password = formData.get('password')?.toString();
if (!name || !email || !password) {
return new Response('Missing fields', { status: 400 });
}
// Check if user exists
const existingUser = await db.select().from(users).where(eq(users.email, email)).get();
if (existingUser) {
return new Response('User already exists', { status: 400 });
}
const passwordHash = await hashPassword(password);
const userId = nanoid();
// Create user
await db.insert(users).values({
id: userId,
name,
email,
passwordHash,
isSiteAdmin: isFirstUser,
});
// Create default organization
const orgId = nanoid();
await db.insert(organizations).values({
id: orgId,
name: `${name}'s Organization`,
});
// Add user to organization
await db.insert(members).values({
userId,
organizationId: orgId,
role: 'owner',
});
// Create session
const { sessionId, expiresAt } = await createSession(userId);
cookies.set('session_id', sessionId, {
path: '/',
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: 'lax',
expires: expiresAt,
});
return redirect('/dashboard');
};