umami/pages/api/accounts/[id]/index.js

71 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-09-30 00:15:11 +02:00
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
2022-10-12 22:11:44 +02:00
import { getAccount, deleteAccount, updateAccount } from 'queries';
2020-08-09 11:03:37 +02:00
import { useAuth } from 'lib/middleware';
export default async (req, res) => {
await useAuth(req, res);
2022-10-12 22:11:44 +02:00
const { isAdmin, userId } = req.auth;
2020-08-09 11:03:37 +02:00
const { id } = req.query;
2020-09-11 22:49:43 +02:00
if (req.method === 'GET') {
2022-10-12 22:11:44 +02:00
if (id !== userId && !isAdmin) {
2022-09-30 00:15:11 +02:00
return unauthorized(res);
}
2022-10-12 22:11:44 +02:00
const account = await getAccount({ id: +id });
2020-08-09 11:03:37 +02:00
2020-09-11 22:49:43 +02:00
return ok(res, account);
2020-08-09 11:03:37 +02:00
}
2022-09-30 00:15:11 +02:00
if (req.method === 'POST') {
2022-10-12 22:11:44 +02:00
const { username, password } = req.body;
2022-09-30 00:15:11 +02:00
2022-10-12 22:11:44 +02:00
if (id !== userId && !isAdmin) {
2022-09-30 00:15:11 +02:00
return unauthorized(res);
}
2022-10-12 22:11:44 +02:00
const account = await getAccount({ id: +id });
2022-09-30 00:15:11 +02:00
const data = {};
if (password) {
data.password = hashPassword(password);
}
// Only admin can change these fields
2022-10-12 22:11:44 +02:00
if (isAdmin) {
2022-09-30 00:15:11 +02:00
data.username = username;
}
// Check when username changes
if (data.username && account.username !== data.username) {
2022-10-12 22:11:44 +02:00
const accountByUsername = await getAccount({ username });
2022-09-30 00:15:11 +02:00
if (accountByUsername) {
2022-11-01 02:50:05 +01:00
return badRequest(res, 'Account already exists.');
2022-09-30 00:15:11 +02:00
}
}
2022-10-12 22:11:44 +02:00
const updated = await updateAccount(data, { id: +id });
2022-09-30 00:15:11 +02:00
return ok(res, updated);
}
2020-08-09 11:03:37 +02:00
if (req.method === 'DELETE') {
2022-11-01 02:50:05 +01:00
if (id === userId) {
return badRequest(res, 'You cannot delete your own account.');
}
2022-10-12 22:11:44 +02:00
if (!isAdmin) {
2022-09-30 00:15:11 +02:00
return unauthorized(res);
}
2022-11-01 02:50:05 +01:00
await deleteAccount(+id);
2020-08-09 11:03:37 +02:00
2020-09-11 22:49:43 +02:00
return ok(res);
2020-08-09 11:03:37 +02:00
}
return methodNotAllowed(res);
};