2022-10-04 02:17:53 +02:00
|
|
|
import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'next-basics';
|
2020-08-12 07:24:41 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2022-10-04 02:17:53 +02:00
|
|
|
import { uuid } from 'lib/crypto';
|
2022-10-26 01:50:12 +02:00
|
|
|
import { createAccount, getAccount, getAccounts } from 'queries';
|
2020-08-12 07:24:41 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
2022-10-10 22:42:18 +02:00
|
|
|
const { isAdmin } = req.auth;
|
2020-08-12 07:24:41 +02:00
|
|
|
|
2022-10-10 22:42:18 +02:00
|
|
|
if (!isAdmin) {
|
2020-09-16 22:13:50 +02:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
2020-08-12 07:24:41 +02:00
|
|
|
|
2020-09-16 22:13:50 +02:00
|
|
|
if (req.method === 'GET') {
|
|
|
|
const accounts = await getAccounts();
|
2020-08-12 07:24:41 +02:00
|
|
|
|
2020-09-16 22:13:50 +02:00
|
|
|
return ok(res, accounts);
|
2020-08-12 07:24:41 +02:00
|
|
|
}
|
|
|
|
|
2022-10-04 02:17:53 +02:00
|
|
|
if (req.method === 'POST') {
|
2022-10-05 05:16:09 +02:00
|
|
|
const { username, password, account_uuid } = req.body;
|
2022-10-04 02:17:53 +02:00
|
|
|
|
2022-10-26 01:50:12 +02:00
|
|
|
const account = await getAccount({ username });
|
2022-10-04 02:17:53 +02:00
|
|
|
|
2022-10-26 01:50:12 +02:00
|
|
|
if (account) {
|
2022-10-04 02:17:53 +02:00
|
|
|
return badRequest(res, 'Account already exists');
|
|
|
|
}
|
|
|
|
|
|
|
|
const created = await createAccount({
|
|
|
|
username,
|
|
|
|
password: hashPassword(password),
|
2022-10-10 22:42:18 +02:00
|
|
|
accountUuid: account_uuid || uuid(),
|
2022-10-04 02:17:53 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
return ok(res, created);
|
|
|
|
}
|
|
|
|
|
2020-08-12 07:24:41 +02:00
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|