2022-07-12 23:14:36 +02:00
|
|
|
import { getAccountById, updateAccount } from 'queries';
|
2020-08-09 11:03:37 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2022-08-29 05:20:54 +02:00
|
|
|
import {
|
|
|
|
badRequest,
|
|
|
|
methodNotAllowed,
|
|
|
|
ok,
|
|
|
|
unauthorized,
|
|
|
|
checkPassword,
|
|
|
|
hashPassword,
|
|
|
|
} from 'next-basics';
|
2020-08-09 11:03:37 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
2022-10-10 22:42:18 +02:00
|
|
|
const { userId: currentUserId, isAdmin: currentUserIsAdmin } = req.auth;
|
2022-10-04 02:17:53 +02:00
|
|
|
const { current_password, new_password } = req.body;
|
|
|
|
const { id } = req.query;
|
|
|
|
const userId = +id;
|
2020-08-09 11:03:37 +02:00
|
|
|
|
2022-10-04 02:17:53 +02:00
|
|
|
if (!currentUserIsAdmin && userId !== currentUserId) {
|
2020-09-11 22:49:43 +02:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
if (req.method === 'POST') {
|
2022-10-04 02:17:53 +02:00
|
|
|
const account = await getAccountById(userId);
|
2020-08-09 11:03:37 +02:00
|
|
|
|
2022-10-04 02:17:53 +02:00
|
|
|
if (!checkPassword(current_password, account.password)) {
|
2020-08-09 11:03:37 +02:00
|
|
|
return badRequest(res, 'Current password is incorrect');
|
|
|
|
}
|
|
|
|
|
2021-05-24 02:29:27 +02:00
|
|
|
const password = hashPassword(new_password);
|
2020-08-09 11:03:37 +02:00
|
|
|
|
2022-10-04 02:17:53 +02:00
|
|
|
const updated = await updateAccount(userId, { password });
|
2020-08-09 11:03:37 +02:00
|
|
|
|
|
|
|
return ok(res, updated);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|