-
Notifications
You must be signed in to change notification settings - Fork 6
/
authenticateOpenId.ts
343 lines (311 loc) · 8.76 KB
/
authenticateOpenId.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import {
GraphQLFieldConfig,
GraphQLID,
GraphQLNonNull,
GraphQLString
} from "graphql";
import jwt from "jsonwebtoken";
import { randomBytes } from "crypto";
import v4 from "uuid/v4";
import fetch from "node-fetch";
import FormData from "form-data";
import {
Context,
GraphQLAuthorization,
Authority,
Authorization,
User,
Role,
ForbiddenError,
AuthenticationError
} from "@authx/authx";
import { createV2AuthXScope } from "@authx/authx/dist/util/scopes";
import { isSuperset } from "@authx/scopes";
import { EmailAuthority } from "@authx/strategy-email";
import { OpenIdAuthority, OpenIdCredential } from "../../model";
export const authenticateOpenId: GraphQLFieldConfig<
any,
{
authorityId: string;
code: string;
},
Context
> = {
type: GraphQLAuthorization,
description: "Create a new authorization.",
args: {
authorityId: {
type: new GraphQLNonNull(GraphQLID)
},
code: {
type: new GraphQLNonNull(GraphQLString),
description:
"The OAuth authorization code provided by the OpenID exchange."
}
},
async resolve(source, args, context): Promise<Authorization> {
const {
pool,
authorization: a,
realm,
strategies: { authorityMap },
base
} = context;
if (a) {
throw new ForbiddenError("You area already authenticated.");
}
const tx = await pool.connect();
try {
await tx.query("BEGIN DEFERRABLE");
// Fetch the authority.
const authority = await Authority.read(
tx,
args.authorityId,
authorityMap
);
if (!(authority instanceof OpenIdAuthority)) {
throw new AuthenticationError(
"The authority uses a strategy other than openid."
);
}
// Fetch the ID token.
const requestBody = new FormData();
requestBody.append("grant_type", "authorization_code");
requestBody.append("client_id", authority.details.clientId);
requestBody.append("client_secret", authority.details.clientSecret);
requestBody.append("code", args.code);
requestBody.append(
"redirect_uri",
`${base}?authorityId=${args.authorityId}`
);
const response = await fetch(authority.details.tokenUrl, {
method: "POST",
body: requestBody
});
const responseBody = (await response.json()) as {
access_token: string;
id_token: string;
expires_in: number;
token_type: string;
refresh_token?: string;
error?: string;
};
if (!responseBody || !responseBody.id_token) {
throw new Error(
(responseBody && responseBody.error) ||
"Invalid response returned by authority."
);
}
// Decode the ID token.
const token = jwt.decode(responseBody.id_token) as {
sub: string;
iss: string;
azp?: string;
aud: string;
iat: number;
exp: number;
name?: string;
given_name?: string;
family_name?: string;
middle_name?: string;
nickname?: string;
preferred_username?: string;
profile?: string;
picture?: string;
website?: string;
email?: string;
email_verified?: boolean;
gender?: string;
birthdate?: string;
zoneinfo?: string;
locale?: string;
phone_number?: string;
phone_number_verified?: boolean;
address?: {
formatted?: string;
street_address?: string;
locality?: string;
region?: string;
postal_code?: string;
country?: string;
};
updated_at?: number;
// This is a google-specific claim for "hosted domain".
hd?: string;
};
if (!token || typeof token.sub !== "string" || !token.sub) {
throw new Error("Invalid token returned by authority.");
}
// Restrict user based to hosted domain.
if (
authority.details.restrictsAccountsToHostedDomains.length &&
(!token.hd ||
!authority.details.restrictsAccountsToHostedDomains.includes(
token.hd
))
) {
throw new AuthenticationError(
`The hosted domain "${token.hd || ""}" is not allowed.`
);
}
const authorizationId = v4();
// Get the credential
let credential = await authority.credential(tx, token.sub);
// Try to associate an existing user by email.
if (
!credential &&
authority.details.emailAuthorityId &&
authority.details.matchesUsersByEmail &&
token.email &&
token.email_verified
) {
const emailAuthority = await EmailAuthority.read(
tx,
authority.details.emailAuthorityId
);
const emailCredential =
emailAuthority &&
emailAuthority.enabled &&
(await emailAuthority.credential(tx, token.email));
if (emailCredential && emailCredential.enabled) {
credential = await OpenIdCredential.write(
tx,
{
enabled: true,
id: v4(),
userId: emailCredential.userId,
authorityId: authority.id,
authorityUserId: token.sub,
details: {}
},
{
recordId: v4(),
createdByAuthorizationId: authorizationId,
createdAt: new Date()
}
);
}
}
// Create a new user.
if (!credential && authority.details.createsUnmatchedUsers) {
const user = await User.write(
tx,
{
id: v4(),
enabled: true,
type: "human",
name: token.name || ""
},
{
recordId: v4(),
createdByAuthorizationId: authorizationId,
createdAt: new Date()
}
);
credential = await OpenIdCredential.write(
tx,
{
enabled: true,
id: v4(),
userId: user.id,
authorityId: authority.id,
authorityUserId: token.sub,
details: {}
},
{
recordId: v4(),
createdByAuthorizationId: authorizationId,
createdAt: new Date()
}
);
// Assign the new user to the configured roles.
if (
authority.details.assignsCreatedUsersToRoleIds &&
authority.details.assignsCreatedUsersToRoleIds.length
) {
const roles = await Promise.all(
authority.details.assignsCreatedUsersToRoleIds.map(id =>
Role.read(tx, id)
)
);
await roles.map(role =>
Role.write(
tx,
{
...role,
userIds: [...role.userIds, user.id]
},
{
recordId: v4(),
createdByAuthorizationId: authorizationId,
createdAt: new Date()
}
)
);
}
}
if (!credential) {
throw new AuthenticationError("No such credential exists.");
}
const values = {
currentAuthorizationId: authorizationId,
currentUserId: credential.userId,
currentGrantId: null,
currentClientId: null
};
// Make sure the user can create new authorizations.
const user = await User.read(tx, credential.userId);
if (
!isSuperset(
await user.access(tx, values),
createV2AuthXScope(
realm,
{
type: "authorization",
authorizationId: "",
grantId: "",
clientId: "",
userId: user.id
},
{
basic: "*",
scopes: "*",
secrets: "*"
}
)
)
) {
throw new ForbiddenError(
"You do not have permission to create this authorization"
);
}
// Create a new authorization.
const authorization = await Authorization.write(
tx,
{
id: authorizationId,
enabled: true,
userId: credential.userId,
grantId: null,
secret: randomBytes(16).toString("hex"),
scopes: [`${realm}:**:**`]
},
{
recordId: v4(),
createdByAuthorizationId: authorizationId,
createdByCredentialId: credential.id,
createdAt: new Date()
}
);
await tx.query("COMMIT");
// use this authorization for the rest of the request
context.authorization = authorization;
return authorization;
} catch (error) {
await tx.query("ROLLBACK");
throw error;
} finally {
tx.release();
}
}
};