/
authOptions.ts
155 lines (147 loc) · 4.9 KB
/
authOptions.ts
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import { StrapiErrorT } from '@/types/strapi/StrapiError';
import { StrapiLoginResponseT } from '@/types/strapi/User';
import { NextAuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import CredentialsProvider from 'next-auth/providers/credentials';
export const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID ?? '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? '',
}),
CredentialsProvider({
name: 'email and password',
credentials: {
identifier: {
label: 'Email or username *',
type: 'text',
},
password: { label: 'Password *', type: 'password' },
},
async authorize(credentials, req) {
// make sure the are credentials
if (!credentials || !credentials.identifier || !credentials.password) {
return null;
}
try {
const strapiResponse = await fetch(
`${process.env.STRAPI_BACKEND_URL}/api/auth/local`,
{
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({
identifier: credentials!.identifier,
password: credentials!.password,
}),
}
);
if (!strapiResponse.ok) {
// return error to signIn callback
const contentType = strapiResponse.headers.get('content-type');
if (contentType === 'application/json; charset=utf-8') {
const data: StrapiErrorT = await strapiResponse.json();
throw new Error(data.error.message);
} else {
throw new Error(strapiResponse.statusText);
}
}
// success
const data: StrapiLoginResponseT = await strapiResponse.json();
return {
name: data.user.username,
email: data.user.email,
id: data.user.id.toString(),
strapiUserId: data.user.id,
blocked: data.user.blocked,
strapiToken: data.jwt,
};
} catch (error) {
// Catch errors in try but also f.e. connection fails
throw error;
}
},
}),
],
callbacks: {
async signIn({ user, account, profile }) {
// console.log('singIn callback', { account, profile, user });
if (
account &&
account.provider === 'google' &&
profile &&
'email_verified' in profile
) {
if (!profile.email_verified) return false;
}
return true;
},
async jwt({ token, trigger, account, user, session }) {
// console.log('jwt callback', {
// token,
// trigger,
// account,
// user,
// session,
// });
if (trigger === 'update' && session?.username) {
token.name = session.username;
}
if (account) {
if (account.provider === 'google') {
// we now know we are doing a sign in using GoogleProvider
try {
const strapiResponse = await fetch(
`${process.env.STRAPI_BACKEND_URL}/api/auth/${account.provider}/callback?access_token=${account.access_token}`,
{ cache: 'no-cache' }
);
if (!strapiResponse.ok) {
const strapiError: StrapiErrorT = await strapiResponse.json();
// console.log('strapiError', strapiError);
throw new Error(strapiError.error.message);
}
const strapiLoginResponse: StrapiLoginResponseT =
await strapiResponse.json();
// customize token
// name and email will already be on here
token.strapiToken = strapiLoginResponse.jwt;
token.strapiUserId = strapiLoginResponse.user.id;
token.provider = account.provider;
token.blocked = strapiLoginResponse.user.blocked;
} catch (error) {
throw error;
}
}
if (account.provider === 'credentials') {
// for credentials, not google provider
// name and email are taken care of by next-auth or authorize
token.strapiToken = user.strapiToken;
token.strapiUserId = user.strapiUserId;
token.provider = account.provider;
token.blocked = user.blocked;
}
}
return token;
},
async session({ token, session }) {
// console.log('session callback', {
// token,
// session,
// });
session.strapiToken = token.strapiToken;
session.provider = token.provider;
session.user.strapiUserId = token.strapiUserId;
session.user.blocked = token.blocked;
return session;
},
},
session: {
strategy: 'jwt',
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: '/signin',
error: '/authError',
},
};