umami/pages/api/account/index.js

28 lines
731 B
JavaScript
Raw Normal View History

2022-08-29 05:20:54 +02:00
import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'next-basics';
2022-09-30 00:15:11 +02:00
import { getAccountByUsername, createAccount } from 'queries';
2020-08-09 08:48:43 +02:00
import { useAuth } from 'lib/middleware';
export default async (req, res) => {
if (req.method === 'POST') {
2022-09-30 00:15:11 +02:00
await useAuth(req, res);
2020-08-09 08:48:43 +02:00
2022-09-30 00:15:11 +02:00
if (!req.auth.is_admin) {
2020-08-09 08:48:43 +02:00
return unauthorized(res);
2022-09-30 00:15:11 +02:00
}
2020-08-09 11:03:37 +02:00
2022-09-30 00:15:11 +02:00
const { username, password } = req.body;
2020-08-09 11:03:37 +02:00
2022-09-30 00:15:11 +02:00
const accountByUsername = await getAccountByUsername(username);
2020-08-09 08:48:43 +02:00
2022-09-30 00:15:11 +02:00
if (accountByUsername) {
return badRequest(res, 'Account already exists');
2020-08-09 08:48:43 +02:00
}
2022-09-30 00:15:11 +02:00
const created = await createAccount({ username, password: hashPassword(password) });
return ok(res, created);
2020-08-09 08:48:43 +02:00
}
return methodNotAllowed(res);
};