Files
cog-socket/src/routes/api/register/+server.ts
2025-07-14 00:24:44 +02:00

25 lines
1.1 KiB
TypeScript

import { json } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import * as schema from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import argon2 from '@node-rs/argon2';
import { generateSessionToken, createSession } from '$lib/server/auth';
import { randomUUID } from 'crypto';
export async function POST({ request, cookies }) {
const { username, password } = await request.json();
if (!username || !password) {
return json({ error: 'Missing username or password' }, { status: 400 });
}
const [existing] = await db.select().from(schema.user).where(eq(schema.user.username, username));
if (existing) {
return json({ error: 'User already exists' }, { status: 409 });
}
const passwordHash = await argon2.hash(password);
const userId = randomUUID();
await db.insert(schema.user).values({ id: userId, username, passwordHash });
const token = generateSessionToken();
const session = await createSession(token, userId);
cookies.set('auth-session', token, { expires: session.expiresAt, path: '/' });
return json({ success: true });
}