Skip to content

Commit

Permalink
try adding callback for getting email account
Browse files Browse the repository at this point in the history
  • Loading branch information
jchaselubitz committed Dec 13, 2023
1 parent 66e57c4 commit f1d2424
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"multer": "^1.4.5-lts.1",
"multer-google-storage": "^1.3.0",
"next": "^13.2.4",
"next-auth": "^4.21.1",
"next-auth": "^4.24.5",
"next-connect": "^0.13.0",
"nodemailer": "^6.9.1",
"postcss": "^8.4.16",
Expand Down
38 changes: 28 additions & 10 deletions pages/api/auth/next-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { AuthOptions, Session, User } from 'next-auth';
import * as jwt from 'jsonwebtoken';
import { JWT } from 'next-auth/jwt';
import { postmarkClient } from '@src/services/postmark';
import { GET_USER_FROM_EMAIL } from '@src/utils/dGraphQueries/user';
import initializeApollo from '@src/utils/apolloClient';

const getEndpoint = () => {
if (process.env.NEXT_PUBLIC_DEPLOY_STAGE === 'production' || process.env.NEXT_PUBLIC_DEPLOY_STAGE === 'staging') {
Expand Down Expand Up @@ -144,13 +146,32 @@ const options: AuthOptions = {
// newUser: '/welcome',
},
callbacks: {
// async signIn({ user, account, profile, email, credentials }) {
// console.log('insignin', user, email);
// if (account?.provider === 'email' && !user.name) {
// user.name = ' '; // Set default name as empty string
// }
// return true;
// },
async signIn({ user, account, email }) {
// Ensure this runs only for the Email provider
if (account?.provider === 'email') {
const apolloClient = initializeApollo();

try {
const { data } = await apolloClient.query({
query: GET_USER_FROM_EMAIL,
variables: { emailAddress: email },
});

if (data && data.queryUser && data.queryUser.length > 0) {
// User exists, continue with sign in
return true;
} else {
// User does not exist, redirect to register page
return '/register';
}
} catch (error) {
throw new Error('Error checking user existence: ' + error?.message);
}
}

// For other providers, allow sign in
return true;
},
//@ts-ignore
async jwt({
token,
Expand All @@ -165,7 +186,6 @@ const options: AuthOptions = {
profile: any;
isNewUser: boolean;
}) {
console.log('In jwt callback:', { token, user, account, profile, isNewUser });
if (user) {
token.id = user.id;
token.name = user.name || '';
Expand All @@ -176,8 +196,6 @@ const options: AuthOptions = {
return token;
},
async session({ session, user, token }: { session: any; user: User; token: JWT }): Promise<Session> {
console.log('In session callback:', { session, user, token });

session.user.id = token.id;
session.encodedJwt = jwt.sign(token, process.env.NEXT_SECRET as string, {
algorithm: 'HS256',
Expand Down

0 comments on commit f1d2424

Please sign in to comment.