Skip to content

Commit

Permalink
Improve error checking for NextAuth configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielMajeri committed Jan 16, 2024
1 parent 9c0f99a commit 5415a7f
Showing 1 changed file with 47 additions and 19 deletions.
66 changes: 47 additions & 19 deletions src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,54 @@
import { NextAuthOptions } from "next-auth";
import NextAuth from "next-auth/next";
import AzureAD from "next-auth/providers/azure-ad";
import type { Provider } from "next-auth/providers/index";
// import prisma from "@/db/prisma";

const providers: Provider[] = [];

const tenantId = process.env.AZURE_AD_TENANT_ID;
if (typeof tenantId !== "string" || !tenantId) {
throw Error(
"Required environment variable `AZURE_AD_TENANT_ID` is not defined",
);
}

const clientId = process.env.AZURE_AD_CLIENT_ID;
if (typeof clientId !== "string" || !clientId) {
throw Error(
"Required environment variable `AZURE_AD_CLIENT_ID` is not defined",
);
}

const clientSecret = process.env.AZURE_AD_CLIENT_SECRET;
if (typeof clientSecret !== "string" || !clientSecret) {
throw Error(
"Required environment variable `AZURE_AD_CLIENT_SECRET` is not defined",
);
}

providers.push(
AzureAD({
tenantId,
clientId,
clientSecret,
authorization: {
params: {},
},
profile(profile) {
return {
id: profile.sub,
azureAdObjectId: profile.oid,
name: profile.name,
email: profile.email,
image: profile.picture ?? null,
};
},
}),
);

export const authOptions: NextAuthOptions = {
providers: [
AzureAD({
clientId: process.env.AZURE_AD_CLIENT_ID as string,
clientSecret: process.env.AZURE_AD_CLIENT_SECRET as string,
tenantId: process.env.AZURE_AD_TENANT_ID as string,
authorization: {
params: {},
},
profile(profile) {
return {
id: profile.sub,
azureAdObjectId: profile.oid,
name: profile.name,
email: profile.email,
image: profile.picture ?? null,
};
},
}),
],
providers,

callbacks: {
async signIn({ user }) {
Expand Down Expand Up @@ -74,5 +100,7 @@ export const authOptions: NextAuthOptions = {
signIn: "/auth/signin",
},
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

0 comments on commit 5415a7f

Please sign in to comment.