umami/pages/api/me/password.ts

52 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-02-28 04:03:04 +00:00
import { NextApiRequestQueryBody, User } from 'lib/types';
2020-08-09 09:03:37 +00:00
import { useAuth } from 'lib/middleware';
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,
hashPassword,
2022-08-29 03:20:54 +00:00
methodNotAllowed,
2023-02-28 04:03:04 +00:00
forbidden,
2022-08-29 03:20:54 +00:00
ok,
} from 'next-basics';
2023-02-28 04:03:04 +00:00
import { getUser, updateUser } from 'queries';
2022-11-15 21:21:14 +00:00
export interface UserPasswordRequestQuery {
id: string;
}
export interface UserPasswordRequestBody {
2022-12-27 01:36:48 +00:00
currentPassword: string;
newPassword: string;
2022-11-15 21:21:14 +00:00
}
export default async (
req: NextApiRequestQueryBody<UserPasswordRequestQuery, UserPasswordRequestBody>,
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);
2022-12-27 01:36:48 +00:00
const { currentPassword, newPassword } = req.body;
2023-04-02 21:23:21 +00:00
const { id } = req.auth.user;
2020-09-11 20:49:43 +00:00
2020-08-09 09:03:37 +00:00
if (req.method === 'POST') {
const user = await getUser({ id }, { 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
2022-11-01 06:42:37 +00:00
const updated = await updateUser({ password }, { id });
2020-08-09 09:03:37 +00:00
return ok(res, updated);
}
return methodNotAllowed(res);
};