2022-07-12 23:14:36 +02:00
|
|
|
import { getAccountById, getAccountByUsername, updateAccount, createAccount } from 'queries';
|
2020-08-09 08:48:43 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2020-08-12 07:24:41 +02:00
|
|
|
import { hashPassword } from 'lib/crypto';
|
2020-08-09 11:03:37 +02:00
|
|
|
import { ok, unauthorized, methodNotAllowed, badRequest } from 'lib/response';
|
2020-08-09 08:48:43 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
const { user_id: current_user_id, is_admin: current_user_is_admin } = req.auth;
|
2020-08-09 08:48:43 +02:00
|
|
|
|
|
|
|
if (req.method === 'POST') {
|
2020-08-09 11:03:37 +02:00
|
|
|
const { user_id, username, password, is_admin } = req.body;
|
2020-08-09 08:48:43 +02:00
|
|
|
|
|
|
|
if (user_id) {
|
2020-08-12 07:24:41 +02:00
|
|
|
const account = await getAccountById(user_id);
|
2020-08-09 08:48:43 +02:00
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
if (account.user_id === current_user_id || current_user_is_admin) {
|
2020-08-12 07:24:41 +02:00
|
|
|
const data = {};
|
|
|
|
|
|
|
|
if (password) {
|
2021-05-24 02:29:27 +02:00
|
|
|
data.password = hashPassword(password);
|
2020-08-12 07:24:41 +02:00
|
|
|
}
|
2020-08-09 08:48:43 +02:00
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
// Only admin can change these fields
|
|
|
|
if (current_user_is_admin) {
|
2022-04-04 07:25:32 +02:00
|
|
|
data.username = username;
|
2020-08-09 11:03:37 +02:00
|
|
|
data.is_admin = is_admin;
|
2020-08-09 08:48:43 +02:00
|
|
|
}
|
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
if (data.username && account.username !== data.username) {
|
2020-08-12 07:24:41 +02:00
|
|
|
const accountByUsername = await getAccountByUsername(username);
|
2020-08-09 11:03:37 +02:00
|
|
|
|
|
|
|
if (accountByUsername) {
|
|
|
|
return badRequest(res, 'Account already exists');
|
|
|
|
}
|
|
|
|
}
|
2022-04-04 09:33:20 +02:00
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
const updated = await updateAccount(user_id, data);
|
2020-08-09 08:48:43 +02:00
|
|
|
|
|
|
|
return ok(res, updated);
|
|
|
|
}
|
|
|
|
|
|
|
|
return unauthorized(res);
|
|
|
|
} else {
|
2020-08-12 07:24:41 +02:00
|
|
|
const accountByUsername = await getAccountByUsername(username);
|
2020-08-09 11:03:37 +02:00
|
|
|
|
|
|
|
if (accountByUsername) {
|
|
|
|
return badRequest(res, 'Account already exists');
|
|
|
|
}
|
|
|
|
|
2021-05-24 02:29:27 +02:00
|
|
|
const created = await createAccount({ username, password: hashPassword(password) });
|
2020-08-09 08:48:43 +02:00
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
return ok(res, created);
|
2020-08-09 08:48:43 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|