implement update user, update password and delete account

This commit is contained in:
m5r
2021-09-25 07:09:20 +08:00
parent 12983316f5
commit c9b657e44c
11 changed files with 220 additions and 83 deletions

View File

@ -0,0 +1,36 @@
import { AuthenticationError, NotFoundError, resolver, SecurePassword } from "blitz";
import { z } from "zod";
import db from "../../../db";
import { authenticateUser } from "../../auth/mutations/login";
import { password } from "../../auth/validations";
const Body = z.object({
currentPassword: z.string(),
newPassword: password,
});
export default resolver.pipe(
resolver.zod(Body),
resolver.authorize(),
async ({ currentPassword, newPassword }, ctx) => {
const user = await db.user.findFirst({ where: { id: ctx.session.userId! } });
if (!user) throw new NotFoundError();
try {
await authenticateUser(user.email, currentPassword);
} catch (error) {
if (error instanceof AuthenticationError) {
throw new Error("Current password is incorrect");
}
throw error;
}
const hashedPassword = await SecurePassword.hash(newPassword.trim());
await db.user.update({
where: { id: user.id },
data: { hashedPassword },
});
},
);

View File

@ -0,0 +1,14 @@
import { NotFoundError, resolver } from "blitz";
import db from "../../../db";
import logout from "../../auth/mutations/logout";
import deleteUserData from "../api/queue/delete-user-data";
export default resolver.pipe(resolver.authorize(), async (_ = null, ctx) => {
const user = await db.user.findFirst({ where: { id: ctx.session.userId! } });
if (!user) throw new NotFoundError();
await db.user.update({ where: { id: user.id }, data: { hashedPassword: "pending deletion" } });
await deleteUserData.enqueue({ userId: user.id });
await logout(null, ctx);
});

View File

@ -0,0 +1,25 @@
import { NotFoundError, resolver } from "blitz";
import { z } from "zod";
import db from "../../../db";
import notifyEmailChangeQueue from "../api/queue/notify-email-change";
const Body = z.object({
email: z.string().email(),
name: z.string(),
});
export default resolver.pipe(resolver.zod(Body), resolver.authorize(), async ({ email, name }, ctx) => {
const user = await db.user.findFirst({ where: { id: ctx.session.userId! } });
if (!user) throw new NotFoundError();
const oldEmail = user.email;
await db.user.update({
where: { id: user.id },
data: { email, name },
});
if (oldEmail !== email) {
// await notifyEmailChangeQueue.enqueue({ newEmail: email, oldEmail: user.email });
}
});