strapi-plugin-oidc 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,741 @@
1
+ import axios from "axios";
2
+ import { randomUUID, randomBytes } from "node:crypto";
3
+ import pkceChallenge from "pkce-challenge";
4
+ import strapiUtils from "@strapi/utils";
5
+ import generator from "generate-password";
6
+ function register$1() {
7
+ }
8
+ async function bootstrap({ strapi: strapi2 }) {
9
+ const actions = [
10
+ {
11
+ section: "plugins",
12
+ displayName: "Read",
13
+ uid: "read",
14
+ pluginName: "strapi-plugin-oidc"
15
+ },
16
+ {
17
+ section: "plugins",
18
+ displayName: "Update",
19
+ uid: "update",
20
+ pluginName: "strapi-plugin-oidc"
21
+ }
22
+ ];
23
+ await strapi2.admin.services.permission.actionProvider.registerMany(actions);
24
+ try {
25
+ const oidcRoleCount = await strapi2.query("plugin::strapi-plugin-oidc.roles").count({
26
+ where: { oauth_type: "4" }
27
+ });
28
+ if (oidcRoleCount === 0) {
29
+ const editorRole = await strapi2.query("admin::role").findOne({
30
+ where: { code: "strapi-editor" }
31
+ });
32
+ if (editorRole) {
33
+ await strapi2.query("plugin::strapi-plugin-oidc.roles").create({
34
+ data: {
35
+ oauth_type: "4",
36
+ roles: [editorRole.id.toString()]
37
+ }
38
+ });
39
+ }
40
+ }
41
+ } catch (err) {
42
+ strapi2.log.warn("Could not initialize default OIDC role:", err.message);
43
+ }
44
+ strapi2.db.lifecycles.subscribe({
45
+ models: ["admin::user"],
46
+ async afterUpdate(event) {
47
+ const { result } = event;
48
+ if (!result?.email) return;
49
+ const query = strapi2.query("plugin::strapi-plugin-oidc.whitelists");
50
+ const whitelistEntry = await query.findOne({ where: { email: result.email } });
51
+ if (!whitelistEntry) return;
52
+ const userWithRoles = await strapi2.query("admin::user").findOne({
53
+ where: { id: result.id },
54
+ populate: ["roles"]
55
+ });
56
+ if (userWithRoles?.roles) {
57
+ const roleIds = userWithRoles.roles.map((r) => r.id.toString());
58
+ await query.update({
59
+ where: { id: whitelistEntry.id },
60
+ data: { roles: roleIds }
61
+ });
62
+ }
63
+ }
64
+ });
65
+ }
66
+ function destroy() {
67
+ }
68
+ const config = {
69
+ default: {
70
+ REMEMBER_ME: false,
71
+ OIDC_REDIRECT_URI: "http://localhost:1337/strapi-plugin-oidc/oidc/callback",
72
+ OIDC_CLIENT_ID: "",
73
+ OIDC_CLIENT_SECRET: "",
74
+ OIDC_SCOPES: "openid profile email",
75
+ OIDC_AUTHORIZATION_ENDPOINT: "",
76
+ OIDC_TOKEN_ENDPOINT: "",
77
+ OIDC_USER_INFO_ENDPOINT: "",
78
+ OIDC_USER_INFO_ENDPOINT_WITH_AUTH_HEADER: false,
79
+ OIDC_GRANT_TYPE: "authorization_code",
80
+ OIDC_FAMILY_NAME_FIELD: "family_name",
81
+ OIDC_GIVEN_NAME_FIELD: "given_name",
82
+ OIDC_LOGOUT_URL: ""
83
+ },
84
+ validator() {
85
+ }
86
+ };
87
+ const info$2 = { "singularName": "roles", "pluralName": "oidc-roles", "collectionName": "oidc-roles", "displayName": "oidc-role", "description": "" };
88
+ const options$1 = { "draftAndPublish": false };
89
+ const pluginOptions$1 = { "content-manager": { "visible": false }, "content-type-builder": { "visible": false } };
90
+ const attributes$1 = { "oauth_type": { "type": "string", "configurable": false, "required": true }, "roles": { "type": "json", "configurable": false } };
91
+ const schema$1 = {
92
+ info: info$2,
93
+ options: options$1,
94
+ pluginOptions: pluginOptions$1,
95
+ attributes: attributes$1
96
+ };
97
+ const roles = {
98
+ schema: schema$1
99
+ };
100
+ const info$1 = { "singularName": "whitelists", "pluralName": "whitelists", "collectionName": "whitelists", "displayName": "whitelist", "description": "" };
101
+ const options = { "draftAndPublish": false };
102
+ const pluginOptions = { "content-manager": { "visible": false }, "content-type-builder": { "visible": false } };
103
+ const attributes = { "email": { "type": "string", "configurable": false, "required": true, "unique": true }, "roles": { "type": "json", "configurable": false } };
104
+ const schema = {
105
+ info: info$1,
106
+ options,
107
+ pluginOptions,
108
+ attributes
109
+ };
110
+ const whitelists = {
111
+ schema
112
+ };
113
+ const contentTypes = {
114
+ roles,
115
+ whitelists
116
+ };
117
+ function configValidation() {
118
+ const config2 = strapi.config.get("plugin::strapi-plugin-oidc");
119
+ if (config2["OIDC_CLIENT_ID"] && config2["OIDC_CLIENT_SECRET"] && config2["OIDC_REDIRECT_URI"] && config2["OIDC_SCOPES"] && config2["OIDC_TOKEN_ENDPOINT"] && config2["OIDC_USER_INFO_ENDPOINT"] && config2["OIDC_GRANT_TYPE"] && config2["OIDC_FAMILY_NAME_FIELD"] && config2["OIDC_GIVEN_NAME_FIELD"] && config2["OIDC_AUTHORIZATION_ENDPOINT"]) {
120
+ return config2;
121
+ }
122
+ throw new Error("OIDC_AUTHORIZATION_ENDPOINT,OIDC_TOKEN_ENDPOINT, OIDC_USER_INFO_ENDPOINT,OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_REDIRECT_URI, and OIDC_SCOPES are required");
123
+ }
124
+ async function oidcSignIn(ctx) {
125
+ let { state } = ctx.query;
126
+ const { OIDC_CLIENT_ID, OIDC_REDIRECT_URI, OIDC_SCOPES, OIDC_AUTHORIZATION_ENDPOINT } = configValidation();
127
+ const { code_verifier: codeVerifier, code_challenge: codeChallenge } = await pkceChallenge();
128
+ ctx.session.codeVerifier = codeVerifier;
129
+ if (!state) {
130
+ state = randomBytes(32).toString("base64url");
131
+ }
132
+ ctx.session.oidcState = state;
133
+ const params = new URLSearchParams();
134
+ params.append("response_type", "code");
135
+ params.append("client_id", OIDC_CLIENT_ID);
136
+ params.append("redirect_uri", OIDC_REDIRECT_URI);
137
+ params.append("scope", OIDC_SCOPES);
138
+ params.append("code_challenge", codeChallenge);
139
+ params.append("code_challenge_method", "S256");
140
+ params.append("state", state);
141
+ const authorizationUrl = `${OIDC_AUTHORIZATION_ENDPOINT}?${params.toString()}`;
142
+ ctx.set("Location", authorizationUrl);
143
+ return ctx.send({}, 302);
144
+ }
145
+ async function oidcSignInCallback(ctx) {
146
+ const config2 = configValidation();
147
+ const httpClient = axios.create();
148
+ const userService = strapi.service("admin::user");
149
+ const oauthService2 = strapi.plugin("strapi-plugin-oidc").service("oauth");
150
+ const roleService2 = strapi.plugin("strapi-plugin-oidc").service("role");
151
+ const whitelistService2 = strapi.plugin("strapi-plugin-oidc").service("whitelist");
152
+ if (!ctx.query.code) {
153
+ return ctx.send(oauthService2.renderSignUpError(`code Not Found`));
154
+ }
155
+ if (!ctx.query.state || ctx.query.state !== ctx.session.oidcState) {
156
+ return ctx.send(oauthService2.renderSignUpError(`Invalid state`));
157
+ }
158
+ const params = new URLSearchParams();
159
+ params.append("code", ctx.query.code);
160
+ params.append("client_id", config2["OIDC_CLIENT_ID"]);
161
+ params.append("client_secret", config2["OIDC_CLIENT_SECRET"]);
162
+ params.append("redirect_uri", config2["OIDC_REDIRECT_URI"]);
163
+ params.append("grant_type", config2["OIDC_GRANT_TYPE"]);
164
+ params.append("code_verifier", ctx.session.codeVerifier);
165
+ try {
166
+ const response = await httpClient.post(config2["OIDC_TOKEN_ENDPOINT"], params, {
167
+ headers: {
168
+ "Content-Type": "application/x-www-form-urlencoded"
169
+ }
170
+ });
171
+ let userInfoEndpointHeaders = {};
172
+ let userInfoEndpointParameters = `?access_token=${response.data.access_token}`;
173
+ if (config2["OIDC_USER_INFO_ENDPOINT_WITH_AUTH_HEADER"]) {
174
+ userInfoEndpointHeaders = {
175
+ headers: { Authorization: `Bearer ${response.data.access_token}` }
176
+ };
177
+ userInfoEndpointParameters = "";
178
+ }
179
+ const userInfoEndpoint = `${config2["OIDC_USER_INFO_ENDPOINT"]}${userInfoEndpointParameters}`;
180
+ const userResponse = await httpClient.get(
181
+ userInfoEndpoint,
182
+ userInfoEndpointHeaders
183
+ );
184
+ const email = userResponse.data.email;
185
+ const whitelistUser = await whitelistService2.checkWhitelistForEmail(email);
186
+ const dbUser = await userService.findOneByEmail(email);
187
+ let activateUser;
188
+ let jwtToken;
189
+ if (dbUser) {
190
+ activateUser = dbUser;
191
+ jwtToken = await oauthService2.generateToken(dbUser, ctx);
192
+ } else {
193
+ let roles2 = [];
194
+ if (whitelistUser && whitelistUser.roles && whitelistUser.roles.length > 0) {
195
+ roles2 = whitelistUser.roles;
196
+ } else {
197
+ const oidcRoles = await roleService2.oidcRoles();
198
+ roles2 = oidcRoles && oidcRoles["roles"] ? oidcRoles["roles"] : [];
199
+ }
200
+ const defaultLocale = oauthService2.localeFindByHeader(ctx.request.headers);
201
+ activateUser = await oauthService2.createUser(
202
+ email,
203
+ userResponse.data[config2["OIDC_FAMILY_NAME_FIELD"]],
204
+ userResponse.data[config2["OIDC_GIVEN_NAME_FIELD"]],
205
+ defaultLocale,
206
+ roles2
207
+ );
208
+ jwtToken = await oauthService2.generateToken(activateUser, ctx);
209
+ await oauthService2.triggerWebHook(activateUser);
210
+ }
211
+ oauthService2.triggerSignInSuccess(activateUser);
212
+ const nonce = randomUUID();
213
+ const html = oauthService2.renderSignUpSuccess(jwtToken, activateUser, nonce);
214
+ ctx.set("Content-Security-Policy", `script-src 'nonce-${nonce}'`);
215
+ ctx.send(html);
216
+ } catch (e) {
217
+ console.error(e);
218
+ ctx.send(oauthService2.renderSignUpError(e.message));
219
+ }
220
+ }
221
+ async function logout(ctx) {
222
+ const config2 = strapi.config.get("plugin::strapi-plugin-oidc");
223
+ const logoutUrl = config2["OIDC_LOGOUT_URL"];
224
+ if (logoutUrl) {
225
+ ctx.redirect(logoutUrl);
226
+ } else {
227
+ const adminPanelUrl = strapi.config.get("admin.url", "/admin");
228
+ ctx.redirect(`${adminPanelUrl}/auth/login`);
229
+ }
230
+ }
231
+ const oidc = {
232
+ oidcSignIn,
233
+ oidcSignInCallback,
234
+ logout
235
+ };
236
+ async function find(ctx) {
237
+ const roleService2 = strapi.plugin("strapi-plugin-oidc").service("role");
238
+ const roles2 = await roleService2.find();
239
+ const oidcConstants = roleService2.getOidcRoles();
240
+ for (const oidc2 of oidcConstants) {
241
+ for (const role2 of roles2) {
242
+ if (role2["oauth_type"] === oidc2["oauth_type"]) {
243
+ oidc2["role"] = role2["roles"];
244
+ }
245
+ }
246
+ }
247
+ ctx.send(oidcConstants);
248
+ }
249
+ async function update(ctx) {
250
+ try {
251
+ const { roles: roles2 } = ctx.request.body;
252
+ const roleService2 = strapi.plugin("strapi-plugin-oidc").service("role");
253
+ await roleService2.update(roles2);
254
+ ctx.send({}, 204);
255
+ } catch (e) {
256
+ console.log(e);
257
+ ctx.send({}, 400);
258
+ }
259
+ }
260
+ const role = {
261
+ find,
262
+ update
263
+ };
264
+ async function info(ctx) {
265
+ const whitelistService2 = strapi.plugin("strapi-plugin-oidc").service("whitelist");
266
+ const settings = await whitelistService2.getSettings();
267
+ const whitelistUsers = await whitelistService2.getUsers();
268
+ ctx.body = {
269
+ useWhitelist: settings.useWhitelist,
270
+ enforceOIDC: settings.enforceOIDC || false,
271
+ whitelistUsers
272
+ };
273
+ }
274
+ async function updateSettings(ctx) {
275
+ const { useWhitelist, enforceOIDC } = ctx.request.body;
276
+ const whitelistService2 = strapi.plugin("strapi-plugin-oidc").service("whitelist");
277
+ await whitelistService2.setSettings({ useWhitelist, enforceOIDC });
278
+ ctx.body = { useWhitelist, enforceOIDC };
279
+ }
280
+ async function publicSettings(ctx) {
281
+ const whitelistService2 = strapi.plugin("strapi-plugin-oidc").service("whitelist");
282
+ const settings = await whitelistService2.getSettings();
283
+ ctx.body = {
284
+ enforceOIDC: settings.enforceOIDC || false
285
+ };
286
+ }
287
+ async function register(ctx) {
288
+ const { email, roles: roles2 } = ctx.request.body;
289
+ if (!email) {
290
+ ctx.body = {
291
+ message: "Please enter a valid email address"
292
+ };
293
+ return;
294
+ }
295
+ const emailList = Array.isArray(email) ? email : email.split(",").map((e) => e.trim()).filter((e) => e);
296
+ const existingUsers = await strapi.query("admin::user").findMany({
297
+ where: { email: { $in: emailList } },
298
+ populate: ["roles"]
299
+ });
300
+ const whitelistService2 = strapi.plugin("strapi-plugin-oidc").service("whitelist");
301
+ let matchedExistingUsersCount = 0;
302
+ for (const singleEmail of emailList) {
303
+ const existingUser = existingUsers.find((u) => u.email === singleEmail);
304
+ let finalRoles = roles2;
305
+ if (existingUser && existingUser.roles) {
306
+ finalRoles = existingUser.roles.map((r) => r.id.toString());
307
+ matchedExistingUsersCount++;
308
+ }
309
+ const alreadyWhitelisted = await strapi.query("plugin::strapi-plugin-oidc.whitelists").findOne({
310
+ where: { email: singleEmail }
311
+ });
312
+ if (!alreadyWhitelisted) {
313
+ await whitelistService2.registerUser(singleEmail, finalRoles);
314
+ }
315
+ }
316
+ ctx.body = { matchedExistingUsersCount };
317
+ }
318
+ async function removeEmail(ctx) {
319
+ const { id } = ctx.params;
320
+ const whitelistService2 = strapi.plugin("strapi-plugin-oidc").service("whitelist");
321
+ await whitelistService2.removeUser(id);
322
+ ctx.body = {};
323
+ }
324
+ async function syncUsers(ctx) {
325
+ const { users } = ctx.request.body;
326
+ const whitelistService2 = strapi.plugin("strapi-plugin-oidc").service("whitelist");
327
+ const currentUsers = await whitelistService2.getUsers();
328
+ let matchedExistingUsersCount = 0;
329
+ const emailsToSync = users.map((u) => u.email);
330
+ const existingStrapiUsers = await strapi.query("admin::user").findMany({
331
+ where: { email: { $in: emailsToSync } },
332
+ populate: ["roles"]
333
+ });
334
+ for (const currUser of currentUsers) {
335
+ if (!users.find((u) => u.email === currUser.email)) {
336
+ await whitelistService2.removeUser(currUser.id);
337
+ }
338
+ }
339
+ for (const user of users) {
340
+ const existingStrapiUser = existingStrapiUsers.find((u) => u.email === user.email);
341
+ let finalRoles = user.roles;
342
+ const currUser = currentUsers.find((u) => u.email === user.email);
343
+ if (!currUser && existingStrapiUser && existingStrapiUser.roles) {
344
+ finalRoles = existingStrapiUser.roles.map((r) => r.id.toString());
345
+ matchedExistingUsersCount++;
346
+ }
347
+ if (currUser) {
348
+ await strapi.query("plugin::strapi-plugin-oidc.whitelists").update({
349
+ where: { id: currUser.id },
350
+ data: { roles: finalRoles }
351
+ });
352
+ } else {
353
+ await whitelistService2.registerUser(user.email, finalRoles);
354
+ }
355
+ }
356
+ ctx.body = { matchedExistingUsersCount };
357
+ }
358
+ const whitelist = {
359
+ info,
360
+ updateSettings,
361
+ publicSettings,
362
+ register,
363
+ removeEmail,
364
+ syncUsers
365
+ };
366
+ const controllers = {
367
+ oidc,
368
+ role,
369
+ whitelist
370
+ };
371
+ const routes = [
372
+ {
373
+ method: "GET",
374
+ path: "/oidc-roles",
375
+ handler: "role.find",
376
+ config: {
377
+ policies: [
378
+ "admin::isAuthenticatedAdmin",
379
+ { name: "admin::hasPermissions", config: { actions: ["plugin::strapi-plugin-oidc.read"] } }
380
+ ]
381
+ }
382
+ },
383
+ {
384
+ method: "PUT",
385
+ path: "/oidc-roles",
386
+ handler: "role.update",
387
+ config: {
388
+ policies: [
389
+ "admin::isAuthenticatedAdmin",
390
+ { name: "admin::hasPermissions", config: { actions: ["plugin::strapi-plugin-oidc.update"] } }
391
+ ]
392
+ }
393
+ },
394
+ {
395
+ method: "GET",
396
+ path: "/oidc",
397
+ handler: "oidc.oidcSignIn",
398
+ config: {
399
+ auth: false
400
+ }
401
+ },
402
+ {
403
+ method: "GET",
404
+ path: "/oidc/callback",
405
+ handler: "oidc.oidcSignInCallback",
406
+ config: {
407
+ auth: false
408
+ }
409
+ },
410
+ {
411
+ method: "GET",
412
+ path: "/logout",
413
+ handler: "oidc.logout",
414
+ config: {
415
+ auth: false
416
+ }
417
+ },
418
+ {
419
+ method: "GET",
420
+ path: "/whitelist",
421
+ handler: "whitelist.info",
422
+ config: {
423
+ policies: [
424
+ "admin::isAuthenticatedAdmin",
425
+ { name: "admin::hasPermissions", config: { actions: ["plugin::strapi-plugin-oidc.read"] } }
426
+ ]
427
+ }
428
+ },
429
+ {
430
+ method: "PUT",
431
+ path: "/whitelist/settings",
432
+ handler: "whitelist.updateSettings",
433
+ config: {
434
+ policies: [
435
+ "admin::isAuthenticatedAdmin",
436
+ { name: "admin::hasPermissions", config: { actions: ["plugin::strapi-plugin-oidc.update"] } }
437
+ ]
438
+ }
439
+ },
440
+ {
441
+ method: "GET",
442
+ path: "/settings/public",
443
+ handler: "whitelist.publicSettings",
444
+ config: {
445
+ auth: false
446
+ }
447
+ },
448
+ {
449
+ method: "PUT",
450
+ path: "/whitelist/sync",
451
+ handler: "whitelist.syncUsers",
452
+ config: {
453
+ policies: [
454
+ "admin::isAuthenticatedAdmin",
455
+ { name: "admin::hasPermissions", config: { actions: ["plugin::strapi-plugin-oidc.update"] } }
456
+ ]
457
+ }
458
+ },
459
+ {
460
+ method: "POST",
461
+ path: "/whitelist",
462
+ handler: "whitelist.register",
463
+ config: {
464
+ policies: [
465
+ "admin::isAuthenticatedAdmin",
466
+ { name: "admin::hasPermissions", config: { actions: ["plugin::strapi-plugin-oidc.update"] } }
467
+ ]
468
+ }
469
+ },
470
+ {
471
+ method: "DELETE",
472
+ path: "/whitelist/:id",
473
+ handler: "whitelist.removeEmail",
474
+ config: {
475
+ policies: [
476
+ "admin::isAuthenticatedAdmin",
477
+ { name: "admin::hasPermissions", config: { actions: ["plugin::strapi-plugin-oidc.update"] } }
478
+ ]
479
+ }
480
+ }
481
+ ];
482
+ const policies = {};
483
+ function oauthService({ strapi: strapi2 }) {
484
+ return {
485
+ async createUser(email, lastname, firstname, locale, roles2 = []) {
486
+ const userService = strapi2.service("admin::user");
487
+ if (/[A-Z]/.test(email)) {
488
+ const dbUser = await userService.findOneByEmail(email.toLocaleLowerCase());
489
+ if (dbUser) {
490
+ return dbUser;
491
+ }
492
+ }
493
+ const createdUser = await userService.create({
494
+ firstname: firstname ? firstname : "unset",
495
+ lastname: lastname ? lastname : "",
496
+ email: email.toLocaleLowerCase(),
497
+ roles: roles2,
498
+ preferedLanguage: locale
499
+ });
500
+ return await userService.register({
501
+ registrationToken: createdUser.registrationToken,
502
+ userInfo: {
503
+ firstname: firstname ? firstname : "unset",
504
+ lastname: lastname ? lastname : "user",
505
+ password: generator.generate({
506
+ length: 43,
507
+ // 256 bits (https://en.wikipedia.org/wiki/Password_strength#Random_passwords)
508
+ numbers: true,
509
+ lowercase: true,
510
+ uppercase: true,
511
+ exclude: '()+_-=}{[]|:;"/?.><,`~',
512
+ strict: true
513
+ })
514
+ }
515
+ });
516
+ },
517
+ addGmailAlias(baseEmail, baseAlias) {
518
+ if (!baseAlias) {
519
+ return baseEmail;
520
+ }
521
+ const alias = baseAlias.replace("/+/g", "");
522
+ const beforePosition = baseEmail.indexOf("@");
523
+ const origin = baseEmail.substring(0, beforePosition);
524
+ const domain = baseEmail.substring(beforePosition);
525
+ return `${origin}+${alias}${domain}`;
526
+ },
527
+ localeFindByHeader(headers) {
528
+ if (headers["accept-language"] && headers["accept-language"].includes("ja")) {
529
+ return "ja";
530
+ } else {
531
+ return "en";
532
+ }
533
+ },
534
+ async triggerWebHook(user) {
535
+ let ENTRY_CREATE;
536
+ const webhookStore = strapi2.serviceMap.get("webhookStore");
537
+ const eventHub = strapi2.serviceMap.get("eventHub");
538
+ if (webhookStore) {
539
+ ENTRY_CREATE = webhookStore.allowedEvents.get("ENTRY_CREATE");
540
+ }
541
+ const modelDef = strapi2.getModel("admin::user");
542
+ const sanitizedEntity = await strapiUtils.sanitize.sanitizers.defaultSanitizeOutput({
543
+ schema: modelDef,
544
+ getModel: (uid2) => strapi2.getModel(uid2)
545
+ }, user);
546
+ eventHub.emit(ENTRY_CREATE, {
547
+ model: modelDef.modelName,
548
+ entry: sanitizedEntity
549
+ });
550
+ },
551
+ triggerSignInSuccess(user) {
552
+ delete user["password"];
553
+ const eventHub = strapi2.serviceMap.get("eventHub");
554
+ eventHub.emit("admin.auth.success", {
555
+ user,
556
+ provider: "strapi-plugin-oidc"
557
+ });
558
+ },
559
+ // Sign In Success
560
+ renderSignUpSuccess(jwtToken, user, nonce) {
561
+ const config2 = strapi2.config.get("plugin::strapi-plugin-oidc");
562
+ const REMEMBER_ME = config2["REMEMBER_ME"];
563
+ const isRememberMe = !!REMEMBER_ME;
564
+ return `
565
+ <!doctype html>
566
+ <html>
567
+ <head>
568
+ <noscript>
569
+ <h3>JavaScript must be enabled for authentication</h3>
570
+ </noscript>
571
+ <script nonce="${nonce}">
572
+ window.addEventListener('load', function() {
573
+ if(${isRememberMe}){
574
+ localStorage.setItem('jwtToken', '"${jwtToken}"');
575
+ }else{
576
+ document.cookie = 'jwtToken=${encodeURIComponent(jwtToken)}; Path=/';
577
+ }
578
+ localStorage.setItem('isLoggedIn', 'true');
579
+ location.href = '${strapi2.config.admin.url}'
580
+ })
581
+ <\/script>
582
+ </head>
583
+ <body>
584
+ </body>
585
+ </html>`;
586
+ },
587
+ // Sign In Error
588
+ renderSignUpError(message) {
589
+ return `
590
+ <!doctype html>
591
+ <html>
592
+ <head></head>
593
+ <body>
594
+ <h3>Authentication failed</h3>
595
+ <p>${message}</p>
596
+ </body>
597
+ </html>`;
598
+ },
599
+ async generateToken(user, ctx) {
600
+ const sessionManager = strapi2.sessionManager;
601
+ if (!sessionManager) {
602
+ throw new Error("sessionManager is not supported. Please upgrade to Strapi v5.24.1 or later.");
603
+ }
604
+ const userId = String(user.id);
605
+ const deviceId = randomUUID();
606
+ const config2 = strapi2.config.get("plugin::strapi-plugin-oidc");
607
+ const REMEMBER_ME = config2["REMEMBER_ME"];
608
+ const rememberMe = !!REMEMBER_ME;
609
+ const { token: refreshToken } = await sessionManager(
610
+ "admin"
611
+ ).generateRefreshToken(userId, deviceId, {
612
+ type: rememberMe ? "refresh" : "session"
613
+ });
614
+ const cookieOptions = {};
615
+ ctx.cookies.set("strapi_admin_refresh", refreshToken, cookieOptions);
616
+ const accessResult = await sessionManager("admin").generateAccessToken(refreshToken);
617
+ if ("error" in accessResult) {
618
+ throw new Error(accessResult.error);
619
+ }
620
+ const { token: accessToken } = accessResult;
621
+ return accessToken;
622
+ }
623
+ };
624
+ }
625
+ function roleService({ strapi: strapi2 }) {
626
+ return {
627
+ OIDC_TYPE: "4",
628
+ getOidcRoles() {
629
+ return [
630
+ {
631
+ "oauth_type": this.OIDC_TYPE,
632
+ name: "OIDC"
633
+ }
634
+ ];
635
+ },
636
+ async oidcRoles() {
637
+ return await strapi2.query("plugin::strapi-plugin-oidc.roles").findOne({
638
+ where: {
639
+ "oauth_type": this.OIDC_TYPE
640
+ }
641
+ });
642
+ },
643
+ async find() {
644
+ return await strapi2.query("plugin::strapi-plugin-oidc.roles").findMany();
645
+ },
646
+ async update(roles2) {
647
+ const query = strapi2.query("plugin::strapi-plugin-oidc.roles");
648
+ await Promise.all(
649
+ roles2.map(async (role2) => {
650
+ const oidcRole = await query.findOne({ where: { "oauth_type": role2["oauth_type"] } });
651
+ if (oidcRole) {
652
+ await query.update({
653
+ where: { "oauth_type": role2["oauth_type"] },
654
+ data: { roles: role2.role }
655
+ });
656
+ } else {
657
+ await query.create({
658
+ data: {
659
+ "oauth_type": role2["oauth_type"],
660
+ roles: role2.role
661
+ }
662
+ });
663
+ }
664
+ })
665
+ );
666
+ }
667
+ };
668
+ }
669
+ function whitelistService({ strapi: strapi2 }) {
670
+ return {
671
+ async getSettings() {
672
+ const pluginStore = strapi2.store({ type: "plugin", name: "strapi-plugin-oidc" });
673
+ let settings = await pluginStore.get({ key: "settings" });
674
+ if (!settings) {
675
+ settings = { useWhitelist: true, enforceOIDC: false };
676
+ await pluginStore.set({ key: "settings", value: settings });
677
+ }
678
+ return settings;
679
+ },
680
+ async setSettings(settings) {
681
+ const pluginStore = strapi2.store({ type: "plugin", name: "strapi-plugin-oidc" });
682
+ await pluginStore.set({ key: "settings", value: settings });
683
+ },
684
+ async getUsers() {
685
+ const query = strapi2.query("plugin::strapi-plugin-oidc.whitelists");
686
+ return await query.findMany();
687
+ },
688
+ async registerUser(email, roles2) {
689
+ const query = strapi2.query("plugin::strapi-plugin-oidc.whitelists");
690
+ await query.create({
691
+ data: {
692
+ email,
693
+ roles: roles2
694
+ }
695
+ });
696
+ },
697
+ async removeUser(id) {
698
+ const query = strapi2.query("plugin::strapi-plugin-oidc.whitelists");
699
+ await query.delete({
700
+ where: {
701
+ id
702
+ }
703
+ });
704
+ },
705
+ async checkWhitelistForEmail(email) {
706
+ const settings = await this.getSettings();
707
+ if (!settings.useWhitelist) {
708
+ return null;
709
+ }
710
+ const query = strapi2.query("plugin::strapi-plugin-oidc.whitelists");
711
+ const result = await query.findOne({
712
+ where: {
713
+ email
714
+ }
715
+ });
716
+ if (result === null) {
717
+ throw new Error("Not present in whitelist");
718
+ }
719
+ return result;
720
+ }
721
+ };
722
+ }
723
+ const services = {
724
+ oauth: oauthService,
725
+ role: roleService,
726
+ whitelist: whitelistService
727
+ };
728
+ const index = {
729
+ register: register$1,
730
+ bootstrap,
731
+ destroy,
732
+ config,
733
+ controllers,
734
+ routes,
735
+ services,
736
+ contentTypes,
737
+ policies
738
+ };
739
+ export {
740
+ index as default
741
+ };