You've already forked obsidian-visualiser
Password reset and new email validation ID stored in DB for more security
This commit is contained in:
75
server/api/users/[id]/change-password.post.ts
Normal file
75
server/api/users/[id]/change-password.post.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { and, count, eq } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
import { usersTable } from '~/db/schema';
|
||||
import { schema as registration } from '~/schemas/registration';
|
||||
import useDatabase from '~/composables/useDatabase';
|
||||
|
||||
const schema = z.object({
|
||||
newPassword: registration.shape.password,
|
||||
oldPassword: registration.shape.password,
|
||||
});
|
||||
|
||||
export default defineEventHandler(async (e) => {
|
||||
try
|
||||
{
|
||||
const session = await getUserSession(e);
|
||||
|
||||
if(!session || !session.user || !session.user.id)
|
||||
{
|
||||
return createError({
|
||||
statusCode: 401,
|
||||
message: 'Unauthorized',
|
||||
});
|
||||
}
|
||||
|
||||
const id = getRouterParam(e, 'id');
|
||||
|
||||
if(!id)
|
||||
{
|
||||
return createError({
|
||||
statusCode: 403,
|
||||
message: 'Forbidden',
|
||||
});
|
||||
}
|
||||
if(session.user.id.toString() !== id)
|
||||
{
|
||||
return createError({
|
||||
statusCode: 401,
|
||||
message: 'Unauthorized',
|
||||
});
|
||||
}
|
||||
|
||||
const body = await readValidatedBody(e, schema.safeParse);
|
||||
|
||||
if(!body.success)
|
||||
throw body.error;
|
||||
|
||||
const db = useDatabase();
|
||||
console.log(body.data.oldPassword, await Bun.password.hash(body.data.oldPassword));
|
||||
const check = db.select({ hash: usersTable.hash }).from(usersTable).where(eq(usersTable.id, session.user.id)).get();
|
||||
|
||||
if(!check || !check.hash)
|
||||
{
|
||||
return createError({
|
||||
statusCode: 401,
|
||||
message: 'Unauthorized',
|
||||
});
|
||||
}
|
||||
if(!await Bun.password.verify(body.data.oldPassword, check.hash))
|
||||
{
|
||||
return { success: false, error: "Ancien mot de passe incorrect" };
|
||||
}
|
||||
|
||||
db.update(usersTable).set({ hash: await Bun.password.hash(body.data.newPassword) }).where(eq(usersTable.id, session.user.id)).run();
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
catch(err: any)
|
||||
{
|
||||
console.error(err);
|
||||
|
||||
return createError({
|
||||
statusCode: 500,
|
||||
});
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user