-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
76 lines (68 loc) · 2.58 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { createGuest, getGuestByEmail } from "./app/_lib/supabase/guests";
import { credentials } from "./app/_lib/authjs/credentialsCallback";
import Google from "next-auth/providers/google";
import Facebook from "next-auth/providers/facebook";
import { SupabaseAdapter } from "@auth/supabase-adapter";
import jwt from "jsonwebtoken";
export const { handlers, signIn, signOut, auth } = NextAuth({
session: { maxAge: 60 * 60 },
pages: {
signIn: "/signin",
},
adapter: SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL ?? "",
secret: process.env.SUPABASE_SERVICE_ROLE_KEY ?? "",
}),
providers: [
Credentials(credentials),
Google({ clientId: process.env.AUTH_GOOGLE_ID, clientSecret: process.env.AUTH_GOOGLE_SECRET }),
Facebook({ clientId: process.env.AUTH_FACEBOOK_ID, clientSecret: process.env.AUTH_FACEBOOK_SECRET }),
],
callbacks: {
authorized({ req, auth }) {
return !!auth;
},
async signIn({ account, user }) {
// When credentials are valid, there is no need to go through SignIn callback because
// all the needed validation have been handled in the authorize() of the credentials provider
if (account.provider === "credentials") return true;
// This is for facebook provider, since some accounts might not be bound with an email address
if (!user.email) return false;
try {
const guest = await getGuestByEmail(user.email);
if (guest) {
return true;
}
} catch (err) {
return false;
}
// When going with OAuth providers, if a user does not have already an account, we simply create it on the go just to reduce a sign up step
try {
await createGuest(user.name, user.email, user.image);
} catch (err) {
return false;
}
return true;
},
async session({ session, token, user }) {
const currentGuest = await getGuestByEmail(session.user.email);
session.user.id = currentGuest.id;
session.user.name = currentGuest.fullname;
session.avatar = currentGuest.avatar;
const signingSecret = process.env.SUPABASE_JWT_SECRET;
if (signingSecret) {
const payload = {
aud: "authenticated",
exp: Math.floor(new Date(session.expires).getTime() / 1000),
sub: currentGuest.fullname,
email: user.email,
role: "authenticated",
};
session.supabaseAccessToken = jwt.sign(payload, signingSecret);
}
return session;
},
},
});