Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New User Management #35

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
7 changes: 5 additions & 2 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
import { handlers } from 'auth';
export const { GET, POST } = handlers;
import auth from 'auth'; // Import the default export from auth.ts
anantduggal marked this conversation as resolved.
Show resolved Hide resolved

// Export GET and POST to handle API routes
anantduggal marked this conversation as resolved.
Show resolved Hide resolved
export const GET = auth;
export const POST = auth;
83 changes: 83 additions & 0 deletions app/api/authOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import NextAuth, { AuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { prisma } from './prisma';

// Custom Google Profile Type
interface GoogleProfile {
sub: string;
name: string;
email: string;
picture: string;
given_name: string;
family_name: string;
}

// Define your NextAuth options
export const authOptions: AuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.AUTH_GOOGLE_ID as string,
clientSecret: process.env.AUTH_GOOGLE_SECRET as string,
authorization: {
params: {
scope: 'openid email profile',
},
},
profile(profile: GoogleProfile) {
return {
id: profile.sub,
name: profile.name,
email: profile.email,
picture: profile.picture,
firstName: profile.given_name,
lastName: profile.family_name,
};
},
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.AUTH_SECRET,
callbacks: {
async signIn({ account, profile }) {
console.log('Account: ', account);
console.log('Profile: ', profile);
const googleProfile = profile as any;

const firstName = googleProfile.given_name || '';
const lastName = googleProfile.family_name || '';

if (account?.provider === 'google' && profile?.email) {
try {
const existingUser = await prisma.user.findUnique({
where: { email: profile.email },
});

if (!existingUser) {
console.log(account.providerAccountId);
await prisma.user.create({
data: {
authId: account.providerAccountId,
email: profile.email,
firstName,
lastName,
role: 'TEACHER',
status: 'INVITED',
numOfAbsences: 10,
},
});
}
console.log('Success');

return true;
} catch (error) {
console.error('Error during sign-in:', error);
return false;
}
}
return false;
},
},
};

export default NextAuth(authOptions);
5 changes: 5 additions & 0 deletions app/api/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export { prisma };
112 changes: 105 additions & 7 deletions auth.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,107 @@
// This is the configuration file for next-auth (now, more generally known as auth.js) https://authjs.dev/
// Expects the following in the .env file: AUTH_SECRET, AUTH_GOOGLE_ID, AUTH_GOOGLE_SECRET
import NextAuth, { AuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { prisma } from './app/api/prisma';

import NextAuth from 'next-auth';
import Google from 'next-auth/providers/google';
// Custom Google Profile Type
anantduggal marked this conversation as resolved.
Show resolved Hide resolved
interface GoogleProfile {
sub: string;
name: string;
email: string;
picture: string;
given_name: string;
family_name: string;
}

export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [Google],
});
// Define your NextAuth options
anantduggal marked this conversation as resolved.
Show resolved Hide resolved
export const authOptions: AuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.AUTH_GOOGLE_ID as string,
clientSecret: process.env.AUTH_GOOGLE_SECRET as string,
authorization: {
params: {
scope: 'openid email profile',
},
},
profile(profile: GoogleProfile) {
return {
id: profile.sub,
name: profile.name,
email: profile.email,
picture: profile.picture,
firstName: profile.given_name,
lastName: profile.family_name,
};
},
}),
],
adapter: PrismaAdapter(prisma),
secret: process.env.AUTH_SECRET,

debug: true,

callbacks: {
async signIn({ account, profile }) {
console.log('Account: ', account);
console.log('Profile: ', profile);
const googleProfile = profile as any;

const firstName = googleProfile.given_name || '';
const lastName = googleProfile.family_name || '';

if (account?.provider === 'google' && profile?.email) {
try {
let existingUser = await prisma.user.findUnique({
where: { email: profile.email },
});

if (!existingUser) {
console.log('Creating new user...');
// console.log(account.providerAccountId);
anantduggal marked this conversation as resolved.
Show resolved Hide resolved
existingUser = await prisma.user.create({
data: {
authId: account.providerAccountId,
email: profile.email,
firstName,
lastName,
role: 'TEACHER',
status: 'INVITED',
numOfAbsences: 10,
},
});
console.log(
anantduggal marked this conversation as resolved.
Show resolved Hide resolved
'BAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAMBAM'
);
console.log('NEW USER IS CREATED ', existingUser.id);

console.log('ONTO ACCOUNTS');
anantduggal marked this conversation as resolved.
Show resolved Hide resolved

await prisma.account.create({
data: {
userId: existingUser.id,
provider: account.provider!,
providerAccountId: account.providerAccountId!,
refreshToken: account.refresh_token,
accessToken: account.access_token,
accessTokenExpires: account.expires_at
? new Date(account.expires_at * 1000)
: null,
providerType: 'oauth',
},
});
console.log('Linked Google account to existing user');
}

return true;
} catch (error) {
console.error('Error during sign-in:', error);
return false;
}
}
return false;
},
},
};

export default NextAuth(authOptions);
Loading