@kne/fastify-oidc 0.0.0-stage → 0.1.1
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 +681 -2
- package/index.js +146 -0
- package/libs/controllers/admin.js +150 -0
- package/libs/controllers/backchannel.js +49 -0
- package/libs/controllers/interaction.js +87 -0
- package/libs/controllers/service.js +59 -0
- package/libs/idp/adapters/sequelize.js +82 -0
- package/libs/idp/create-provider.js +286 -0
- package/libs/idp/grant-helpers.js +31 -0
- package/libs/idp/grants/token-exchange.js +82 -0
- package/libs/idp/identity.js +108 -0
- package/libs/idp/index.js +123 -0
- package/libs/idp/mount.js +26 -0
- package/libs/locale/en-US.js +63 -0
- package/libs/locale/index.js +4 -0
- package/libs/locale/zh-CN.js +63 -0
- package/libs/models/client.js +43 -0
- package/libs/models/key.js +44 -0
- package/libs/models/payload.js +50 -0
- package/libs/models/resource-server.js +42 -0
- package/libs/models/session-tenant.js +26 -0
- package/libs/resource/authenticate.js +203 -0
- package/libs/resource/dpop.js +52 -0
- package/libs/resource/normalize-user.js +42 -0
- package/libs/resource/revocation.js +62 -0
- package/libs/resource/service-client.js +91 -0
- package/libs/resource/user-mirror.js +60 -0
- package/libs/resource/verify-token.js +51 -0
- package/libs/services/client.js +167 -0
- package/libs/services/grant.js +104 -0
- package/libs/services/interaction.js +118 -0
- package/libs/services/key.js +103 -0
- package/libs/services/resource-server.js +99 -0
- package/libs/services/session-tenant.js +32 -0
- package/libs/utils/crypto.js +25 -0
- package/libs/utils/intl.js +71 -0
- package/libs/utils/resolve-options.js +68 -0
- package/package.json +83 -4
package/index.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const resolveOptions = require('./libs/utils/resolve-options');
|
|
4
|
+
const createIdp = require('./libs/idp');
|
|
5
|
+
const mount = require('./libs/idp/mount');
|
|
6
|
+
const createRevocation = require('./libs/resource/revocation');
|
|
7
|
+
const createDPoP = require('./libs/resource/dpop');
|
|
8
|
+
const createVerifier = require('./libs/resource/verify-token');
|
|
9
|
+
const createServiceClient = require('./libs/resource/service-client');
|
|
10
|
+
const createUserMirror = require('./libs/resource/user-mirror');
|
|
11
|
+
const createAuthenticate = require('./libs/resource/authenticate');
|
|
12
|
+
const { locale, createTranslator } = require('./libs/utils/intl');
|
|
13
|
+
|
|
14
|
+
const DAY = 24 * 60 * 60;
|
|
15
|
+
const INSECURE_SECRET = 'fastify-oidc-insecure-key-secret';
|
|
16
|
+
|
|
17
|
+
module.exports = fp(
|
|
18
|
+
async (fastify, options) => {
|
|
19
|
+
const env = process.env;
|
|
20
|
+
options = Object.assign(
|
|
21
|
+
{
|
|
22
|
+
name: 'oidc',
|
|
23
|
+
prefix: '/api/oidc',
|
|
24
|
+
dbTableNamePrefix: 't_',
|
|
25
|
+
mode: env.AUTH_MODE || 'standalone',
|
|
26
|
+
origin: env.ORIGIN,
|
|
27
|
+
issuer: env.OIDC_ISSUER,
|
|
28
|
+
mountPath: '/oidc',
|
|
29
|
+
audience: env.OIDC_AUDIENCE,
|
|
30
|
+
clientId: env.OIDC_CLIENT_ID,
|
|
31
|
+
claimNamespace: null,
|
|
32
|
+
keyEncryptionSecret: env.OIDC_KEY_SECRET,
|
|
33
|
+
cookieSecret: env.OIDC_COOKIE_SECRET,
|
|
34
|
+
trustProxy: true,
|
|
35
|
+
allowPrivateFetch: false,
|
|
36
|
+
adapter: null,
|
|
37
|
+
clockTolerance: 5,
|
|
38
|
+
retiredKeyTTL: 2 * DAY,
|
|
39
|
+
keyReloadInterval: 60,
|
|
40
|
+
cleanupInterval: 60 * 60,
|
|
41
|
+
interactionPage: '/oidc-interaction',
|
|
42
|
+
callbackPath: '/oidc-callback',
|
|
43
|
+
legacyToken: true,
|
|
44
|
+
tenantSource: null,
|
|
45
|
+
tenantUserContextName: 'tenantUserInfo',
|
|
46
|
+
requireDPoP: false,
|
|
47
|
+
includePermissions: false,
|
|
48
|
+
defaultResourceScope: 'api',
|
|
49
|
+
accountNamespace: 'account',
|
|
50
|
+
tenantNamespace: 'tenant',
|
|
51
|
+
intlNamespace: 'intl',
|
|
52
|
+
clients: [],
|
|
53
|
+
resourceServers: [],
|
|
54
|
+
seedSelf: true,
|
|
55
|
+
selfClient: {},
|
|
56
|
+
serviceScopes: ['user:read', 'tenant:read'],
|
|
57
|
+
userMirrorTTL: 10 * 60,
|
|
58
|
+
revocationStore: null,
|
|
59
|
+
dpopReplayStore: null,
|
|
60
|
+
getAuthenticate: type => {
|
|
61
|
+
const { authenticate } = fastify[options.name];
|
|
62
|
+
if (/:manage$/.test(type)) {
|
|
63
|
+
return [authenticate.user, authenticate.admin];
|
|
64
|
+
}
|
|
65
|
+
return [authenticate.user];
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
options
|
|
69
|
+
);
|
|
70
|
+
options.ttl = Object.assign({ accessToken: 10 * 60, idToken: 60 * 60, refreshToken: 14 * DAY, interaction: 10 * 60, session: 14 * DAY, grant: 14 * DAY }, options.ttl);
|
|
71
|
+
options.serviceClient = Object.assign({ clientId: env.OIDC_SERVICE_CLIENT_ID, clientSecret: env.OIDC_SERVICE_CLIENT_SECRET }, options.serviceClient);
|
|
72
|
+
options.runtime = resolveOptions(options);
|
|
73
|
+
const { runtime } = options;
|
|
74
|
+
|
|
75
|
+
if (runtime.idpEnabled && !options.keyEncryptionSecret) {
|
|
76
|
+
fastify.log.warn('fastify-oidc: 未配置 keyEncryptionSecret(环境变量 OIDC_KEY_SECRET),正在使用不安全的默认值,生产环境必须配置');
|
|
77
|
+
options.keyEncryptionSecret = INSECURE_SECRET;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (!fastify.hasRequestDecorator('user')) {
|
|
81
|
+
fastify.decorateRequest('user', null);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const translator = createTranslator({ fastify, options });
|
|
85
|
+
const idp = runtime.idpEnabled ? createIdp({ fastify, options, translator }) : null;
|
|
86
|
+
const revocation = createRevocation({ store: options.revocationStore, ttl: Math.max(options.ttl.accessToken, options.ttl.idToken) + options.clockTolerance });
|
|
87
|
+
const verifier = createVerifier({ options, getLocalJWKS: idp ? () => idp.getLocalJWKS() : null });
|
|
88
|
+
const serviceClient = createServiceClient({ options });
|
|
89
|
+
const userMirror = createUserMirror({ fastify, options, serviceClient });
|
|
90
|
+
const dpop = createDPoP({ clockTolerance: options.clockTolerance, replayStore: options.dpopReplayStore });
|
|
91
|
+
const authenticate = createAuthenticate({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, translator });
|
|
92
|
+
|
|
93
|
+
const modules = [];
|
|
94
|
+
if (runtime.idpEnabled) {
|
|
95
|
+
modules.push([
|
|
96
|
+
'models',
|
|
97
|
+
await fastify.sequelize.addModels(path.resolve(__dirname, './libs/models'), {
|
|
98
|
+
prefix: options.dbTableNamePrefix,
|
|
99
|
+
modelPrefix: options.name
|
|
100
|
+
})
|
|
101
|
+
]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let readyPromise = Promise.resolve();
|
|
105
|
+
if (idp) {
|
|
106
|
+
readyPromise = fastify.sequelize.syncPromise.then(() => idp.init());
|
|
107
|
+
readyPromise.catch(err => fastify.log.error({ err }, 'fastify-oidc: IdP 初始化失败'));
|
|
108
|
+
fastify.addHook('onClose', async () => idp.close());
|
|
109
|
+
fastify.register(mount, { idp, mountPath: runtime.mountPath, translator });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
fastify.register(require('@kne/fastify-namespace'), {
|
|
113
|
+
options,
|
|
114
|
+
name: options.name,
|
|
115
|
+
modules: [
|
|
116
|
+
...modules,
|
|
117
|
+
['locale', locale],
|
|
118
|
+
['translator', translator],
|
|
119
|
+
['idp', idp],
|
|
120
|
+
['revocation', revocation],
|
|
121
|
+
['verifier', verifier],
|
|
122
|
+
['serviceClient', serviceClient],
|
|
123
|
+
['userMirror', userMirror],
|
|
124
|
+
['authenticate', authenticate],
|
|
125
|
+
['whenReady', () => readyPromise],
|
|
126
|
+
[
|
|
127
|
+
'onPermissionChange',
|
|
128
|
+
async ({ userIds = [], logout = false } = {}) => {
|
|
129
|
+
if (!idp) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
await readyPromise;
|
|
133
|
+
for (const userId of userIds) {
|
|
134
|
+
await fastify[options.name].services.grant.revokeByAccount(userId, { logout });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
],
|
|
138
|
+
['services', path.resolve(__dirname, './libs/services')],
|
|
139
|
+
['controllers', path.resolve(__dirname, './libs/controllers')]
|
|
140
|
+
]
|
|
141
|
+
});
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
name: 'fastify-oidc'
|
|
145
|
+
}
|
|
146
|
+
);
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
|
|
3
|
+
const idSchema = { type: 'object', required: ['id'], properties: { id: { type: 'string' } } };
|
|
4
|
+
const listQuery = {
|
|
5
|
+
type: 'object',
|
|
6
|
+
properties: {
|
|
7
|
+
filter: { type: 'object', additionalProperties: true },
|
|
8
|
+
perPage: { type: 'number', default: 20 },
|
|
9
|
+
currentPage: { type: 'number', default: 1 }
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
const statusBody = {
|
|
13
|
+
type: 'object',
|
|
14
|
+
required: ['id', 'status'],
|
|
15
|
+
properties: { id: { type: 'string' }, status: { type: 'string', enum: ['open', 'closed'] } }
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
module.exports = fp(async (fastify, options) => {
|
|
19
|
+
const { services, translator } = fastify[options.name];
|
|
20
|
+
if (!options.runtime.idpEnabled) {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const { wrap } = translator;
|
|
24
|
+
const admin = `${options.prefix}/admin`;
|
|
25
|
+
|
|
26
|
+
const clientBody = {
|
|
27
|
+
type: 'object',
|
|
28
|
+
properties: {
|
|
29
|
+
id: { type: 'string' },
|
|
30
|
+
clientId: { type: 'string' },
|
|
31
|
+
clientName: { type: 'string' },
|
|
32
|
+
clientSecret: { type: 'string' },
|
|
33
|
+
metadata: { type: 'object', additionalProperties: true },
|
|
34
|
+
allowedResources: { type: 'array', items: { type: 'string' } },
|
|
35
|
+
description: { type: 'string' }
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const resourceServerBody = {
|
|
40
|
+
type: 'object',
|
|
41
|
+
properties: {
|
|
42
|
+
id: { type: 'string' },
|
|
43
|
+
identifier: { type: 'string' },
|
|
44
|
+
name: { type: 'string' },
|
|
45
|
+
scope: { type: 'string' },
|
|
46
|
+
accessTokenTTL: { type: 'number' },
|
|
47
|
+
includePermissions: { type: 'boolean' },
|
|
48
|
+
description: { type: 'string' }
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const crud = (path, tag, service, body) => {
|
|
53
|
+
const tags = [tag];
|
|
54
|
+
const onRequest = options.getAuthenticate(`${path}:manage`);
|
|
55
|
+
fastify.get(
|
|
56
|
+
`${admin}/${path}/list`,
|
|
57
|
+
{ onRequest, schema: { tags, summary: `${tag}列表`, query: listQuery } },
|
|
58
|
+
wrap(async request => service().list(request.query))
|
|
59
|
+
);
|
|
60
|
+
fastify.get(
|
|
61
|
+
`${admin}/${path}/detail`,
|
|
62
|
+
{ onRequest, schema: { tags, summary: `${tag}详情`, query: idSchema } },
|
|
63
|
+
wrap(async request => service().detail(request.query))
|
|
64
|
+
);
|
|
65
|
+
fastify.post(
|
|
66
|
+
`${admin}/${path}/create`,
|
|
67
|
+
{ onRequest, schema: { tags, summary: `创建${tag}`, body } },
|
|
68
|
+
wrap(async request => service().create(request.body))
|
|
69
|
+
);
|
|
70
|
+
fastify.post(
|
|
71
|
+
`${admin}/${path}/save`,
|
|
72
|
+
{ onRequest, schema: { tags, summary: `修改${tag}`, body: Object.assign({}, body, { required: ['id'] }) } },
|
|
73
|
+
wrap(async request => {
|
|
74
|
+
await service().save(request.body);
|
|
75
|
+
return {};
|
|
76
|
+
})
|
|
77
|
+
);
|
|
78
|
+
fastify.post(
|
|
79
|
+
`${admin}/${path}/set-status`,
|
|
80
|
+
{ onRequest, schema: { tags, summary: `启用 / 停用${tag}`, body: statusBody } },
|
|
81
|
+
wrap(async request => {
|
|
82
|
+
await service().setStatus(request.body);
|
|
83
|
+
return {};
|
|
84
|
+
})
|
|
85
|
+
);
|
|
86
|
+
fastify.post(
|
|
87
|
+
`${admin}/${path}/remove`,
|
|
88
|
+
{ onRequest, schema: { tags, summary: `删除${tag}`, body: idSchema } },
|
|
89
|
+
wrap(async request => {
|
|
90
|
+
await service().remove(request.body);
|
|
91
|
+
return {};
|
|
92
|
+
})
|
|
93
|
+
);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
crud('client', 'OIDC Client', () => services.client, clientBody);
|
|
97
|
+
crud('resource-server', 'OIDC 资源服务', () => services.resourceServer, resourceServerBody);
|
|
98
|
+
|
|
99
|
+
fastify.post(
|
|
100
|
+
`${admin}/client/rotate-secret`,
|
|
101
|
+
{ onRequest: options.getAuthenticate('client:manage'), schema: { tags: ['OIDC Client'], summary: '重置 client secret(明文只返回一次)', body: idSchema } },
|
|
102
|
+
wrap(async request => services.client.rotateSecret(request.body))
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
fastify.get(
|
|
106
|
+
`${admin}/key/list`,
|
|
107
|
+
{ onRequest: options.getAuthenticate('key:manage'), schema: { tags: ['OIDC 签名密钥'], summary: '签名密钥列表' } },
|
|
108
|
+
wrap(async () => services.key.list())
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
fastify.post(
|
|
112
|
+
`${admin}/key/rotate`,
|
|
113
|
+
{ onRequest: options.getAuthenticate('key:manage'), schema: { tags: ['OIDC 签名密钥'], summary: '轮换签名密钥' } },
|
|
114
|
+
wrap(async () => services.key.rotate())
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
fastify.get(
|
|
118
|
+
`${admin}/session/list`,
|
|
119
|
+
{
|
|
120
|
+
onRequest: options.getAuthenticate('session:manage'),
|
|
121
|
+
schema: { tags: ['OIDC 会话'], summary: '用户登录会话列表', query: { type: 'object', required: ['userId'], properties: { userId: { type: 'string' } } } }
|
|
122
|
+
},
|
|
123
|
+
wrap(async request => services.grant.listSessions(request.query))
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
fastify.post(
|
|
127
|
+
`${admin}/session/revoke`,
|
|
128
|
+
{
|
|
129
|
+
onRequest: options.getAuthenticate('session:manage'),
|
|
130
|
+
schema: { tags: ['OIDC 会话'], summary: '结束指定会话', body: { type: 'object', required: ['uid'], properties: { uid: { type: 'string' } } } }
|
|
131
|
+
},
|
|
132
|
+
wrap(async request => {
|
|
133
|
+
await services.grant.revokeSession(request.body);
|
|
134
|
+
return {};
|
|
135
|
+
})
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
fastify.post(
|
|
139
|
+
`${admin}/session/revoke-user`,
|
|
140
|
+
{
|
|
141
|
+
onRequest: options.getAuthenticate('session:manage'),
|
|
142
|
+
schema: {
|
|
143
|
+
tags: ['OIDC 会话'],
|
|
144
|
+
summary: '撤销用户全部令牌(logout=true 时同时强制下线)',
|
|
145
|
+
body: { type: 'object', required: ['userId'], properties: { userId: { type: 'string' }, logout: { type: 'boolean', default: true } } }
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
wrap(async request => services.grant.revokeByAccount(request.body.userId, { logout: request.body.logout }))
|
|
149
|
+
);
|
|
150
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
const httpErrors = require('http-errors');
|
|
3
|
+
const { createError } = require('../utils/intl');
|
|
4
|
+
|
|
5
|
+
const { BadRequest } = httpErrors;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* central 子项目接收主项目的 back-channel logout 通知,把 sid / sub 加入本地撤销列表。
|
|
9
|
+
* client 的 backchannel_logout_uri 配置为 `${ORIGIN}${prefix}/backchannel-logout`
|
|
10
|
+
*/
|
|
11
|
+
module.exports = fp(async (fastify, options) => {
|
|
12
|
+
if (options.runtime.idpEnabled) {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
const { verifier, revocation, translator } = fastify[options.name];
|
|
16
|
+
|
|
17
|
+
fastify.register(async child => {
|
|
18
|
+
child.removeAllContentTypeParsers();
|
|
19
|
+
child.addContentTypeParser('application/x-www-form-urlencoded', { parseAs: 'string' }, (request, body, done) => {
|
|
20
|
+
done(null, Object.fromEntries(new URLSearchParams(body)));
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
child.post(
|
|
24
|
+
`${options.prefix}/backchannel-logout`,
|
|
25
|
+
{
|
|
26
|
+
schema: {
|
|
27
|
+
tags: ['OIDC 服务接口'],
|
|
28
|
+
summary: '接收 back-channel logout 通知',
|
|
29
|
+
body: { type: 'object', required: ['logout_token'], properties: { logout_token: { type: 'string' } } }
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
translator.wrap(async (request, reply) => {
|
|
33
|
+
let payload;
|
|
34
|
+
try {
|
|
35
|
+
payload = await verifier.verifyLogoutToken(request.body.logout_token, { audience: options.runtime.clientId });
|
|
36
|
+
} catch (e) {
|
|
37
|
+
throw createError(BadRequest, e.messageId || 'logoutTokenInvalid');
|
|
38
|
+
}
|
|
39
|
+
if (payload.sid) {
|
|
40
|
+
await revocation.revokeSession(payload.sid);
|
|
41
|
+
} else {
|
|
42
|
+
await revocation.revokeSubject(String(payload.sub));
|
|
43
|
+
}
|
|
44
|
+
reply.header('cache-control', 'no-store');
|
|
45
|
+
return {};
|
|
46
|
+
})
|
|
47
|
+
);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
|
|
3
|
+
module.exports = fp(async (fastify, options) => {
|
|
4
|
+
const { services, translator } = fastify[options.name];
|
|
5
|
+
if (!options.runtime.idpEnabled) {
|
|
6
|
+
return;
|
|
7
|
+
}
|
|
8
|
+
const { wrap } = translator;
|
|
9
|
+
const base = `${options.prefix}/interaction/:uid`;
|
|
10
|
+
const params = { type: 'object', required: ['uid'], properties: { uid: { type: 'string' } } };
|
|
11
|
+
const tags = ['OIDC 登录交互'];
|
|
12
|
+
|
|
13
|
+
fastify.get(
|
|
14
|
+
base,
|
|
15
|
+
{
|
|
16
|
+
schema: { tags, summary: '交互入口,跳转到前端登录交互页', params }
|
|
17
|
+
},
|
|
18
|
+
async (request, reply) => {
|
|
19
|
+
const target = new URL(options.interactionPage, options.runtime.origin);
|
|
20
|
+
target.searchParams.set('uid', request.params.uid);
|
|
21
|
+
return reply.redirect(target.toString(), 303);
|
|
22
|
+
}
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
fastify.get(
|
|
26
|
+
`${base}/details`,
|
|
27
|
+
{
|
|
28
|
+
schema: { tags, summary: '获取当前交互详情(步骤、client、用户、可选租户)', params }
|
|
29
|
+
},
|
|
30
|
+
wrap(async (request, reply) => services.interaction.details({ request, reply, uid: request.params.uid }))
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
fastify.post(
|
|
34
|
+
`${base}/login`,
|
|
35
|
+
{
|
|
36
|
+
schema: {
|
|
37
|
+
tags,
|
|
38
|
+
summary: '账号密码登录',
|
|
39
|
+
params,
|
|
40
|
+
body: {
|
|
41
|
+
type: 'object',
|
|
42
|
+
required: ['password'],
|
|
43
|
+
properties: {
|
|
44
|
+
type: { type: 'string', enum: ['email', 'phone'], default: 'email' },
|
|
45
|
+
email: { type: 'string' },
|
|
46
|
+
phone: { type: 'string' },
|
|
47
|
+
password: { type: 'string' },
|
|
48
|
+
remember: { type: 'boolean', default: true }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
wrap(async (request, reply) => {
|
|
54
|
+
const { remember, ...credentials } = request.body;
|
|
55
|
+
return services.interaction.login({ request, reply, uid: request.params.uid, credentials, remember });
|
|
56
|
+
})
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
fastify.post(
|
|
60
|
+
`${base}/tenant`,
|
|
61
|
+
{
|
|
62
|
+
schema: {
|
|
63
|
+
tags,
|
|
64
|
+
summary: '选择租户',
|
|
65
|
+
params,
|
|
66
|
+
body: { type: 'object', required: ['tenantId'], properties: { tenantId: { type: 'string' } } }
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
wrap(async (request, reply) => services.interaction.selectTenant({ request, reply, uid: request.params.uid, tenantId: request.body.tenantId }))
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
fastify.post(
|
|
73
|
+
`${base}/confirm`,
|
|
74
|
+
{
|
|
75
|
+
schema: { tags, summary: '确认授权(consent)', params }
|
|
76
|
+
},
|
|
77
|
+
wrap(async (request, reply) => services.interaction.confirm({ request, reply, uid: request.params.uid }))
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
fastify.post(
|
|
81
|
+
`${base}/abort`,
|
|
82
|
+
{
|
|
83
|
+
schema: { tags, summary: '取消登录', params }
|
|
84
|
+
},
|
|
85
|
+
wrap(async (request, reply) => services.interaction.abort({ request, reply, uid: request.params.uid }))
|
|
86
|
+
);
|
|
87
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
const httpErrors = require('http-errors');
|
|
3
|
+
const { pick } = require('lodash');
|
|
4
|
+
const { createError } = require('../utils/intl');
|
|
5
|
+
|
|
6
|
+
const { NotFound } = httpErrors;
|
|
7
|
+
|
|
8
|
+
const PROFILE_FIELDS = ['id', 'nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description', 'status'];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 供 central 子项目以 client_credentials 令牌调用的服务接口
|
|
12
|
+
*/
|
|
13
|
+
module.exports = fp(async (fastify, options) => {
|
|
14
|
+
if (!options.runtime.idpEnabled) {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
const { authenticate, translator } = fastify[options.name];
|
|
18
|
+
const { wrap } = translator;
|
|
19
|
+
const getIdp = () => fastify[options.name].idp;
|
|
20
|
+
const tags = ['OIDC 服务接口'];
|
|
21
|
+
|
|
22
|
+
fastify.get(
|
|
23
|
+
`${options.prefix}/service/user`,
|
|
24
|
+
{
|
|
25
|
+
onRequest: [authenticate.client('user:read')],
|
|
26
|
+
schema: { tags, summary: '获取用户资料', query: { type: 'object', required: ['id'], properties: { id: { type: 'string' } } } }
|
|
27
|
+
},
|
|
28
|
+
wrap(async request => {
|
|
29
|
+
const user = await getIdp().identity.getUser(request.query.id);
|
|
30
|
+
if (!user) {
|
|
31
|
+
throw createError(NotFound, 'userNotFound');
|
|
32
|
+
}
|
|
33
|
+
return Object.assign(pick(user, PROFILE_FIELDS), { id: String(user.id) });
|
|
34
|
+
})
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
fastify.get(
|
|
38
|
+
`${options.prefix}/service/tenant-user`,
|
|
39
|
+
{
|
|
40
|
+
onRequest: [authenticate.client('tenant:read')],
|
|
41
|
+
schema: {
|
|
42
|
+
tags,
|
|
43
|
+
summary: '获取用户在租户内的身份、角色与权限',
|
|
44
|
+
query: { type: 'object', required: ['userId', 'tenantId'], properties: { userId: { type: 'string' }, tenantId: { type: 'string' } } }
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
wrap(async request => {
|
|
48
|
+
const tenant = fastify[options.tenantNamespace];
|
|
49
|
+
if (!tenant) {
|
|
50
|
+
throw createError(NotFound, 'tenantNotEnabled');
|
|
51
|
+
}
|
|
52
|
+
const { userId, tenantId } = request.query;
|
|
53
|
+
if (!(await getIdp().identity.isTenantMember(userId, tenantId))) {
|
|
54
|
+
throw createError(NotFound, 'tenantMemberNotFound');
|
|
55
|
+
}
|
|
56
|
+
return tenant.services.user.getTenantUserInfo({ id: userId, tenantId });
|
|
57
|
+
})
|
|
58
|
+
);
|
|
59
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
const epochTime = date => Math.floor(date.getTime() / 1000);
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 基于 fastify-sequelize 的 oidc-provider Adapter。
|
|
5
|
+
* Client 不走这里,由 create-provider 中的 client adapter 从 client 表读取。
|
|
6
|
+
*/
|
|
7
|
+
module.exports = ({ models }) => {
|
|
8
|
+
const toPayload = row => {
|
|
9
|
+
if (!row) {
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
if (row.expiresAt && row.expiresAt.getTime() <= Date.now()) {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
const payload = Object.assign({}, row.payload);
|
|
16
|
+
if (row.consumedAt) {
|
|
17
|
+
payload.consumed = epochTime(row.consumedAt);
|
|
18
|
+
}
|
|
19
|
+
return payload;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
return class SequelizeAdapter {
|
|
23
|
+
constructor(name) {
|
|
24
|
+
this.name = name;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async upsert(id, payload, expiresIn) {
|
|
28
|
+
const values = {
|
|
29
|
+
payload,
|
|
30
|
+
grantId: payload.grantId || null,
|
|
31
|
+
userCode: payload.userCode || null,
|
|
32
|
+
uid: payload.uid || null,
|
|
33
|
+
accountId: payload.accountId || null,
|
|
34
|
+
expiresAt: expiresIn ? new Date(Date.now() + expiresIn * 1000) : null,
|
|
35
|
+
consumedAt: payload.consumed ? new Date(payload.consumed * 1000) : null
|
|
36
|
+
};
|
|
37
|
+
const row = await models.payload.findOne({ where: { modelName: this.name, payloadId: id } });
|
|
38
|
+
if (row) {
|
|
39
|
+
await row.update(values);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await models.payload.create(Object.assign({ modelName: this.name, payloadId: id }, values));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async find(id) {
|
|
46
|
+
return toPayload(await models.payload.findOne({ where: { modelName: this.name, payloadId: id } }));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async findByUid(uid) {
|
|
50
|
+
return toPayload(await models.payload.findOne({ where: { modelName: this.name, uid } }));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async findByUserCode(userCode) {
|
|
54
|
+
return toPayload(await models.payload.findOne({ where: { modelName: this.name, userCode } }));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async consume(id) {
|
|
58
|
+
await models.payload.update({ consumedAt: new Date() }, { where: { modelName: this.name, payloadId: id } });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async destroy(id) {
|
|
62
|
+
await models.payload.destroy({ where: { modelName: this.name, payloadId: id } });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async revokeByGrantId(grantId) {
|
|
66
|
+
await models.payload.destroy({ where: { grantId } });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async findByAccountId(accountId) {
|
|
70
|
+
const rows = await models.payload.findAll({ where: { modelName: this.name, accountId: String(accountId) } });
|
|
71
|
+
return rows.map(toPayload).filter(Boolean);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async findGrantIdsByAccountId(accountId) {
|
|
75
|
+
const rows = await models.payload.findAll({
|
|
76
|
+
attributes: ['payloadId'],
|
|
77
|
+
where: { modelName: 'Grant', accountId: String(accountId) }
|
|
78
|
+
});
|
|
79
|
+
return rows.map(row => row.payloadId);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
};
|