Files
evidencija-rezija/app/lib/auth.ts
2024-01-08 16:32:08 +01:00

65 lines
2.3 KiB
TypeScript

import NextAuth, { NextAuthConfig } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { Session } from 'next-auth';
import { AuthenticatedUser } from './types/next-auth';
const authConfig: NextAuthConfig = {
callbacks: {
// method verifies if the user is logged in or not
// -> is called by Next-Auth when the midleware calls the `auth` method (exported below)
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
return (isLoggedIn);
},
// method is called when the user is not logged in
// this is a hack which takes user ID and assigns it temporaty to the token, which is then used to extend Session.user
// see: https://stackoverflow.com/questions/70409219/get-user-id-from-session-in-next-auth-client
jwt({ token, account, user }) {
if (account) {
token.accessToken = account.access_token
token.id = user?.id
}
return token
},
// method is called after the JWT token is created
// this is a hack which takes user ID temporaty assigned to the token and assigns it to the Session.user
// see: https://stackoverflow.com/questions/70409219/get-user-id-from-session-in-next-auth-client
async session({ session, token }:{ session:Session, token:any }) {
if(session.user && token) {
session.user.id = token.id;
}
return session;
},
},
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
secret: process.env.AUTH_SECRET,
session: {
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `jwt` is automatically set to `true` if no database is specified.
strategy: 'jwt'
},
};
export const { auth, handlers: { GET, POST } } = NextAuth(authConfig);
export const withUser = (fn: (user: AuthenticatedUser, ...args:any) => Promise<any>) => async (...args:any) => {
const session = await auth();
if(!session) {
return({
errors: {
message: "Not authenticated",
},
message: "Not authenticated",
});
}
const { user } = session;
return(fn(user, ...args));
}