umami/pages/api/accounts/index.js

41 lines
979 B
JavaScript
Raw Normal View History

import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'next-basics';
2020-08-12 07:24:41 +02:00
import { useAuth } from 'lib/middleware';
import { uuid } from 'lib/crypto';
import { createAccount, getAccountByUsername, getAccounts } from 'queries';
2020-08-12 07:24:41 +02:00
export default async (req, res) => {
await useAuth(req, res);
2020-09-16 22:13:50 +02:00
const { is_admin } = req.auth;
2020-08-12 07:24:41 +02:00
2020-09-16 22:13:50 +02:00
if (!is_admin) {
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
}
if (req.method === 'POST') {
const { username, password, account_uuid } = req.body;
const accountByUsername = await getAccountByUsername(username);
if (accountByUsername) {
return badRequest(res, 'Account already exists');
}
const created = await createAccount({
username,
password: hashPassword(password),
account_uuid: account_uuid || uuid(),
});
return ok(res, created);
}
2020-08-12 07:24:41 +02:00
return methodNotAllowed(res);
};