-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.ts
181 lines (164 loc) · 5.65 KB
/
auth.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { Result } from "@repo/strapi"
import { getServerSession } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import type {
GetServerSidePropsContext,
NextApiRequest,
NextApiResponse,
} from "next"
import type { NextAuthOptions } from "next-auth"
import Strapi from "./strapi"
export const authOptions: NextAuthOptions = {
session: {
strategy: "jwt",
maxAge: 2592000, // 30 days - synced with strapi
},
providers: [
CredentialsProvider({
name: "StrapiCredentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials.password) {
return null
}
return (
Strapi.fetchAPI(
`/auth/local`,
undefined,
{
body: JSON.stringify({
identifier: credentials.email,
password: credentials.password,
}),
method: "POST",
next: { revalidate: 0 },
},
{ omitAuthorization: true }
)
.then((data) => {
const { jwt, user } = data
if (jwt == null || user == null) {
return null
}
return {
name: user.username,
email: user.email,
// strapi user id is a number, but next-auth expects a string
id: user.id.toString(),
userId: user.id,
blocked: user.blocked,
strapiJWT: jwt,
}
})
// eslint-disable-next-line no-unused-vars
.catch((_error) => {
return null
})
)
},
}),
],
callbacks: {
jwt: async ({ token, user, trigger, account, session }) => {
if (trigger === "update" && session?.username) {
// change username update
token.name = session.username
}
if (trigger === "update" && session?.strapiJWT) {
// change password update
token.strapiJWT = session.strapiJWT
}
if (account) {
// initial login
if (account.access_token != null) {
// OAuth login - connect the account
try {
const data = await Strapi.fetchAPI(
`/auth/${account.provider}/callback?access_token=${account.access_token}`,
undefined,
{ next: { revalidate: 0 } }
)
const { jwt, user } = data
if (jwt == null) {
throw new Error("No JWT provided by Strapi API")
}
// add only necessary data to the token
token.strapiJWT = jwt
token.userId = user?.id
token.blocked = user?.blocked
} catch (error: any) {
token.error = "oauth_error"
if (error?.message?.includes("Email is already taken")) {
token.error = "different_provider"
}
}
}
if (account.provider === "credentials") {
// credentials login
// add only necessary data to the token
// make sure structure is the same as in OAuth login
token.strapiJWT = user.strapiJWT
token.userId = user.userId
token.blocked = user.blocked
}
}
// do not attach the whole user data to this final token object
// the token object is encrypted into JWT cookie string which is then sent in the requests
// very long tokens can cause problems (cookie size limit, performance, kill the server)
return token
},
session: async ({ token, session }) => {
if (token?.strapiJWT != null && token?.error == null) {
// check if token is valid and user data is still up-to-date
// this is optional
// this block checks validity of the token against strapi
// the check happens on every get session call (many times)
// it can be removed to improve performance but weird things can happen
// (user is logged in within NextAuth and UI but not in Strapi API)
try {
const fetchedUser: Result<"plugin::users-permissions.user"> =
await Strapi.fetchAPI(
"/users/me",
undefined,
{ next: { revalidate: 0 } },
{ strapiJWT: token.strapiJWT }
)
// API token is valid - update/reload user data or add more data
token.name = fetchedUser.username
token.blocked = fetchedUser.blocked ?? false
} catch (error: any) {
// API token is invalid - send error to client and user is logged out
// console.error("Strapi JWT token is invalid: ", error.message)
token.error = "invalid_strapi_token"
}
}
if (token) {
// expose following data to the client (/api/auth/session response)
// don't expose sensitive data
// we can add more data to "session" object if needed (user roles, avatar, etc.)
// data passed from here are not part of the JWT token and cookie
session.error = token.error
session.strapiJWT = token.strapiJWT
session.user.userId = token.userId
session.user.blocked = token.blocked
}
return session
},
},
pages: {
signIn: "/auth/signin",
signOut: "/auth/signout",
},
}
// Use it in server contexts
export function getAuth(
...args:
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
| [NextApiRequest, NextApiResponse]
| []
) {
return getServerSession(...args, authOptions)
}