Files
tatort/src/routes/api/users/+server.ts

39 lines
997 B
TypeScript

import { json } from '@sveltejs/kit';
import { addUser, getUsers } from '$lib/server/userService';
import bcrypt from 'bcrypt';
const saltRounds = 12;
export function GET({ locals }) {
if (!locals.user) {
return json({ error: 'Unauthorized' }, { status: 401 });
}
const userList = getUsers();
return new Response(JSON.stringify(userList));
}
export async function POST({ request, locals }) {
if (!locals.user) {
return json({ error: 'Unauthorized' }, { status: 401 });
}
const data = await request.json();
const userName = data.userName;
const userPassword = data.userPassword;
if (!userName || !userPassword) {
return json({ error: 'Missing input' }, { status: 400 });
}
const hashedPassword = bcrypt.hashSync(userPassword, saltRounds);
const rowInfo = addUser(userName, hashedPassword);
if (rowInfo?.changes == 1) {
return json({ userId: rowInfo.lastInsertRowid, userName: userName }, { status: 201 });
} else {
return new Response(null, { status: 400 });
}
}