Files
sign/apps/web/src/pages/api/auth/[...nextauth].ts

82 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-01-30 17:31:27 +11:00
import type { NextApiRequest, NextApiResponse } from 'next';
2023-06-09 18:21:18 +10:00
import NextAuth from 'next-auth';
import { getStripeCustomerByUser } from '@documenso/ee/server-only/stripe/get-customer';
import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
2023-06-09 18:21:18 +10:00
import { NEXT_AUTH_OPTIONS } from '@documenso/lib/next-auth/auth-options';
2024-01-31 12:27:40 +11:00
import { extractNextApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
2024-01-30 17:31:27 +11:00
import { prisma } from '@documenso/prisma';
import { UserSecurityAuditLogType } from '@documenso/prisma/client';
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
2024-01-31 12:27:40 +11:00
const { ipAddress, userAgent } = extractNextApiRequestMetadata(req);
2024-01-30 17:31:27 +11:00
return await NextAuth(req, res, {
...NEXT_AUTH_OPTIONS,
pages: {
signIn: '/signin',
signOut: '/signout',
error: '/signin',
},
events: {
signIn: async ({ user: { id: userId } }) => {
const [user] = await Promise.all([
await prisma.user.findFirstOrThrow({
where: {
id: userId,
},
}),
await prisma.userSecurityAuditLog.create({
data: {
2024-04-30 15:54:24 +07:00
userId,
ipAddress,
userAgent,
type: UserSecurityAuditLogType.SIGN_IN,
},
}),
]);
// Create the Stripe customer and attach it to the user if it doesn't exist.
if (user.customerId === null && IS_BILLING_ENABLED()) {
2024-04-30 15:50:22 +07:00
await getStripeCustomerByUser(user).catch((err) => {
console.error(err);
});
}
2024-01-30 17:31:27 +11:00
},
signOut: async ({ token }) => {
const userId = typeof token.id === 'string' ? parseInt(token.id) : token.id;
if (isNaN(userId)) {
return;
}
await prisma.userSecurityAuditLog.create({
data: {
userId,
ipAddress,
userAgent,
type: UserSecurityAuditLogType.SIGN_OUT,
},
});
},
linkAccount: async ({ user }) => {
const userId = typeof user.id === 'string' ? parseInt(user.id) : user.id;
if (isNaN(userId)) {
return;
}
2023-06-09 18:21:18 +10:00
2024-01-30 17:31:27 +11:00
await prisma.userSecurityAuditLog.create({
data: {
userId,
ipAddress,
userAgent,
type: UserSecurityAuditLogType.ACCOUNT_SSO_LINK,
},
});
},
},
});
}