umami/pages/api/account.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-08-09 08:48:43 +02:00
import { getAccounts, getAccount, updateAccount, createAccount } from 'lib/db';
import { useAuth } from 'lib/middleware';
import { hashPassword, uuid } 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 === 'GET') {
2020-08-09 11:03:37 +02:00
if (current_user_is_admin) {
2020-08-09 08:48:43 +02:00
const accounts = await getAccounts();
return ok(res, accounts);
}
return unauthorized(res);
}
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-09 11:03:37 +02:00
const account = await getAccount({ 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-09 08:48:43 +02:00
const data = { password: password ? await hashPassword(password) : undefined };
2020-08-09 11:03:37 +02:00
// Only admin can change these fields
if (current_user_is_admin) {
// Cannot change username of admin
if (username !== 'admin') {
data.username = username;
}
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) {
const accountByUsername = await getAccount({ username });
if (accountByUsername) {
return badRequest(res, 'Account already exists');
}
}
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-09 11:03:37 +02:00
const accountByUsername = await getAccount({ username });
if (accountByUsername) {
return badRequest(res, 'Account already exists');
}
const created = await createAccount({ username, password: await 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);
};