diff --git a/packages/backend/src/CoreModule.js b/packages/backend/src/CoreModule.js index c16ef57f..3de3ff73 100644 --- a/packages/backend/src/CoreModule.js +++ b/packages/backend/src/CoreModule.js @@ -219,6 +219,9 @@ const install = async ({ services, app }) => { const { GetUserService } = require('./services/GetUserService'); services.registerService('get-user', GetUserService); + + const { DetailProviderService } = require('./services/DetailProviderService'); + services.registerService('whoami', DetailProviderService); } const install_legacy = async ({ services }) => { diff --git a/packages/backend/src/routers/whoami.js b/packages/backend/src/routers/whoami.js index fe6bf912..02846aa5 100644 --- a/packages/backend/src/routers/whoami.js +++ b/packages/backend/src/routers/whoami.js @@ -60,6 +60,11 @@ const WHOAMI_GET = eggspress('/whoami', { ...(req.new_token ? { token: req.token } : {}) }; + // Get whoami values from other services + const svc_whoami = req.services.get('whoami'); + const provider_details = await svc_whoami.get_details({ user: req.user }); + Object.assign(details, provider_details); + if ( ! is_user ) { // When apps call /whoami they should not see these attributes // delete details.username; diff --git a/packages/backend/src/services/DetailProviderService.js b/packages/backend/src/services/DetailProviderService.js new file mode 100644 index 00000000..2907fdc8 --- /dev/null +++ b/packages/backend/src/services/DetailProviderService.js @@ -0,0 +1,29 @@ +const BaseService = require("./BaseService") + +/** + * A generic service class for any service that enables registering + * detail providers. A detail provider is a function that takes an + * input object and uses its values to populate another object. + */ +class DetailProviderService extends BaseService { + _construct () { + this.providers_ = []; + } + + register_provider (fn) { + this.providers_.push(fn); + } + + async get_details (context) { + const details = {}; + + for (const provider of this.providers_) { + const out = await provider(context); + Object.assign(details, out); + } + + return details; + } +} + +module.exports = { DetailProviderService }