handle auth correctly and added change password

This commit is contained in:
Carl-Gerhard Lindesvärd
2023-10-28 22:59:33 +02:00
parent e0cc9ef83b
commit aa5c881ec6
7 changed files with 149 additions and 44 deletions

View File

@@ -5,7 +5,7 @@ import {
protectedProcedure,
} from "@/server/api/trpc";
import { db } from "@/server/db";
import { hashPassword } from "@/server/services/hash.service";
import { hashPassword, verifyPassword } from "@/server/services/hash.service";
export const userRouter = createTRPCRouter({
current: protectedProcedure.query(({ ctx }) => {
@@ -47,14 +47,10 @@ export const userRouter = createTRPCRouter({
}
})
if(user.password !== input.oldPassword) {
if(!(await verifyPassword(input.oldPassword, user.password))) {
throw new Error('Old password is incorrect')
}
if(user.password === input.password) {
throw new Error('New password cannot be the same as old password')
}
return db.user.update({
where: {
id: ctx.session.user.id

View File

@@ -8,7 +8,7 @@ import {
import { db } from "@/server/db";
import Credentials from "next-auth/providers/credentials";
import { createError } from "./exceptions";
import { verifyPassword } from "@/server/services/hash.service";
import { hashPassword, verifyPassword } from "@/server/services/hash.service";
/**
* Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`
@@ -55,18 +55,26 @@ export const authOptions: NextAuthOptions = {
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if(!credentials?.password || !credentials?.email) {
return null
}
const user = await db.user.findFirst({
where: { email: credentials?.email },
});
if (user) {
return {
...user,
image: 'https://avatars.githubusercontent.com/u/18133?v=4'
};
} else {
return null;
if(!user) {
return null
}
if(!await verifyPassword(credentials.password, user.password)) {
return null
}
return {
...user,
image: 'https://api.dicebear.com/7.x/adventurer/svg?seed=Abby'
};
},
}),
/**