2022-11-01 07:42:37 +01:00
|
|
|
import { getUser, updateUser } 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';
|
2022-10-25 19:45:56 +02:00
|
|
|
import { allowQuery } from 'lib/auth';
|
2022-11-01 17:56:43 +01:00
|
|
|
import { TYPE_USER } from 'lib/constants';
|
2022-11-15 22:21:14 +01:00
|
|
|
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
|
|
|
|
import { NextApiResponse } from 'next';
|
|
|
|
import { User } from 'interface/api/models';
|
|
|
|
|
|
|
|
export interface UserPasswordRequestQuery {
|
|
|
|
id: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface UserPasswordRequestBody {
|
|
|
|
current_password: string;
|
|
|
|
new_password: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<UserPasswordRequestQuery, UserPasswordRequestBody>,
|
|
|
|
res: NextApiResponse<User>,
|
|
|
|
) => {
|
2020-08-09 11:03:37 +02:00
|
|
|
await useAuth(req, res);
|
|
|
|
|
2022-10-04 02:17:53 +02:00
|
|
|
const { current_password, new_password } = req.body;
|
2022-11-01 07:42:37 +01:00
|
|
|
const { id } = req.query;
|
2020-08-09 11:03:37 +02:00
|
|
|
|
2022-11-01 17:56:43 +01:00
|
|
|
if (!(await allowQuery(req, TYPE_USER))) {
|
2020-09-11 22:49:43 +02:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2020-08-09 11:03:37 +02:00
|
|
|
if (req.method === 'POST') {
|
2022-11-01 07:42:37 +01:00
|
|
|
const user = await getUser({ id });
|
2020-08-09 11:03:37 +02:00
|
|
|
|
2022-11-01 07:42:37 +01:00
|
|
|
if (!checkPassword(current_password, user.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-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);
|
|
|
|
};
|