2022-12-07 03:36:41 +01:00
|
|
|
import { NextApiRequestQueryBody } from 'lib/types';
|
2022-12-02 05:53:37 +01:00
|
|
|
import { canUpdateUser } from 'lib/auth';
|
2020-08-09 11:03:37 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2022-11-19 03:49:58 +01:00
|
|
|
import { NextApiResponse } from 'next';
|
2022-08-29 05:20:54 +02:00
|
|
|
import {
|
|
|
|
badRequest,
|
2022-11-19 03:49:58 +01:00
|
|
|
checkPassword,
|
|
|
|
hashPassword,
|
2022-08-29 05:20:54 +02:00
|
|
|
methodNotAllowed,
|
|
|
|
ok,
|
|
|
|
unauthorized,
|
|
|
|
} from 'next-basics';
|
2022-11-19 03:49:58 +01:00
|
|
|
import { getUser, updateUser, User } from 'queries';
|
2022-11-15 22:21:14 +01:00
|
|
|
|
|
|
|
export interface UserPasswordRequestQuery {
|
|
|
|
id: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface UserPasswordRequestBody {
|
2022-12-27 02:36:48 +01:00
|
|
|
currentPassword: string;
|
|
|
|
newPassword: string;
|
2022-11-15 22:21:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<UserPasswordRequestQuery, UserPasswordRequestBody>,
|
|
|
|
res: NextApiResponse<User>,
|
|
|
|
) => {
|
2020-08-09 11:03:37 +02:00
|
|
|
await useAuth(req, res);
|
|
|
|
|
2022-12-27 02:36:48 +01:00
|
|
|
const { currentPassword, newPassword } = req.body;
|
2022-11-01 07:42:37 +01:00
|
|
|
const { id } = req.query;
|
2020-09-11 22:49:43 +02:00
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
if (req.method === 'POST') {
|
2022-12-28 00:18:58 +01:00
|
|
|
if (!(await canUpdateUser(req.auth, id))) {
|
2022-12-02 05:53:37 +01:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2022-12-27 01:57:59 +01:00
|
|
|
const user = await getUser({ id }, { includePassword: true });
|
2020-08-09 11:03:37 +02:00
|
|
|
|
2022-12-27 02:36:48 +01:00
|
|
|
if (!checkPassword(currentPassword, user.password)) {
|
2020-08-09 11:03:37 +02:00
|
|
|
return badRequest(res, 'Current password is incorrect');
|
|
|
|
}
|
|
|
|
|
2022-12-27 02:36:48 +01:00
|
|
|
const password = hashPassword(newPassword);
|
2020-08-09 11:03:37 +02:00
|
|
|
|
2022-11-01 07:42:37 +01:00
|
|
|
const updated = await updateUser({ password }, { id });
|
2020-08-09 11:03:37 +02:00
|
|
|
|
|
|
|
return ok(res, updated);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|