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

69 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-09-30 00:15:11 +02:00
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getAccountById, deleteAccount, getAccountByUsername, 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-09-30 00:15:11 +02:00
const { is_admin: currentUserIsAdmin, user_id: currentUserId } = req.auth;
2020-08-09 11:03:37 +02:00
const { id } = req.query;
2022-09-30 00:15:11 +02:00
const userId = +id;
2020-08-09 11:03:37 +02:00
2020-09-11 22:49:43 +02:00
if (req.method === 'GET') {
2022-09-30 00:15:11 +02:00
if (userId !== currentUserId && !currentUserIsAdmin) {
return unauthorized(res);
}
const account = await getAccountById(userId);
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') {
const { username, password, is_admin } = req.body;
if (userId !== currentUserId && !currentUserIsAdmin) {
return unauthorized(res);
}
const account = await getAccountById(userId);
const data = {};
if (password) {
data.password = hashPassword(password);
}
// Only admin can change these fields
if (currentUserIsAdmin) {
data.username = username;
data.isAdmin = is_admin;
2022-09-30 00:15:11 +02:00
}
// Check when username changes
if (data.username && account.username !== data.username) {
const accountByUsername = await getAccountByUsername(username);
if (accountByUsername) {
return badRequest(res, 'Account already exists');
}
}
const updated = await updateAccount(userId, data);
return ok(res, updated);
}
2020-08-09 11:03:37 +02:00
if (req.method === 'DELETE') {
2022-09-30 00:15:11 +02:00
if (!currentUserIsAdmin) {
return unauthorized(res);
}
await deleteAccount(userId);
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);
};