Added better error handling for sign in api

This commit is contained in:
Khalim Conn-Kowlessar 2023-07-11 10:31:26 +01:00
parent d1e9d8949d
commit 64f5649db1

View file

@ -32,33 +32,43 @@ export const AuthOptions: NextAuthOptions = {
},
callbacks: {
async signIn({ user, account }) {
if (user == null || user.email == null) {
return "/beta";
}
try {
if (user == null || user.email == null) {
return "/beta";
}
const dbUser: User[] = await db
.select()
.from(userTable)
.where(eq(userTable.email, String(user.email)));
if (dbUser.length !== 1 || account == null) {
return "/beta";
}
if (!dbUser[0].oauthId) {
// We make a second query to populate the oauthId and oauthProvider
console.log("Updating user with oauthId and oauthProvider");
const provider = account.provider as OauthProvider;
await db
.update(userTable)
.set({ oauthId: user.id, oauthProvider: provider })
const dbUser: User[] = await db
.select()
.from(userTable)
.where(eq(userTable.email, String(user.email)));
console.log("Updated oauthId and oauthProvider");
}
if (dbUser.length > 1) {
console.error(`Multiple users found with email ${user.email}`);
return false;
}
return true;
if (dbUser.length !== 0 || account == null) {
return "/beta";
}
if (!dbUser[0].oauthId) {
// We make a second query to populate the oauthId and oauthProvider
console.log("Updating user with oauthId and oauthProvider");
const provider = account.provider as OauthProvider;
await db
.update(userTable)
.set({ oauthId: user.id, oauthProvider: provider })
.where(eq(userTable.email, String(user.email)));
console.log("Updated oauthId and oauthProvider");
}
return true;
} catch (error) {
console.error("Error during sign-in: ", error);
return false;
}
},
async redirect({ baseUrl }) {
const redirectUrl = baseUrl + "/home";