umami/src/pages/api/me/password.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-08-20 05:23:15 +00:00
import { useAuth, useValidate } from 'lib/middleware';
2023-02-28 04:03:04 +00:00
import { NextApiRequestQueryBody, User } from 'lib/types';
2022-11-19 02:49:58 +00:00
import { NextApiResponse } from 'next';
2022-08-29 03:20:54 +00:00
import {
badRequest,
2022-11-19 02:49:58 +00:00
checkPassword,
2023-08-20 05:23:15 +00:00
forbidden,
2022-11-19 02:49:58 +00:00
hashPassword,
2022-08-29 03:20:54 +00:00
methodNotAllowed,
ok,
} from 'next-basics';
2024-01-30 08:10:25 +00:00
import { getUser, updateUser } from 'queries';
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
2022-11-15 21:21:14 +00:00
export interface UserPasswordRequestBody {
2022-12-27 01:36:48 +00:00
currentPassword: string;
newPassword: string;
2022-11-15 21:21:14 +00:00
}
2023-08-20 05:23:15 +00:00
const schema = {
POST: yup.object().shape({
currentPassword: yup.string().required(),
newPassword: yup.string().min(8).required(),
}),
};
2022-11-15 21:21:14 +00:00
export default async (
2024-02-01 06:08:48 +00:00
req: NextApiRequestQueryBody<any, UserPasswordRequestBody>,
2022-11-15 21:21:14 +00:00
res: NextApiResponse<User>,
) => {
2023-02-28 04:03:04 +00:00
if (process.env.CLOUD_MODE) {
return forbidden(res);
}
2020-08-09 09:03:37 +00:00
await useAuth(req, res);
2023-09-30 03:24:48 +00:00
await useValidate(schema, req, res);
2023-08-20 05:23:15 +00:00
2022-12-27 01:36:48 +00:00
const { currentPassword, newPassword } = req.body;
2024-02-01 06:08:48 +00:00
const { id: userId } = req.auth.user;
2020-09-11 20:49:43 +00:00
2020-08-09 09:03:37 +00:00
if (req.method === 'POST') {
2024-02-01 06:08:48 +00:00
const user = await getUser(userId, { includePassword: true });
2020-08-09 09:03:37 +00:00
2022-12-27 01:36:48 +00:00
if (!checkPassword(currentPassword, user.password)) {
2020-08-09 09:03:37 +00:00
return badRequest(res, 'Current password is incorrect');
}
2022-12-27 01:36:48 +00:00
const password = hashPassword(newPassword);
2020-08-09 09:03:37 +00:00
2024-02-01 06:08:48 +00:00
const updated = await updateUser(userId, { password });
2020-08-09 09:03:37 +00:00
return ok(res, updated);
}
return methodNotAllowed(res);
};