cal.pub0.org/pages/api/auth/[...nextauth].tsx

74 lines
1.9 KiB
TypeScript
Raw Normal View History

import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import prisma from "../../../lib/prisma";
2021-08-18 12:15:22 +00:00
import { Session, verifyPassword } from "../../../lib/auth";
2021-03-24 15:03:04 +00:00
export default NextAuth({
session: {
jwt: true,
},
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
error: "/auth/error", // Error code passed in query string as ?error=
},
providers: [
Providers.Credentials({
name: "Calendso",
credentials: {
email: { label: "Email Address", type: "email", placeholder: "john.doe@example.com" },
password: { label: "Password", type: "password", placeholder: "Your super secure password" },
},
async authorize(credentials) {
const user = await prisma.user.findFirst({
where: {
email: credentials.email,
},
});
2021-03-24 15:03:04 +00:00
if (!user) {
throw new Error("No user found");
}
if (!user.password) {
throw new Error("Incorrect password");
}
2021-03-24 15:03:04 +00:00
const isValid = await verifyPassword(credentials.password, user.password);
2021-03-24 15:03:04 +00:00
if (!isValid) {
throw new Error("Incorrect password");
}
2021-03-24 15:03:04 +00:00
return {
id: user.id,
username: user.username,
email: user.email,
name: user.name,
image: user.avatar,
};
},
}),
],
callbacks: {
async jwt(token, user) {
// Add username to the token right after signin
if (user?.username) {
token.id = user.id;
token.username = user.username;
}
return token;
},
async session(session, token) {
2021-08-18 12:15:22 +00:00
const calendsoSession: Session = {
...session,
user: {
...session.user,
id: token.id as number,
username: token.username as string,
2021-05-05 20:01:56 +00:00
},
};
return calendsoSession;
2021-05-05 20:01:56 +00:00
},
},
2021-05-05 20:01:56 +00:00
});