umami/pages/api/account/password.js

33 lines
893 B
JavaScript
Raw Normal View History

2020-08-12 07:24:41 +02:00
import { getAccountById, updateAccount } from 'lib/queries';
2020-08-09 11:03:37 +02:00
import { useAuth } from 'lib/middleware';
2020-09-11 22:49:43 +02:00
import { badRequest, methodNotAllowed, ok, unauthorized } from 'lib/response';
2020-08-09 11:03:37 +02:00
import { checkPassword, hashPassword } from 'lib/crypto';
export default async (req, res) => {
await useAuth(req, res);
2020-09-11 22:49:43 +02:00
const { user_id, is_admin } = req.auth;
2020-08-09 11:03:37 +02:00
const { current_password, new_password } = req.body;
2020-09-11 22:49:43 +02:00
if (is_admin) {
return unauthorized(res);
}
2020-08-09 11:03:37 +02:00
if (req.method === 'POST') {
2020-08-12 07:24:41 +02:00
const account = await getAccountById(user_id);
2020-08-09 11:03:37 +02:00
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);
};