umami/pages/api/account/password.js

39 lines
912 B
JavaScript
Raw Normal View History

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);
2020-09-15 17:50:05 +02:00
const { user_id: auth_user_id, is_admin } = req.auth;
const { user_id, current_password, new_password } = req.body;
2020-08-09 11:03:37 +02:00
if (!is_admin && user_id !== auth_user_id) {
2020-09-11 22:49:43 +02:00
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);
const valid = checkPassword(current_password, account.password);
2020-08-09 11:03:37 +02:00
if (!valid) {
return badRequest(res, 'Current password is incorrect');
}
const password = hashPassword(new_password);
2020-08-09 11:03:37 +02:00
const updated = await updateAccount(user_id, { password });
return ok(res, updated);
}
return methodNotAllowed(res);
};