Account editing and change password.

This commit is contained in:
Mike Cao 2020-08-09 02:03:37 -07:00
parent b5cf9f8719
commit b392a51676
23 changed files with 230 additions and 102 deletions

33
pages/api/account/[id].js Normal file
View file

@ -0,0 +1,33 @@
import { getAccount, deleteAccount } from 'lib/db';
import { useAuth } from 'lib/middleware';
import { methodNotAllowed, ok, unauthorized } from 'lib/response';
export default async (req, res) => {
await useAuth(req, res);
const { is_admin } = req.auth;
const { id } = req.query;
const user_id = +id;
if (req.method === 'GET') {
if (is_admin) {
const account = await getAccount({ user_id });
return ok(res, account);
}
return unauthorized(res);
}
if (req.method === 'DELETE') {
if (is_admin) {
await deleteAccount(user_id);
return ok(res);
}
return unauthorized(res);
}
return methodNotAllowed(res);
};

View file

@ -0,0 +1,28 @@
import { getAccount, updateAccount } from 'lib/db';
import { useAuth } from 'lib/middleware';
import { badRequest, methodNotAllowed, ok } from 'lib/response';
import { checkPassword, hashPassword } from 'lib/crypto';
export default async (req, res) => {
await useAuth(req, res);
const { user_id } = req.auth;
const { current_password, new_password } = req.body;
if (req.method === 'POST') {
const account = await getAccount({ user_id });
const valid = await checkPassword(current_password, account.password);
if (!valid) {
return badRequest(res, 'Current password is incorrect');
}
const password = await hashPassword(new_password);
const updated = await updateAccount(user_id, { password });
return ok(res, updated);
}
return methodNotAllowed(res);
};