diff --git a/app/auth.ts b/app/auth.ts index ec6657cc8..2f7151725 100644 --- a/app/auth.ts +++ b/app/auth.ts @@ -5,6 +5,8 @@ import { } from "next-auth"; import AzureADProvider from "next-auth/providers/azure-ad"; +import { incrementSignInCount, incrementSessionRefreshCount } from '../utils/cloud/redisRestClient'; + /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. @@ -60,6 +62,12 @@ export const authOptions: NextAuthOptions = { export const authOptions: NextAuthOptions = { callbacks: { async signIn({ user, account, profile }) { + if (!user?.email) { + console.error("Email is required for sign in"); + return false; // Prevent sign-in + } + const dateKey = new Date().toISOString().slice(0, 7); // "YYYY-MM" + await incrementSignInCount(user.email, dateKey); return true; }, async session({ session, token }) { @@ -71,6 +79,17 @@ export const authOptions: NextAuthOptions = { id: userId, }; + // Assuming the email is stored in the token and not directly in the session.user object + if (!token?.email) { + console.error("Email is required for session handling"); + // Modify the session object as needed or return a modified session + // For example, you might want to set a flag indicating an incomplete session + session.error = "Email is missing"; + return session; // Return the modified session + } + const dateKey = new Date().toISOString().slice(0, 7); // "YYYY-MM" + await incrementSessionRefreshCount(token.email, dateKey); + return session; }, // Add other callbacks with async as needed diff --git a/app/utils/cloud/redisRestClient.ts b/app/utils/cloud/redisRestClient.ts index b82544267..dcf256021 100644 --- a/app/utils/cloud/redisRestClient.ts +++ b/app/utils/cloud/redisRestClient.ts @@ -14,6 +14,28 @@ const headers = { 'Content-Type': 'application/json', }; +export const incrementSignInCount = async (email: string | undefined, dateKey: string) => { + if (!email) { + console.error('Email is undefined, cannot increment sign-in count.'); + return; + } + + const response = await fetch(`${redisRestUrl}/hincrby`, { + method: 'POST', + headers: headers, + body: JSON.stringify({ + key: `signin_count:${email}`, + field: dateKey, + increment: 1 + }), + }); + + if (!response.ok) { + console.error('Failed to increment sign-in count in Redis via REST API'); + } + }; + + export const incrementSessionRefreshCount = async (email: string | undefined, dateKey: string) => { if (!email) { console.error('Email is undefined, cannot increment session refresh count.');