@builder6/oidc-provider 0.15.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.
package/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # Builder6 OIDC Provider
2
+
3
+
4
+ ## Environment Variables
5
+
6
+ ```shell
7
+ B6_OIDC_PROVIDER_CLIENT_ID=test
8
+ B6_OIDC_PROVIDER_CLIENT_SECRET=secret
9
+ B6_OIDC_PROVIDER_REDIRECT_URIS=http://localhost:5100
10
+ ```
11
+
12
+ ## OpenID Configuration URI
13
+
14
+ ```shell
15
+ http://localhost:5100/api/v6/idp/common/.well-known/openid-configuration
16
+ ```
17
+
18
+ ## Debug OIDC Provider
19
+
20
+ https://oidcdebugger.com/
21
+
22
+ Auth URL: http://localhost:5100/api/v6/idp/common/auth
23
+
24
+ with environment variables:
25
+
26
+ ```shell
27
+ B6_OIDC_PROVIDER_CLIENT_ID=test
28
+ B6_OIDC_PROVIDER_CLIENT_SECRET=secret
29
+ B6_OIDC_PROVIDER_REDIRECT_URIS=https://oidcdebugger.com/debug
30
+ ```
@@ -0,0 +1,2 @@
1
+ export * from './oidc-provider/oidc-provider.module';
2
+ export * from './oidc-provider/oidc-provider.service';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./oidc-provider/oidc-provider.module"), exports);
18
+ __exportStar(require("./oidc-provider/oidc-provider.service"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,uEAAqD;AACrD,wEAAsD"}
@@ -0,0 +1,14 @@
1
+ import { Request, Response } from 'express';
2
+ import { OidcProviderService } from './oidc-provider.service';
3
+ import { AuthService } from '@builder6/core';
4
+ export declare class OidcProviderController {
5
+ private readonly oidcService;
6
+ private readonly authService;
7
+ private engine;
8
+ constructor(oidcService: OidcProviderService, authService: AuthService);
9
+ showInteraction(uid: string, req: Request, res: Response): Promise<Response<any, Record<string, any>>>;
10
+ loginSubmit(uid: string, username: string, password: string, req: Request, res: Response): Promise<any>;
11
+ consentSubmit(uid: string, grantDecision: string, req: Request, res: Response): Promise<any>;
12
+ consentSubmitAbort(uid: string, grantDecision: string, req: Request, res: Response): Promise<void>;
13
+ mountedOidc(req: Request, res: Response): void;
14
+ }
@@ -0,0 +1,213 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.OidcProviderController = void 0;
19
+ const common_1 = require("@nestjs/common");
20
+ const oidc_provider_service_1 = require("./oidc-provider.service");
21
+ const node_assert_1 = require("node:assert");
22
+ const core_1 = require("@builder6/core");
23
+ const liquidjs_1 = require("liquidjs");
24
+ const path_1 = __importDefault(require("path"));
25
+ let OidcProviderController = class OidcProviderController {
26
+ constructor(oidcService, authService) {
27
+ this.oidcService = oidcService;
28
+ this.authService = authService;
29
+ this.engine = new liquidjs_1.Liquid({
30
+ root: path_1.default.resolve(__dirname, '../../views'),
31
+ extname: '.liquid',
32
+ });
33
+ }
34
+ async showInteraction(uid, req, res) {
35
+ const interaction = await this.oidcService.provider.interactionDetails(req, res);
36
+ const { prompt, params } = interaction;
37
+ if (prompt.name === 'login') {
38
+ const data = { uid, params };
39
+ const rendered = await this.engine.renderFile('login', data);
40
+ res.status(200).send(rendered);
41
+ }
42
+ else if (prompt.name === 'consent') {
43
+ return res.send(`
44
+ <html>
45
+ <body>
46
+ <h1>授权请求</h1>
47
+ <p>客户端 <strong>${params.client_id}</strong> 正在请求访问您的资源:</p>
48
+ <p><strong>请求的范围(scope)</strong>: ${params.scope || '(无)'}</p>
49
+ <p>是否授权该客户端访问上述权限?</p>
50
+ <form method="POST" action="/api/v6/idp/common/interaction/${uid}/confirm">
51
+ <button name="grant" value="yes" type="submit">同意</button>
52
+ </form>
53
+ <form method="POST" action="/api/v6/idp/common/interaction/${uid}/abort">
54
+ <button name="grant" value="no" type="submit">拒绝</button>
55
+ </form>
56
+ </body>
57
+ </html>
58
+ `);
59
+ }
60
+ else {
61
+ return res.status(400).send('未知的交互请求');
62
+ }
63
+ }
64
+ async loginSubmit(uid, username, password, req, res) {
65
+ const accountId = await this.oidcService.validateUser(username, password);
66
+ if (!accountId) {
67
+ return res.redirect(`/api/v6/idp/common/interaction/${uid}`);
68
+ }
69
+ const interactionDetails = await this.oidcService.provider.interactionDetails(req, res);
70
+ const { params } = interactionDetails;
71
+ const grant = new this.oidcService.provider.Grant({
72
+ accountId,
73
+ clientId: params.client_id,
74
+ });
75
+ grant.addOIDCScope('openid email profile');
76
+ const grantId = await grant.save();
77
+ const result = {
78
+ login: { accountId },
79
+ consent: {
80
+ grantId,
81
+ },
82
+ };
83
+ return this.oidcService.provider.interactionFinished(req, res, result, {
84
+ mergeWithLastSubmission: false,
85
+ });
86
+ }
87
+ async consentSubmit(uid, grantDecision, req, res) {
88
+ try {
89
+ const interactionDetails = await this.oidcService.provider.interactionDetails(req, res);
90
+ const { prompt: { name, details }, params, session: { accountId }, } = interactionDetails;
91
+ node_assert_1.strict.equal(name, 'consent');
92
+ let { grantId } = interactionDetails;
93
+ let grant;
94
+ if (grantId) {
95
+ grant = await this.oidcService.provider.Grant.find(grantId);
96
+ }
97
+ else {
98
+ grant = new this.oidcService.provider.Grant({
99
+ accountId,
100
+ clientId: params.client_id,
101
+ });
102
+ }
103
+ if (details.missingOIDCScope) {
104
+ grant.addOIDCScope(details.missingOIDCScope.join(' '));
105
+ }
106
+ if (details.missingOIDCClaims) {
107
+ grant.addOIDCClaims(details.missingOIDCClaims);
108
+ }
109
+ if (details.missingResourceScopes) {
110
+ for (const [indicator, scopes] of Object.entries(details.missingResourceScopes)) {
111
+ grant.addResourceScope(indicator, scopes.join(' '));
112
+ }
113
+ }
114
+ grantId = await grant.save();
115
+ const consent = {};
116
+ if (!interactionDetails.grantId) {
117
+ consent.grantId = grantId;
118
+ }
119
+ const result = { consent };
120
+ return await this.oidcService.provider.interactionFinished(req, res, result, {
121
+ mergeWithLastSubmission: true,
122
+ });
123
+ }
124
+ catch (err) {
125
+ console.error(err);
126
+ res.status(500).send('OIDC Server Error');
127
+ }
128
+ }
129
+ async consentSubmitAbort(uid, grantDecision, req, res) {
130
+ try {
131
+ const result = {
132
+ error: 'access_denied',
133
+ error_description: 'End-User aborted interaction',
134
+ };
135
+ await this.oidcService.provider.interactionFinished(req, res, result, {
136
+ mergeWithLastSubmission: false,
137
+ });
138
+ }
139
+ catch (err) {
140
+ console.error(err);
141
+ res.status(500).send('OIDC Server Error');
142
+ }
143
+ }
144
+ mountedOidc(req, res) {
145
+ req.url = req.originalUrl.replace('/api/v6/idp/common', '');
146
+ const callback = this.oidcService.getCallback();
147
+ if (!callback) {
148
+ res.status(404).send('Not Found');
149
+ }
150
+ try {
151
+ this.oidcService.getCallback()(req, res);
152
+ }
153
+ catch (err) {
154
+ console.error(err);
155
+ res.status(500).send('OIDC Server Error');
156
+ }
157
+ }
158
+ };
159
+ exports.OidcProviderController = OidcProviderController;
160
+ __decorate([
161
+ (0, common_1.Get)('interaction/:uid'),
162
+ __param(0, (0, common_1.Param)('uid')),
163
+ __param(1, (0, common_1.Req)()),
164
+ __param(2, (0, common_1.Res)()),
165
+ __metadata("design:type", Function),
166
+ __metadata("design:paramtypes", [String, Object, Object]),
167
+ __metadata("design:returntype", Promise)
168
+ ], OidcProviderController.prototype, "showInteraction", null);
169
+ __decorate([
170
+ (0, common_1.Post)('interaction/:uid/login'),
171
+ __param(0, (0, common_1.Param)('uid')),
172
+ __param(1, (0, common_1.Body)('username')),
173
+ __param(2, (0, common_1.Body)('password')),
174
+ __param(3, (0, common_1.Req)()),
175
+ __param(4, (0, common_1.Res)()),
176
+ __metadata("design:type", Function),
177
+ __metadata("design:paramtypes", [String, String, String, Object, Object]),
178
+ __metadata("design:returntype", Promise)
179
+ ], OidcProviderController.prototype, "loginSubmit", null);
180
+ __decorate([
181
+ (0, common_1.Post)('interaction/:uid/confirm'),
182
+ __param(0, (0, common_1.Param)('uid')),
183
+ __param(1, (0, common_1.Body)('grant')),
184
+ __param(2, (0, common_1.Req)()),
185
+ __param(3, (0, common_1.Res)()),
186
+ __metadata("design:type", Function),
187
+ __metadata("design:paramtypes", [String, String, Object, Object]),
188
+ __metadata("design:returntype", Promise)
189
+ ], OidcProviderController.prototype, "consentSubmit", null);
190
+ __decorate([
191
+ (0, common_1.Post)('interaction/:uid/abort'),
192
+ __param(0, (0, common_1.Param)('uid')),
193
+ __param(1, (0, common_1.Body)('grant')),
194
+ __param(2, (0, common_1.Req)()),
195
+ __param(3, (0, common_1.Res)()),
196
+ __metadata("design:type", Function),
197
+ __metadata("design:paramtypes", [String, String, Object, Object]),
198
+ __metadata("design:returntype", Promise)
199
+ ], OidcProviderController.prototype, "consentSubmitAbort", null);
200
+ __decorate([
201
+ (0, common_1.All)('/*idp'),
202
+ __param(0, (0, common_1.Req)()),
203
+ __param(1, (0, common_1.Res)()),
204
+ __metadata("design:type", Function),
205
+ __metadata("design:paramtypes", [Object, Object]),
206
+ __metadata("design:returntype", void 0)
207
+ ], OidcProviderController.prototype, "mountedOidc", null);
208
+ exports.OidcProviderController = OidcProviderController = __decorate([
209
+ (0, common_1.Controller)('api/v6/idp/common'),
210
+ __metadata("design:paramtypes", [oidc_provider_service_1.OidcProviderService,
211
+ core_1.AuthService])
212
+ ], OidcProviderController);
213
+ //# sourceMappingURL=oidc-provider.controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-provider.controller.js","sourceRoot":"","sources":["../../src/oidc-provider/oidc-provider.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CASwB;AAExB,mEAA8D;AAC9D,6CAA+C;AAC/C,yCAA6C;AAC7C,uCAAkC;AAClC,gDAAwB;AAGjB,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IAGjC,YACmB,WAAgC,EAChC,WAAwB;QADxB,gBAAW,GAAX,WAAW,CAAqB;QAChC,gBAAW,GAAX,WAAW,CAAa;QAEzC,IAAI,CAAC,MAAM,GAAG,IAAI,iBAAM,CAAC;YACvB,IAAI,EAAE,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,aAAa,CAAC;YAC5C,OAAO,EAAE,SAAS;SACnB,CAAC,CAAC;IACL,CAAC;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
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const testing_1 = require("@nestjs/testing");
4
+ const oidc_provider_controller_1 = require("./oidc-provider.controller");
5
+ describe('OidcProviderController', () => {
6
+ let controller;
7
+ beforeEach(async () => {
8
+ const module = await testing_1.Test.createTestingModule({
9
+ controllers: [oidc_provider_controller_1.OidcProviderController],
10
+ }).compile();
11
+ controller = module.get(oidc_provider_controller_1.OidcProviderController);
12
+ });
13
+ it('should be defined', () => {
14
+ expect(controller).toBeDefined();
15
+ });
16
+ });
17
+ //# sourceMappingURL=oidc-provider.controller.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-provider.controller.spec.js","sourceRoot":"","sources":["../../src/oidc-provider/oidc-provider.controller.spec.ts"],"names":[],"mappings":";;AAAA,6CAAsD;AACtD,yEAAoE;AAEpE,QAAQ,CAAC,wBAAwB,EAAE,GAAG,EAAE;IACtC,IAAI,UAAkC,CAAC;IAEvC,UAAU,CAAC,KAAK,IAAI,EAAE;QACpB,MAAM,MAAM,GAAkB,MAAM,cAAI,CAAC,mBAAmB,CAAC;YAC3D,WAAW,EAAE,CAAC,iDAAsB,CAAC;SACtC,CAAC,CAAC,OAAO,EAAE,CAAC;QAEb,UAAU,GAAG,MAAM,CAAC,GAAG,CAAyB,iDAAsB,CAAC,CAAC;IAC1E,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,mBAAmB,EAAE,GAAG,EAAE;QAC3B,MAAM,CAAC,UAAU,CAAC,CAAC,WAAW,EAAE,CAAC;IACnC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare class OidcProviderModule {
2
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.OidcProviderModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const oidc_provider_service_1 = require("./oidc-provider.service");
12
+ const oidc_provider_controller_1 = require("./oidc-provider.controller");
13
+ const core_1 = require("@builder6/core");
14
+ let OidcProviderModule = class OidcProviderModule {
15
+ };
16
+ exports.OidcProviderModule = OidcProviderModule;
17
+ exports.OidcProviderModule = OidcProviderModule = __decorate([
18
+ (0, common_1.Module)({
19
+ imports: [core_1.AuthModule, core_1.MongodbModule],
20
+ providers: [oidc_provider_service_1.OidcProviderService],
21
+ controllers: [oidc_provider_controller_1.OidcProviderController],
22
+ exports: [oidc_provider_service_1.OidcProviderService],
23
+ })
24
+ ], OidcProviderModule);
25
+ //# sourceMappingURL=oidc-provider.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-provider.module.js","sourceRoot":"","sources":["../../src/oidc-provider/oidc-provider.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAAwC;AACxC,mEAA8D;AAC9D,yEAAoE;AACpE,yCAA2D;AAQpD,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;CAAG,CAAA;AAArB,gDAAkB;6BAAlB,kBAAkB;IAN9B,IAAA,eAAM,EAAC;QACN,OAAO,EAAE,CAAC,iBAAU,EAAE,oBAAa,CAAC;QACpC,SAAS,EAAE,CAAC,2CAAmB,CAAC;QAChC,WAAW,EAAE,CAAC,iDAAsB,CAAC;QACrC,OAAO,EAAE,CAAC,2CAAmB,CAAC;KAC/B,CAAC;GACW,kBAAkB,CAAG"}
@@ -0,0 +1,25 @@
1
+ import { AuthService, MongodbService } from '@builder6/core';
2
+ import { ConfigService } from '@nestjs/config';
3
+ import { Provider } from 'oidc-provider';
4
+ import type { KoaContextWithOIDC } from 'oidc-provider';
5
+ export declare class OidcProviderService {
6
+ private configService;
7
+ private readonly authService;
8
+ private mongodbService;
9
+ provider: Provider;
10
+ private readonly logger;
11
+ constructor(configService: ConfigService, authService: AuthService, mongodbService: MongodbService);
12
+ validateUser(username: string, password: string, space_id?: string): Promise<string | null>;
13
+ findAccount(ctx: KoaContextWithOIDC, id: string): Promise<{
14
+ accountId: string;
15
+ claims: () => {
16
+ sub: any;
17
+ space: any;
18
+ username: any;
19
+ email: any;
20
+ mobile: any;
21
+ name: any;
22
+ };
23
+ }>;
24
+ getCallback(): any;
25
+ }
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ var OidcProviderService_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.OidcProviderService = void 0;
17
+ const core_1 = require("@builder6/core");
18
+ const common_1 = require("@nestjs/common");
19
+ const config_1 = require("@nestjs/config");
20
+ const oidc_provider_1 = require("oidc-provider");
21
+ const bcrypt_1 = __importDefault(require("bcrypt"));
22
+ const crypto_1 = __importDefault(require("crypto"));
23
+ let OidcProviderService = OidcProviderService_1 = class OidcProviderService {
24
+ constructor(configService, authService, mongodbService) {
25
+ this.configService = configService;
26
+ this.authService = authService;
27
+ this.mongodbService = mongodbService;
28
+ this.logger = new common_1.Logger(OidcProviderService_1.name);
29
+ const rootUrl = this.configService.get('root.url');
30
+ const clientId = this.configService.get('oidc.provider.client.id');
31
+ const clientSecret = this.configService.get('oidc.provider.client.secret');
32
+ const redirectUris = this.configService
33
+ .get('oidc.provider.redirect.uris')
34
+ ?.split(',');
35
+ if (!clientId || !clientSecret) {
36
+ return;
37
+ }
38
+ const oidcConfig = {
39
+ clients: [
40
+ {
41
+ client_id: clientId,
42
+ client_secret: clientSecret,
43
+ redirect_uris: [...redirectUris],
44
+ response_types: ['code'],
45
+ grant_types: ['authorization_code'],
46
+ },
47
+ ],
48
+ features: {
49
+ revocation: { enabled: true },
50
+ introspection: { enabled: true },
51
+ registration: { enabled: false },
52
+ devInteractions: { enabled: false },
53
+ },
54
+ pkce: {
55
+ required: () => false,
56
+ },
57
+ clientBasedCORS: (ctx, origin, client) => {
58
+ return true;
59
+ },
60
+ interactions: {
61
+ url(ctx, interaction) {
62
+ return `/api/v6/idp/common/interaction/${interaction.uid}`;
63
+ },
64
+ },
65
+ findAccount: this.findAccount.bind(this),
66
+ };
67
+ this.provider = new oidc_provider_1.Provider(`${rootUrl}/api/v6/idp`, oidcConfig);
68
+ }
69
+ async validateUser(username, password, space_id) {
70
+ if (!space_id) {
71
+ space_id = await this.authService.getPrimarySpaceId();
72
+ }
73
+ const user = (await this.mongodbService.findOne('users', {
74
+ $or: [
75
+ { username: { $regex: new RegExp(username, 'i') } },
76
+ { 'emails.address': { $regex: new RegExp(username, 'i') } },
77
+ { mobile: { $regex: new RegExp(username, 'i') } },
78
+ ],
79
+ }));
80
+ if (!user) {
81
+ this.logger.log(`Login failed ${username}, user not found`);
82
+ return null;
83
+ }
84
+ if (password) {
85
+ const hash = crypto_1.default.createHash('sha256');
86
+ hash.update(password);
87
+ const bcryptPassword = hash.digest('hex');
88
+ const match = await bcrypt_1.default.compare(bcryptPassword, user.services.password.bcrypt);
89
+ if (!match) {
90
+ this.logger.log(`Login failed ${username}, Password does not match`);
91
+ return null;
92
+ }
93
+ }
94
+ return `${space_id}/${user._id}`;
95
+ }
96
+ async findAccount(ctx, id) {
97
+ console.log('findAccount', ctx, id);
98
+ const { spaceId, userId } = id.split('/');
99
+ const user = await this.authService.getSpaceUser(userId, spaceId);
100
+ return {
101
+ accountId: id,
102
+ claims: () => ({
103
+ sub: userId,
104
+ space: spaceId,
105
+ username: user.username,
106
+ email: user.email,
107
+ mobile: user.mobile,
108
+ name: user.name,
109
+ }),
110
+ };
111
+ }
112
+ getCallback() {
113
+ return this.provider?.callback();
114
+ }
115
+ };
116
+ exports.OidcProviderService = OidcProviderService;
117
+ exports.OidcProviderService = OidcProviderService = OidcProviderService_1 = __decorate([
118
+ (0, common_1.Injectable)(),
119
+ __metadata("design:paramtypes", [config_1.ConfigService,
120
+ core_1.AuthService,
121
+ core_1.MongodbService])
122
+ ], OidcProviderService);
123
+ //# sourceMappingURL=oidc-provider.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-provider.service.js","sourceRoot":"","sources":["../../src/oidc-provider/oidc-provider.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAA6D;AAC7D,2CAAoD;AACpD,2CAA+C;AAC/C,iDAAyC;AAEzC,oDAA4B;AAC5B,oDAA4B;AAGrB,IAAM,mBAAmB,2BAAzB,MAAM,mBAAmB;IAI9B,YACU,aAA4B,EACnB,WAAwB,EACjC,cAA8B;QAF9B,kBAAa,GAAb,aAAa,CAAe;QACnB,gBAAW,GAAX,WAAW,CAAa;QACjC,mBAAc,GAAd,cAAc,CAAgB;QALvB,WAAM,GAAG,IAAI,eAAM,CAAC,qBAAmB,CAAC,IAAI,CAAC,CAAC;QAO7D,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,QA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AAQ,2BAA2B,CAAC,CAAC;gBACrE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QAED,OAAO,GAAG,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;IACnC,CAAC;IAID,KAAK,CAAC,WAAW,CAAC,GAAuB,EAAE,EAAU;QAEnD,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;QAiBpC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAQ,CAAC;QACjD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAElE,OAAO;YACL,SAAS,EAAE,EAAE;YACb,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;gBACb,GAAG,EAAE,MAAM;gBACX,KAAK,EAAE,OAAO;gBACd,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,IAAI,EAAE,IAAI,CAAC,IAAI;aAChB,CAAC;SACH,CAAC;IACJ,CAAC;IAGD,WAAW;QACT,OAAO,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,CAAC;IACnC,CAAC;CACF,CAAA;AA9IY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,mBAAU,GAAE;qCAMc,sBAAa;QACN,kBAAW;QACjB,qBAAc;GAP7B,mBAAmB,CA8I/B"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const testing_1 = require("@nestjs/testing");
4
+ const oidc_provider_service_1 = require("./oidc-provider.service");
5
+ describe('OidcProviderService', () => {
6
+ let service;
7
+ beforeEach(async () => {
8
+ const module = await testing_1.Test.createTestingModule({
9
+ providers: [oidc_provider_service_1.OidcProviderService],
10
+ }).compile();
11
+ service = module.get(oidc_provider_service_1.OidcProviderService);
12
+ });
13
+ it('should be defined', () => {
14
+ expect(service).toBeDefined();
15
+ });
16
+ });
17
+ //# sourceMappingURL=oidc-provider.service.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-provider.service.spec.js","sourceRoot":"","sources":["../../src/oidc-provider/oidc-provider.service.spec.ts"],"names":[],"mappings":";;AAAA,6CAAsD;AACtD,mEAA8D;AAE9D,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,IAAI,OAA4B,CAAC;IAEjC,UAAU,CAAC,KAAK,IAAI,EAAE;QACpB,MAAM,MAAM,GAAkB,MAAM,cAAI,CAAC,mBAAmB,CAAC;YAC3D,SAAS,EAAE,CAAC,2CAAmB,CAAC;SACjC,CAAC,CAAC,OAAO,EAAE,CAAC;QAEb,OAAO,GAAG,MAAM,CAAC,GAAG,CAAsB,2CAAmB,CAAC,CAAC;IACjE,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,mBAAmB,EAAE,GAAG,EAAE;QAC3B,MAAM,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;IAChC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@builder6/oidc-provider",
3
+ "version": "0.15.0",
4
+ "main": "dist/index.js",
5
+ "license": "MIT",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "scripts": {
10
+ "format": "prettier --write \"src/**/*.ts\"",
11
+ "build": "rimraf dist && tsc",
12
+ "build:watch": "rimraf dist && tsc --watch"
13
+ },
14
+ "dependencies": {
15
+ "@builder6/core": "0.15.0",
16
+ "lodash": "^4.17.5",
17
+ "oidc-provider": "^8.8.1"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "gitHead": "afb054a09554b900d65a2588d27ddf1001639843"
23
+ }