feat: home-server package initial setup with Api Gateway and Auth services (#605)

* fix(api-gateway): reduce exports

* wip controllers

* fix: imports of controllers

* fix(api-gateway): rename http service interface to proxy interface

* wip: self-registering services and controllers

* wip: add registering controller method bindings and services in container

* feat: merge two services together

* wip: resolving endpoints to direct code calls

* wip: bind controller container to a singleton

* fix: controller binding to instantiate and self-register on controller container

* fix: move signout endpoint to auth controller

* wip: define inversify controllers in the controller container

* fix(auth): bind inversify controllers to controller container

* fix(auth): linter issues

* fix(auth): specs

* fix(auth): inversify controllers bindings

* wip: endpoint resolving

* wip: add endpoint for more auth controllers

* wip: add sessions controller endpoint resolvings

* wip: add subscription invites endpoint resolvings

* wip: add subscription tokens endpoint resolvings

* wip: add all binding for auth server controllers

* wip: fix migrations path

* fix: configure default env vars and ci setup
This commit is contained in:
Karol Sójko 2023-05-16 11:38:56 +02:00 committed by GitHub
parent 89eb798fa8
commit dc71e6777f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
183 changed files with 2324 additions and 1235 deletions

View file

@ -15,6 +15,7 @@ DB_TYPE=mysql
REDIS_PORT=6379 REDIS_PORT=6379
REDIS_HOST=cache REDIS_HOST=cache
CACHE_TYPE=redis
######## ########
# KEYS # # KEYS #

4
.pnp.cjs generated
View file

@ -4623,8 +4623,11 @@ const RAW_RUNTIME_STATE =
"packageDependencies": [\ "packageDependencies": [\
["@standardnotes/home-server", "workspace:packages/home-server"],\ ["@standardnotes/home-server", "workspace:packages/home-server"],\
["@standardnotes/api-gateway", "workspace:packages/api-gateway"],\ ["@standardnotes/api-gateway", "workspace:packages/api-gateway"],\
["@standardnotes/auth-server", "workspace:packages/auth"],\
["@standardnotes/domain-core", "workspace:packages/domain-core"],\
["@types/cors", "npm:2.8.13"],\ ["@types/cors", "npm:2.8.13"],\
["@types/express", "npm:4.17.17"],\ ["@types/express", "npm:4.17.17"],\
["@types/prettyjson", "npm:0.0.30"],\
["@typescript-eslint/eslint-plugin", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.59.2"],\ ["@typescript-eslint/eslint-plugin", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.59.2"],\
["@typescript-eslint/parser", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.59.2"],\ ["@typescript-eslint/parser", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.59.2"],\
["cors", "npm:2.8.5"],\ ["cors", "npm:2.8.5"],\
@ -4637,6 +4640,7 @@ const RAW_RUNTIME_STATE =
["inversify", "npm:6.0.1"],\ ["inversify", "npm:6.0.1"],\
["inversify-express-utils", "npm:6.4.3"],\ ["inversify-express-utils", "npm:6.4.3"],\
["prettier", "npm:2.8.8"],\ ["prettier", "npm:2.8.8"],\
["prettyjson", "npm:1.2.5"],\
["reflect-metadata", "npm:0.1.13"],\ ["reflect-metadata", "npm:0.1.13"],\
["typescript", "patch:typescript@npm%3A5.0.4#optional!builtin<compat/typescript>::version=5.0.4&hash=b5f058"],\ ["typescript", "patch:typescript@npm%3A5.0.4#optional!builtin<compat/typescript>::version=5.0.4&hash=b5f058"],\
["winston", "npm:3.8.2"]\ ["winston", "npm:3.8.2"]\

View file

@ -9,19 +9,23 @@ import { Timer, TimerInterface } from '@standardnotes/time'
import { Env } from './Env' import { Env } from './Env'
import { TYPES } from './Types' import { TYPES } from './Types'
import { AuthMiddleware } from '../Controller/AuthMiddleware' import { AuthMiddleware } from '../Controller/AuthMiddleware'
import { HttpServiceInterface } from '../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../Service/Http/ServiceProxyInterface'
import { HttpService } from '../Service/Http/HttpService' import { HttpServiceProxy } from '../Service/Http/HttpServiceProxy'
import { SubscriptionTokenAuthMiddleware } from '../Controller/SubscriptionTokenAuthMiddleware' import { SubscriptionTokenAuthMiddleware } from '../Controller/SubscriptionTokenAuthMiddleware'
import { CrossServiceTokenCacheInterface } from '../Service/Cache/CrossServiceTokenCacheInterface' import { CrossServiceTokenCacheInterface } from '../Service/Cache/CrossServiceTokenCacheInterface'
import { RedisCrossServiceTokenCache } from '../Infra/Redis/RedisCrossServiceTokenCache' import { RedisCrossServiceTokenCache } from '../Infra/Redis/RedisCrossServiceTokenCache'
import { WebSocketAuthMiddleware } from '../Controller/WebSocketAuthMiddleware' import { WebSocketAuthMiddleware } from '../Controller/WebSocketAuthMiddleware'
import { InMemoryCrossServiceTokenCache } from '../Infra/InMemory/InMemoryCrossServiceTokenCache' import { InMemoryCrossServiceTokenCache } from '../Infra/InMemory/InMemoryCrossServiceTokenCache'
import { DirectCallServiceProxy } from '../Service/Proxy/DirectCallServiceProxy'
import { ServiceContainerInterface } from '@standardnotes/domain-core'
import { EndpointResolverInterface } from '../Service/Resolver/EndpointResolverInterface'
import { EndpointResolver } from '../Service/Resolver/EndpointResolver'
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const newrelicFormatter = require('@newrelic/winston-enricher') const newrelicFormatter = require('@newrelic/winston-enricher')
export class ContainerConfigLoader { export class ContainerConfigLoader {
async load(): Promise<Container> { async load(serviceContainer?: ServiceContainerInterface): Promise<Container> {
const env: Env = new Env() const env: Env = new Env()
env.load() env.load()
@ -57,14 +61,14 @@ export class ContainerConfigLoader {
container.bind<AxiosInstance>(TYPES.HTTPClient).toConstantValue(axios.create()) container.bind<AxiosInstance>(TYPES.HTTPClient).toConstantValue(axios.create())
// env vars // env vars
container.bind(TYPES.SYNCING_SERVER_JS_URL).toConstantValue(env.get('SYNCING_SERVER_JS_URL')) container.bind(TYPES.SYNCING_SERVER_JS_URL).toConstantValue(env.get('SYNCING_SERVER_JS_URL', true))
container.bind(TYPES.AUTH_SERVER_URL).toConstantValue(env.get('AUTH_SERVER_URL')) container.bind(TYPES.AUTH_SERVER_URL).toConstantValue(env.get('AUTH_SERVER_URL', true))
container.bind(TYPES.REVISIONS_SERVER_URL).toConstantValue(env.get('REVISIONS_SERVER_URL', true)) container.bind(TYPES.REVISIONS_SERVER_URL).toConstantValue(env.get('REVISIONS_SERVER_URL', true))
container.bind(TYPES.EMAIL_SERVER_URL).toConstantValue(env.get('EMAIL_SERVER_URL', true)) container.bind(TYPES.EMAIL_SERVER_URL).toConstantValue(env.get('EMAIL_SERVER_URL', true))
container.bind(TYPES.PAYMENTS_SERVER_URL).toConstantValue(env.get('PAYMENTS_SERVER_URL', true)) container.bind(TYPES.PAYMENTS_SERVER_URL).toConstantValue(env.get('PAYMENTS_SERVER_URL', true))
container.bind(TYPES.FILES_SERVER_URL).toConstantValue(env.get('FILES_SERVER_URL', true)) container.bind(TYPES.FILES_SERVER_URL).toConstantValue(env.get('FILES_SERVER_URL', true))
container.bind(TYPES.AUTH_JWT_SECRET).toConstantValue(env.get('AUTH_JWT_SECRET'))
container.bind(TYPES.WEB_SOCKET_SERVER_URL).toConstantValue(env.get('WEB_SOCKET_SERVER_URL', true)) container.bind(TYPES.WEB_SOCKET_SERVER_URL).toConstantValue(env.get('WEB_SOCKET_SERVER_URL', true))
container.bind(TYPES.AUTH_JWT_SECRET).toConstantValue(env.get('AUTH_JWT_SECRET'))
container container
.bind(TYPES.HTTP_CALL_TIMEOUT) .bind(TYPES.HTTP_CALL_TIMEOUT)
.toConstantValue(env.get('HTTP_CALL_TIMEOUT', true) ? +env.get('HTTP_CALL_TIMEOUT', true) : 60_000) .toConstantValue(env.get('HTTP_CALL_TIMEOUT', true) ? +env.get('HTTP_CALL_TIMEOUT', true) : 60_000)
@ -79,7 +83,16 @@ export class ContainerConfigLoader {
.to(SubscriptionTokenAuthMiddleware) .to(SubscriptionTokenAuthMiddleware)
// Services // Services
container.bind<HttpServiceInterface>(TYPES.HTTPService).to(HttpService) if (isConfiguredForHomeServer) {
if (!serviceContainer) {
throw new Error('Service container is required when configured for home server')
}
container
.bind<ServiceProxyInterface>(TYPES.ServiceProxy)
.toConstantValue(new DirectCallServiceProxy(serviceContainer))
} else {
container.bind<ServiceProxyInterface>(TYPES.ServiceProxy).to(HttpServiceProxy)
}
container.bind<TimerInterface>(TYPES.Timer).toConstantValue(new Timer()) container.bind<TimerInterface>(TYPES.Timer).toConstantValue(new Timer())
if (isConfiguredForHomeServer) { if (isConfiguredForHomeServer) {
@ -89,6 +102,9 @@ export class ContainerConfigLoader {
} else { } else {
container.bind<CrossServiceTokenCacheInterface>(TYPES.CrossServiceTokenCache).to(RedisCrossServiceTokenCache) container.bind<CrossServiceTokenCacheInterface>(TYPES.CrossServiceTokenCache).to(RedisCrossServiceTokenCache)
} }
container
.bind<EndpointResolverInterface>(TYPES.EndpointResolver)
.toConstantValue(new EndpointResolver(isConfiguredForHomeServer))
return container return container
} }

View file

@ -0,0 +1,37 @@
import {
ControllerContainerInterface,
ServiceContainerInterface,
ServiceIdentifier,
ServiceInterface,
} from '@standardnotes/domain-core'
import { ContainerConfigLoader } from './Container'
export class Service implements ServiceInterface {
constructor(
private serviceContainer: ServiceContainerInterface,
private controllerContainer: ControllerContainerInterface,
) {
this.serviceContainer.register(ServiceIdentifier.create(ServiceIdentifier.NAMES.ApiGateway).getValue(), this)
}
async handleRequest(request: never, response: never, endpointOrMethodIdentifier: string): Promise<unknown> {
const method = this.controllerContainer.get(endpointOrMethodIdentifier)
if (!method) {
throw new Error(`Method ${endpointOrMethodIdentifier} not found`)
}
return method(request, response)
}
async getContainer(): Promise<unknown> {
const config = new ContainerConfigLoader()
return config.load(this.serviceContainer)
}
getId(): ServiceIdentifier {
return ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue()
}
}

View file

@ -19,9 +19,10 @@ export const TYPES = {
WebSocketAuthMiddleware: Symbol.for('WebSocketAuthMiddleware'), WebSocketAuthMiddleware: Symbol.for('WebSocketAuthMiddleware'),
SubscriptionTokenAuthMiddleware: Symbol.for('SubscriptionTokenAuthMiddleware'), SubscriptionTokenAuthMiddleware: Symbol.for('SubscriptionTokenAuthMiddleware'),
// Services // Services
HTTPService: Symbol.for('HTTPService'), ServiceProxy: Symbol.for('ServiceProxy'),
CrossServiceTokenCache: Symbol.for('CrossServiceTokenCache'), CrossServiceTokenCache: Symbol.for('CrossServiceTokenCache'),
Timer: Symbol.for('Timer'), Timer: Symbol.for('Timer'),
EndpointResolver: Symbol.for('EndpointResolver'),
} }
// export default TYPES // export default TYPES

View file

@ -1,3 +1,3 @@
export * from './Container' export * from './Container'
export * from './Env' export * from './Service'
export * from './Types' export * from './Types'

View file

@ -2,14 +2,14 @@ import { Request, Response } from 'express'
import { inject } from 'inversify' import { inject } from 'inversify'
import { controller, all, BaseHttpController, httpPost, httpGet, results, httpDelete } from 'inversify-express-utils' import { controller, all, BaseHttpController, httpPost, httpGet, results, httpDelete } from 'inversify-express-utils'
import { TYPES } from '../Bootstrap/Types' import { TYPES } from '../Bootstrap/Types'
import { HttpServiceInterface } from '../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../Service/Http/ServiceProxyInterface'
@controller('') @controller('')
export class LegacyController extends BaseHttpController { export class LegacyController extends BaseHttpController {
private AUTH_ROUTES: Map<string, string> private AUTH_ROUTES: Map<string, string>
private PARAMETRIZED_AUTH_ROUTES: Map<string, string> private PARAMETRIZED_AUTH_ROUTES: Map<string, string>
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) {
super() super()
this.AUTH_ROUTES = new Map([ this.AUTH_ROUTES = new Map([

View file

@ -2,37 +2,51 @@ import { Request, Response } from 'express'
import { inject } from 'inversify' import { inject } from 'inversify'
import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1') @controller('/v1')
export class ActionsController extends BaseHttpController { export class ActionsController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private serviceProxy: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpPost('/login') @httpPost('/login')
async login(request: Request, response: Response): Promise<void> { async login(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/sign_in', request.body) await this.serviceProxy.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/sign_in'),
request.body,
)
} }
@httpGet('/login-params') @httpGet('/login-params')
async loginParams(request: Request, response: Response): Promise<void> { async loginParams(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/params', request.body) await this.serviceProxy.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'auth/params'),
request.body,
)
} }
@httpPost('/logout') @httpPost('/logout')
async logout(request: Request, response: Response): Promise<void> { async logout(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/sign_out', request.body) await this.serviceProxy.callAuthServer(
} request,
response,
@httpGet('/auth/methods') this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/sign_out'),
async methods(request: Request, response: Response): Promise<void> { request.body,
await this.httpService.callAuthServer(request, response, 'auth/methods', request.body) )
} }
@httpGet('/unsubscribe/:token') @httpGet('/unsubscribe/:token')
async emailUnsubscribe(request: Request, response: Response): Promise<void> { async emailUnsubscribe(request: Request, response: Response): Promise<void> {
await this.httpService.callEmailServer( await this.serviceProxy.callEmailServer(
request, request,
response, response,
`subscriptions/actions/unsubscribe/${request.params.token}`, `subscriptions/actions/unsubscribe/${request.params.token}`,
@ -42,16 +56,31 @@ export class ActionsController extends BaseHttpController {
@httpPost('/recovery/codes', TYPES.AuthMiddleware) @httpPost('/recovery/codes', TYPES.AuthMiddleware)
async recoveryCodes(request: Request, response: Response): Promise<void> { async recoveryCodes(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/recovery/codes', request.body) await this.serviceProxy.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/recovery/codes'),
request.body,
)
} }
@httpPost('/recovery/login') @httpPost('/recovery/login')
async recoveryLogin(request: Request, response: Response): Promise<void> { async recoveryLogin(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/recovery/login', request.body) await this.serviceProxy.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/recovery/login'),
request.body,
)
} }
@httpPost('/recovery/login-params') @httpPost('/recovery/login-params')
async recoveryParams(request: Request, response: Response): Promise<void> { async recoveryParams(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/recovery/params', request.body) await this.serviceProxy.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/recovery/params'),
request.body,
)
} }
} }

View file

@ -3,11 +3,15 @@ import { Request, Response } from 'express'
import { controller, BaseHttpController, httpPost, httpGet, httpDelete } from 'inversify-express-utils' import { controller, BaseHttpController, httpPost, httpGet, httpDelete } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/authenticators') @controller('/v1/authenticators')
export class AuthenticatorsController extends BaseHttpController { export class AuthenticatorsController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@ -16,14 +20,23 @@ export class AuthenticatorsController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
`authenticators/${request.params.authenticatorId}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'DELETE',
'authenticators/:authenticatorId',
request.params.authenticatorId,
),
request.body, request.body,
) )
} }
@httpGet('/', TYPES.AuthMiddleware) @httpGet('/', TYPES.AuthMiddleware)
async list(request: Request, response: Response): Promise<void> { async list(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'authenticators/', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'authenticators/'),
request.body,
)
} }
@httpGet('/generate-registration-options', TYPES.AuthMiddleware) @httpGet('/generate-registration-options', TYPES.AuthMiddleware)
@ -31,7 +44,7 @@ export class AuthenticatorsController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
'authenticators/generate-registration-options', this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'authenticators/generate-registration-options'),
request.body, request.body,
) )
} }
@ -41,13 +54,18 @@ export class AuthenticatorsController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
'authenticators/generate-authentication-options', this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'authenticators/generate-authentication-options'),
request.body, request.body,
) )
} }
@httpPost('/verify-registration', TYPES.AuthMiddleware) @httpPost('/verify-registration', TYPES.AuthMiddleware)
async verifyRegistration(request: Request, response: Response): Promise<void> { async verifyRegistration(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'authenticators/verify-registration', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'authenticators/verify-registration'),
request.body,
)
} }
} }

View file

@ -3,16 +3,25 @@ import { inject } from 'inversify'
import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/files') @controller('/v1/files')
export class FilesController extends BaseHttpController { export class FilesController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpPost('/valet-tokens', TYPES.AuthMiddleware) @httpPost('/valet-tokens', TYPES.AuthMiddleware)
async createToken(request: Request, response: Response): Promise<void> { async createToken(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'valet-tokens', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'valet-tokens'),
request.body,
)
} }
} }

View file

@ -2,11 +2,11 @@ import { Request, Response } from 'express'
import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils'
import { inject } from 'inversify' import { inject } from 'inversify'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
@controller('/v1') @controller('/v1')
export class InvoicesController extends BaseHttpController { export class InvoicesController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) {
super() super()
} }

View file

@ -2,26 +2,45 @@ import { Request, Response } from 'express'
import { inject } from 'inversify' import { inject } from 'inversify'
import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/items', TYPES.AuthMiddleware) @controller('/v1/items', TYPES.AuthMiddleware)
export class ItemsController extends BaseHttpController { export class ItemsController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpPost('/') @httpPost('/')
async sync(request: Request, response: Response): Promise<void> { async sync(request: Request, response: Response): Promise<void> {
await this.httpService.callSyncingServer(request, response, 'items/sync', request.body) await this.httpService.callSyncingServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'items/sync'),
request.body,
)
} }
@httpPost('/check-integrity') @httpPost('/check-integrity')
async checkIntegrity(request: Request, response: Response): Promise<void> { async checkIntegrity(request: Request, response: Response): Promise<void> {
await this.httpService.callSyncingServer(request, response, 'items/check-integrity', request.body) await this.httpService.callSyncingServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'items/check-integrity'),
request.body,
)
} }
@httpGet('/:uuid') @httpGet('/:uuid')
async getItem(request: Request, response: Response): Promise<void> { async getItem(request: Request, response: Response): Promise<void> {
await this.httpService.callSyncingServer(request, response, `items/${request.params.uuid}`, request.body) await this.httpService.callSyncingServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'items/:uuid', request.params.uuid),
request.body,
)
} }
} }

View file

@ -3,22 +3,36 @@ import { inject } from 'inversify'
import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/offline') @controller('/v1/offline')
export class OfflineController extends BaseHttpController { export class OfflineController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpGet('/features') @httpGet('/features')
async getOfflineFeatures(request: Request, response: Response): Promise<void> { async getOfflineFeatures(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'offline/features', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'offline/features'),
request.body,
)
} }
@httpPost('/subscription-tokens') @httpPost('/subscription-tokens')
async createOfflineSubscriptionToken(request: Request, response: Response): Promise<void> { async createOfflineSubscriptionToken(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'offline/subscription-tokens', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'offline/subscription-tokens'),
request.body,
)
} }
@httpPost('/payments/stripe-setup-intent') @httpPost('/payments/stripe-setup-intent')

View file

@ -2,11 +2,11 @@ import { Request, Response } from 'express'
import { inject } from 'inversify' import { inject } from 'inversify'
import { all, BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils' import { all, BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
@controller('/v1') @controller('/v1')
export class PaymentsController extends BaseHttpController { export class PaymentsController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) {
super() super()
} }

View file

@ -2,33 +2,55 @@ import { Request, Response } from 'express'
import { inject } from 'inversify' import { inject } from 'inversify'
import { BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/sessions') @controller('/v1/sessions')
export class SessionsController extends BaseHttpController { export class SessionsController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpGet('/', TYPES.AuthMiddleware) @httpGet('/', TYPES.AuthMiddleware)
async getSessions(request: Request, response: Response): Promise<void> { async getSessions(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'sessions') await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'sessions'),
)
} }
@httpDelete('/:uuid', TYPES.AuthMiddleware) @httpDelete('/:uuid', TYPES.AuthMiddleware)
async deleteSession(request: Request, response: Response): Promise<void> { async deleteSession(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'session', { await this.httpService.callAuthServer(
uuid: request.params.uuid, request,
}) response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('DELETE', 'session'),
{
uuid: request.params.uuid,
},
)
} }
@httpDelete('/', TYPES.AuthMiddleware) @httpDelete('/', TYPES.AuthMiddleware)
async deleteSessions(request: Request, response: Response): Promise<void> { async deleteSessions(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'session/all') await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('DELETE', 'session/all'),
)
} }
@httpPost('/refresh') @httpPost('/refresh')
async refreshSession(request: Request, response: Response): Promise<void> { async refreshSession(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'session/refresh', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'session/refresh'),
request.body,
)
} }
} }

View file

@ -3,31 +3,61 @@ import { inject } from 'inversify'
import { BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/subscription-invites') @controller('/v1/subscription-invites')
export class SubscriptionInvitesController extends BaseHttpController { export class SubscriptionInvitesController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpPost('/', TYPES.AuthMiddleware) @httpPost('/', TYPES.AuthMiddleware)
async inviteToSubscriptionSharing(request: Request, response: Response): Promise<void> { async inviteToSubscriptionSharing(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'subscription-invites', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'subscription-invites'),
request.body,
)
} }
@httpGet('/', TYPES.AuthMiddleware) @httpGet('/', TYPES.AuthMiddleware)
async listInvites(request: Request, response: Response): Promise<void> { async listInvites(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'subscription-invites', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'subscription-invites'),
request.body,
)
} }
@httpDelete('/:inviteUuid', TYPES.AuthMiddleware) @httpDelete('/:inviteUuid', TYPES.AuthMiddleware)
async cancelSubscriptionSharing(request: Request, response: Response): Promise<void> { async cancelSubscriptionSharing(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `subscription-invites/${request.params.inviteUuid}`) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'DELETE',
'subscription-invites/:inviteUuid',
request.params.inviteUuid,
),
)
} }
@httpPost('/:inviteUuid/accept', TYPES.AuthMiddleware) @httpPost('/:inviteUuid/accept', TYPES.AuthMiddleware)
async acceptInvite(request: Request, response: Response): Promise<void> { async acceptInvite(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `subscription-invites/${request.params.inviteUuid}/accept`) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'POST',
'subscription-invites/:inviteUuid/accept',
request.params.inviteUuid,
),
)
} }
} }

View file

@ -3,16 +3,25 @@ import { inject } from 'inversify'
import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/subscription-tokens') @controller('/v1/subscription-tokens')
export class TokensController extends BaseHttpController { export class TokensController extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpPost('/', TYPES.AuthMiddleware) @httpPost('/', TYPES.AuthMiddleware)
async createToken(request: Request, response: Response): Promise<void> { async createToken(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'subscription-tokens', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'subscription-tokens'),
request.body,
)
} }
} }

View file

@ -13,13 +13,15 @@ import {
} from 'inversify-express-utils' } from 'inversify-express-utils'
import { Logger } from 'winston' import { Logger } from 'winston'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { TokenAuthenticationMethod } from '../TokenAuthenticationMethod' import { TokenAuthenticationMethod } from '../TokenAuthenticationMethod'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/users') @controller('/v1/users')
export class UsersController extends BaseHttpController { export class UsersController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.HTTPService) private httpService: HttpServiceInterface, @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Logger) private logger: Logger,
) { ) {
super() super()
@ -37,7 +39,12 @@ export class UsersController extends BaseHttpController {
@httpPatch('/:userId', TYPES.AuthMiddleware) @httpPatch('/:userId', TYPES.AuthMiddleware)
async updateUser(request: Request, response: Response): Promise<void> { async updateUser(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `users/${request.params.userId}`, request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('PATCH', 'users/:userId', request.params.userId),
request.body,
)
} }
@httpPut('/:userUuid/password', TYPES.AuthMiddleware) @httpPut('/:userUuid/password', TYPES.AuthMiddleware)
@ -49,7 +56,11 @@ export class UsersController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
`users/${request.params.userUuid}/attributes/credentials`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'PUT',
'users/:userUuid/attributes/credentials',
request.params.userUuid,
),
request.body, request.body,
) )
} }
@ -59,14 +70,22 @@ export class UsersController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
`users/${request.params.userUuid}/attributes/credentials`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'PUT',
'users/:userUuid/attributes/credentials',
request.params.userUuid,
),
request.body, request.body,
) )
} }
@httpGet('/:userId/params', TYPES.AuthMiddleware) @httpGet('/:userId/params', TYPES.AuthMiddleware)
async getKeyParams(request: Request, response: Response): Promise<void> { async getKeyParams(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/params') await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'auth/params'),
)
} }
@all('/:userId/mfa', TYPES.AuthMiddleware) @all('/:userId/mfa', TYPES.AuthMiddleware)
@ -76,22 +95,49 @@ export class UsersController extends BaseHttpController {
@httpPost('/:userUuid/integrations/listed', TYPES.AuthMiddleware) @httpPost('/:userUuid/integrations/listed', TYPES.AuthMiddleware)
async createListedAccount(request: Request, response: Response): Promise<void> { async createListedAccount(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'listed', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'listed'),
request.body,
)
} }
@httpPost('/') @httpPost('/')
async register(request: Request, response: Response): Promise<void> { async register(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth'),
request.body,
)
} }
@httpGet('/:userUuid/settings', TYPES.AuthMiddleware) @httpGet('/:userUuid/settings', TYPES.AuthMiddleware)
async listSettings(request: Request, response: Response): Promise<void> { async listSettings(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/settings`) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'users/:userUuid/settings',
request.params.userUuid,
),
)
} }
@httpPut('/:userUuid/settings', TYPES.AuthMiddleware) @httpPut('/:userUuid/settings', TYPES.AuthMiddleware)
async putSetting(request: Request, response: Response): Promise<void> { async putSetting(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/settings`, request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'PUT',
'users/:userUuid/settings',
request.params.userUuid,
),
request.body,
)
} }
@httpGet('/:userUuid/settings/:settingName', TYPES.AuthMiddleware) @httpGet('/:userUuid/settings/:settingName', TYPES.AuthMiddleware)
@ -99,7 +145,12 @@ export class UsersController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
`users/${request.params.userUuid}/settings/${request.params.settingName}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'users/:userUuid/settings/:settingName',
request.params.userUuid,
request.params.settingName,
),
) )
} }
@ -108,7 +159,12 @@ export class UsersController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
`users/${request.params.userUuid}/settings/${request.params.settingName}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'DELETE',
'users/:userUuid/settings/:settingName',
request.params.userUuid,
request.params.settingName,
),
request.body, request.body,
) )
} }
@ -118,29 +174,62 @@ export class UsersController extends BaseHttpController {
await this.httpService.callAuthServer( await this.httpService.callAuthServer(
request, request,
response, response,
`users/${request.params.userUuid}/subscription-settings/${request.params.subscriptionSettingName}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'users/:userUuid/subscription-settings/:subscriptionSettingName',
request.params.userUuid,
request.params.subscriptionSettingName,
),
) )
} }
@httpGet('/:userUuid/features', TYPES.AuthMiddleware) @httpGet('/:userUuid/features', TYPES.AuthMiddleware)
async getFeatures(request: Request, response: Response): Promise<void> { async getFeatures(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/features`) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'users/:userUuid/features',
request.params.userUuid,
),
)
} }
@httpGet('/:userUuid/subscription', TYPES.AuthMiddleware) @httpGet('/:userUuid/subscription', TYPES.AuthMiddleware)
async getSubscription(request: Request, response: Response): Promise<void> { async getSubscription(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/subscription`) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'users/:userUuid/subscription',
request.params.userUuid,
),
)
} }
@httpGet('/subscription', TYPES.SubscriptionTokenAuthMiddleware) @httpGet('/subscription', TYPES.SubscriptionTokenAuthMiddleware)
async getSubscriptionBySubscriptionToken(request: Request, response: Response): Promise<void> { async getSubscriptionBySubscriptionToken(request: Request, response: Response): Promise<void> {
if (response.locals.tokenAuthenticationMethod === TokenAuthenticationMethod.OfflineSubscriptionToken) { if (response.locals.tokenAuthenticationMethod === TokenAuthenticationMethod.OfflineSubscriptionToken) {
await this.httpService.callAuthServer(request, response, 'offline/users/subscription') await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'offline/users/subscription'),
)
return return
} }
await this.httpService.callAuthServer(request, response, `users/${response.locals.userUuid}/subscription`) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'users/:userUuid/subscription',
response.locals.userUuid,
),
)
} }
@httpDelete('/:userUuid', TYPES.AuthMiddleware) @httpDelete('/:userUuid', TYPES.AuthMiddleware)
@ -150,6 +239,15 @@ export class UsersController extends BaseHttpController {
@httpPost('/:userUuid/requests', TYPES.AuthMiddleware) @httpPost('/:userUuid/requests', TYPES.AuthMiddleware)
async submitRequest(request: Request, response: Response): Promise<void> { async submitRequest(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/requests`, request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'POST',
'users/:userUuid/requests',
request.params.userUuid,
),
request.body,
)
} }
} }

View file

@ -4,12 +4,14 @@ import { BaseHttpController, controller, httpDelete, httpPost } from 'inversify-
import { Logger } from 'winston' import { Logger } from 'winston'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v1/sockets') @controller('/v1/sockets')
export class WebSocketsController extends BaseHttpController { export class WebSocketsController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.HTTPService) private httpService: HttpServiceInterface, @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Logger) private logger: Logger,
) { ) {
super() super()
@ -17,7 +19,12 @@ export class WebSocketsController extends BaseHttpController {
@httpPost('/tokens', TYPES.AuthMiddleware) @httpPost('/tokens', TYPES.AuthMiddleware)
async createWebSocketConnectionToken(request: Request, response: Response): Promise<void> { async createWebSocketConnectionToken(request: Request, response: Response): Promise<void> {
await this.httpService.callWebSocketServer(request, response, 'sockets/tokens', request.body) await this.httpService.callWebSocketServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'sockets/tokens'),
request.body,
)
} }
@httpPost('/connections', TYPES.WebSocketAuthMiddleware) @httpPost('/connections', TYPES.WebSocketAuthMiddleware)
@ -33,7 +40,11 @@ export class WebSocketsController extends BaseHttpController {
await this.httpService.callWebSocketServer( await this.httpService.callWebSocketServer(
request, request,
response, response,
`sockets/connections/${request.headers.connectionid}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'POST',
'sockets/connections/:connectionId',
request.headers.connectionid as string,
),
request.body, request.body,
) )
} }
@ -51,7 +62,11 @@ export class WebSocketsController extends BaseHttpController {
await this.httpService.callWebSocketServer( await this.httpService.callWebSocketServer(
request, request,
response, response,
`sockets/connections/${request.headers.connectionid}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'DELETE',
'sockets/connections/:connectionId',
request.headers.connectionid as string,
),
request.body, request.body,
) )
} }

View file

@ -3,21 +3,35 @@ import { inject } from 'inversify'
import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v2') @controller('/v2')
export class ActionsControllerV2 extends BaseHttpController { export class ActionsControllerV2 extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpPost('/login') @httpPost('/login')
async login(request: Request, response: Response): Promise<void> { async login(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/pkce_sign_in', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/pkce_sign_in'),
request.body,
)
} }
@httpPost('/login-params') @httpPost('/login-params')
async loginParams(request: Request, response: Response): Promise<void> { async loginParams(request: Request, response: Response): Promise<void> {
await this.httpService.callAuthServer(request, response, 'auth/pkce_params', request.body) await this.httpService.callAuthServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/pkce_params'),
request.body,
)
} }
} }

View file

@ -2,11 +2,11 @@ import { Request, Response } from 'express'
import { BaseHttpController, controller, httpDelete, httpGet, httpPatch, httpPost } from 'inversify-express-utils' import { BaseHttpController, controller, httpDelete, httpGet, httpPatch, httpPost } from 'inversify-express-utils'
import { inject } from 'inversify' import { inject } from 'inversify'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
@controller('/v2') @controller('/v2')
export class PaymentsControllerV2 extends BaseHttpController { export class PaymentsControllerV2 extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) {
super() super()
} }

View file

@ -3,17 +3,29 @@ import { inject } from 'inversify'
import { BaseHttpController, controller, httpDelete, httpGet } from 'inversify-express-utils' import { BaseHttpController, controller, httpDelete, httpGet } from 'inversify-express-utils'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface'
import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface'
@controller('/v2/items/:itemUuid/revisions', TYPES.AuthMiddleware) @controller('/v2/items/:itemUuid/revisions', TYPES.AuthMiddleware)
export class RevisionsControllerV2 extends BaseHttpController { export class RevisionsControllerV2 extends BaseHttpController {
constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { constructor(
@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface,
@inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface,
) {
super() super()
} }
@httpGet('/') @httpGet('/')
async getRevisions(request: Request, response: Response): Promise<void> { async getRevisions(request: Request, response: Response): Promise<void> {
await this.httpService.callRevisionsServer(request, response, `items/${request.params.itemUuid}/revisions`) await this.httpService.callRevisionsServer(
request,
response,
this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'items/:itemUuid/revisions',
request.params.itemUuid,
),
)
} }
@httpGet('/:id') @httpGet('/:id')
@ -21,7 +33,12 @@ export class RevisionsControllerV2 extends BaseHttpController {
await this.httpService.callRevisionsServer( await this.httpService.callRevisionsServer(
request, request,
response, response,
`items/${request.params.itemUuid}/revisions/${request.params.id}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'GET',
'items/:itemUuid/revisions/:id',
request.params.itemUuid,
request.params.id,
),
) )
} }
@ -30,7 +47,12 @@ export class RevisionsControllerV2 extends BaseHttpController {
await this.httpService.callRevisionsServer( await this.httpService.callRevisionsServer(
request, request,
response, response,
`items/${request.params.itemUuid}/revisions/${request.params.id}`, this.endpointResolver.resolveEndpointOrMethodIdentifier(
'DELETE',
'items/:itemUuid/revisions/:id',
request.params.itemUuid,
request.params.id,
),
) )
} }
} }

View file

@ -1,2 +0,0 @@
export * from './InMemory/InMemoryCrossServiceTokenCache'
export * from './Redis/RedisCrossServiceTokenCache'

View file

@ -6,10 +6,10 @@ import { Logger } from 'winston'
import { TYPES } from '../../Bootstrap/Types' import { TYPES } from '../../Bootstrap/Types'
import { CrossServiceTokenCacheInterface } from '../Cache/CrossServiceTokenCacheInterface' import { CrossServiceTokenCacheInterface } from '../Cache/CrossServiceTokenCacheInterface'
import { HttpServiceInterface } from './HttpServiceInterface' import { ServiceProxyInterface } from './ServiceProxyInterface'
@injectable() @injectable()
export class HttpService implements HttpServiceInterface { export class HttpServiceProxy implements ServiceProxyInterface {
constructor( constructor(
@inject(TYPES.HTTPClient) private httpClient: AxiosInstance, @inject(TYPES.HTTPClient) private httpClient: AxiosInstance,
@inject(TYPES.AUTH_SERVER_URL) private authServerUrl: string, @inject(TYPES.AUTH_SERVER_URL) private authServerUrl: string,
@ -27,16 +27,16 @@ export class HttpService implements HttpServiceInterface {
async callSyncingServer( async callSyncingServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
await this.callServer(this.syncingServerJsUrl, request, response, endpoint, payload) await this.callServer(this.syncingServerJsUrl, request, response, endpointOrMethodIdentifier, payload)
} }
async callRevisionsServer( async callRevisionsServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
if (!this.revisionsServerUrl) { if (!this.revisionsServerUrl) {
@ -44,31 +44,37 @@ export class HttpService implements HttpServiceInterface {
return return
} }
await this.callServer(this.revisionsServerUrl, request, response, endpoint, payload) await this.callServer(this.revisionsServerUrl, request, response, endpointOrMethodIdentifier, payload)
} }
async callLegacySyncingServer( async callLegacySyncingServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
await this.callServerWithLegacyFormat(this.syncingServerJsUrl, request, response, endpoint, payload) await this.callServerWithLegacyFormat(
this.syncingServerJsUrl,
request,
response,
endpointOrMethodIdentifier,
payload,
)
} }
async callAuthServer( async callAuthServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
await this.callServer(this.authServerUrl, request, response, endpoint, payload) await this.callServer(this.authServerUrl, request, response, endpointOrMethodIdentifier, payload)
} }
async callEmailServer( async callEmailServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
if (!this.emailServerUrl) { if (!this.emailServerUrl) {
@ -77,13 +83,13 @@ export class HttpService implements HttpServiceInterface {
return return
} }
await this.callServer(this.emailServerUrl, request, response, endpoint, payload) await this.callServer(this.emailServerUrl, request, response, endpointOrMethodIdentifier, payload)
} }
async callWebSocketServer( async callWebSocketServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
if (!this.webSocketServerUrl) { if (!this.webSocketServerUrl) {
@ -92,13 +98,13 @@ export class HttpService implements HttpServiceInterface {
return return
} }
await this.callServer(this.webSocketServerUrl, request, response, endpoint, payload) await this.callServer(this.webSocketServerUrl, request, response, endpointOrMethodIdentifier, payload)
} }
async callPaymentsServer( async callPaymentsServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
if (!this.paymentsServerUrl) { if (!this.paymentsServerUrl) {
@ -106,23 +112,29 @@ export class HttpService implements HttpServiceInterface {
return return
} }
await this.callServerWithLegacyFormat(this.paymentsServerUrl, request, response, endpoint, payload) await this.callServerWithLegacyFormat(
this.paymentsServerUrl,
request,
response,
endpointOrMethodIdentifier,
payload,
)
} }
async callAuthServerWithLegacyFormat( async callAuthServerWithLegacyFormat(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
await this.callServerWithLegacyFormat(this.authServerUrl, request, response, endpoint, payload) await this.callServerWithLegacyFormat(this.authServerUrl, request, response, endpointOrMethodIdentifier, payload)
} }
private async getServerResponse( private async getServerResponse(
serverUrl: string, serverUrl: string,
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<AxiosResponse | undefined> { ): Promise<AxiosResponse | undefined> {
try { try {
@ -142,7 +154,7 @@ export class HttpService implements HttpServiceInterface {
headers['X-Auth-Offline-Token'] = response.locals.offlineAuthToken headers['X-Auth-Offline-Token'] = response.locals.offlineAuthToken
} }
this.logger.debug(`Calling [${request.method}] ${serverUrl}/${endpoint}, this.logger.debug(`Calling [${request.method}] ${serverUrl}/${endpointOrMethodIdentifier},
headers: ${JSON.stringify(headers)}, headers: ${JSON.stringify(headers)},
query: ${JSON.stringify(request.query)}, query: ${JSON.stringify(request.query)},
payload: ${JSON.stringify(payload)}`) payload: ${JSON.stringify(payload)}`)
@ -150,7 +162,7 @@ export class HttpService implements HttpServiceInterface {
const serviceResponse = await this.httpClient.request({ const serviceResponse = await this.httpClient.request({
method: request.method as Method, method: request.method as Method,
headers, headers,
url: `${serverUrl}/${endpoint}`, url: `${serverUrl}/${endpointOrMethodIdentifier}`,
data: this.getRequestData(payload), data: this.getRequestData(payload),
maxContentLength: Infinity, maxContentLength: Infinity,
maxBodyLength: Infinity, maxBodyLength: Infinity,
@ -172,7 +184,9 @@ export class HttpService implements HttpServiceInterface {
? JSON.stringify((error as AxiosError).response?.data) ? JSON.stringify((error as AxiosError).response?.data)
: (error as Error).message : (error as Error).message
this.logger.error(`Could not pass the request to ${serverUrl}/${endpoint} on underlying service: ${errorMessage}`) this.logger.error(
`Could not pass the request to ${serverUrl}/${endpointOrMethodIdentifier} on underlying service: ${errorMessage}`,
)
this.logger.debug('Response error: %O', (error as AxiosError).response ?? error) this.logger.debug('Response error: %O', (error as AxiosError).response ?? error)
@ -195,10 +209,16 @@ export class HttpService implements HttpServiceInterface {
serverUrl: string, serverUrl: string,
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
const serviceResponse = await this.getServerResponse(serverUrl, request, response, endpoint, payload) const serviceResponse = await this.getServerResponse(
serverUrl,
request,
response,
endpointOrMethodIdentifier,
payload,
)
this.logger.debug(`Response from underlying server: ${JSON.stringify(serviceResponse?.data)}, this.logger.debug(`Response from underlying server: ${JSON.stringify(serviceResponse?.data)},
headers: ${JSON.stringify(serviceResponse?.headers)}`) headers: ${JSON.stringify(serviceResponse?.headers)}`)
@ -233,10 +253,16 @@ export class HttpService implements HttpServiceInterface {
serverUrl: string, serverUrl: string,
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> { ): Promise<void> {
const serviceResponse = await this.getServerResponse(serverUrl, request, response, endpoint, payload) const serviceResponse = await this.getServerResponse(
serverUrl,
request,
response,
endpointOrMethodIdentifier,
payload,
)
if (!serviceResponse) { if (!serviceResponse) {
return return

View file

@ -1,52 +1,52 @@
import { Request, Response } from 'express' import { Request, Response } from 'express'
export interface HttpServiceInterface { export interface ServiceProxyInterface {
callEmailServer( callEmailServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
callAuthServer( callAuthServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
callAuthServerWithLegacyFormat( callAuthServerWithLegacyFormat(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
callRevisionsServer( callRevisionsServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
callSyncingServer( callSyncingServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
callLegacySyncingServer( callLegacySyncingServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
callPaymentsServer( callPaymentsServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
callWebSocketServer( callWebSocketServer(
request: Request, request: Request,
response: Response, response: Response,
endpoint: string, endpointOrMethodIdentifier: string,
payload?: Record<string, unknown> | string, payload?: Record<string, unknown> | string,
): Promise<void> ): Promise<void>
} }

View file

@ -0,0 +1,74 @@
import { Request, Response } from 'express'
import { ServiceProxyInterface } from '../Http/ServiceProxyInterface'
import { ServiceContainerInterface, ServiceIdentifier } from '@standardnotes/domain-core'
export class DirectCallServiceProxy implements ServiceProxyInterface {
constructor(private serviceContainer: ServiceContainerInterface) {}
async callEmailServer(_request: Request, _response: Response, _endpointOrMethodIdentifier: string): Promise<void> {
throw new Error('Email server is not available.')
}
async callAuthServer(request: never, response: never, endpointOrMethodIdentifier: string): Promise<void> {
const authService = this.serviceContainer.get(ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue())
if (!authService) {
throw new Error('Auth service not found')
}
const serviceResponse = (await authService.handleRequest(request, response, endpointOrMethodIdentifier)) as {
statusCode: number
json: Record<string, unknown>
}
void (response as Response).status(serviceResponse.statusCode).send(serviceResponse.json)
}
async callAuthServerWithLegacyFormat(
_request: Request,
_response: Response,
_endpointOrMethodIdentifier: string,
): Promise<void> {
throw new Error('Legacy auth endpoints are no longer available.')
}
async callRevisionsServer(request: never, response: never, endpointOrMethodIdentifier: string): Promise<void> {
const service = this.serviceContainer.get(ServiceIdentifier.create(ServiceIdentifier.NAMES.Revisions).getValue())
if (!service) {
throw new Error('Revisions service not found')
}
await service.handleRequest(request, response, endpointOrMethodIdentifier)
}
async callSyncingServer(request: never, response: never, endpointOrMethodIdentifier: string): Promise<void> {
const service = this.serviceContainer.get(
ServiceIdentifier.create(ServiceIdentifier.NAMES.SyncingServer).getValue(),
)
if (!service) {
throw new Error('Syncing service not found')
}
await service.handleRequest(request, response, endpointOrMethodIdentifier)
}
async callLegacySyncingServer(
_request: Request,
_response: Response,
_endpointOrMethodIdentifier: string,
): Promise<void> {
throw new Error('Legacy syncing server endpoints are no longer available.')
}
async callPaymentsServer(_request: Request, _response: Response, _endpointOrMethodIdentifier: string): Promise<void> {
throw new Error('Payments server is not available.')
}
async callWebSocketServer(
_request: Request,
_response: Response,
_endpointOrMethodIdentifier: string,
): Promise<void> {
throw new Error('Websockets server is not available.')
}
}

View file

@ -0,0 +1,70 @@
import { EndpointResolverInterface } from './EndpointResolverInterface'
export class EndpointResolver implements EndpointResolverInterface {
constructor(private isConfiguredForHomeServer: boolean) {}
private readonly endpointToIdentifierMap: Map<string, string> = new Map([
// Actions Controller
['[POST]:auth/sign_in', 'auth.signIn'],
['[GET]:auth/params', 'auth.params'],
['[POST]:auth/sign_out', 'auth.signOut'],
['[POST]:auth/recovery/codes', 'auth.generateRecoveryCodes'],
['[POST]:auth/recovery/login', 'auth.signInWithRecoveryCodes'],
['[POST]:auth/recovery/params', 'auth.recoveryKeyParams'],
// Authenticators Controller
['[DELETE]:authenticators/:authenticatorId', 'auth.authenticators.delete'],
['[GET]:authenticators/', 'auth.authenticators.list'],
['[GET]:authenticators/generate-registration-options', 'auth.authenticators.generateRegistrationOptions'],
['[POST]:authenticators/generate-authentication-options', 'auth.authenticators.generateAuthenticationOptions'],
['[POST]:authenticators/verify-registration', 'auth.authenticators.verifyRegistrationResponse'],
// Files Controller
['[POST]:valet-tokens', 'auth.valet-tokens.create'],
// Offline Controller
['[GET]:offline/features', 'auth.offline.features'],
['[POST]:offline/subscription-tokens', 'auth.offline.subscriptionTokens.create'],
// Sessions Controller
['[GET]:sessions', 'auth.sessions.list'],
['[DELETE]:session', 'auth.sessions.delete'],
['[DELETE]:session/all', 'auth.sessions.deleteAll'],
['[POST]:session/refresh', 'auth.sessions.refresh'],
// Subscription Invites Controller
['[POST]:subscription-invites', 'auth.subscriptionInvites.create'],
['[GET]:subscription-invites', 'auth.subscriptionInvites.list'],
['[DELETE]:subscription-invites/:inviteUuid', 'auth.subscriptionInvites.delete'],
['[POST]:subscription-invites/:inviteUuid/accept', 'auth.subscriptionInvites.accept'],
// Tokens Controller
['[POST]:subscription-tokens', 'auth.subscription-tokens.create'],
// Users Controller
['[PATCH]:users/:userId', 'auth.users.update'],
['[PUT]:users/:userUuid/attributes/credentials', 'auth.users.updateCredentials'],
['[PUT]:auth/params', 'auth.users.getKeyParams'],
['[POST]:listed', 'auth.users.createListedAccount'],
['[POST]:auth', 'auth.users.register'],
['[GET]:users/:userUuid/settings', 'auth.users.getSettings'],
['[PUT]:users/:userUuid/settings', 'auth.users.updateSetting'],
['[GET]:users/:userUuid/settings/:settingName', 'auth.users.getSetting'],
['[DELETE]:users/:userUuid/settings/:settingName', 'auth.users.deleteSetting'],
['[GET]:users/:userUuid/subscription-settings/:subscriptionSettingName', 'auth.users.getSubscriptionSetting'],
['[GET]:users/:userUuid/features', 'auth.users.getFeatures'],
['[GET]:users/:userUuid/subscription', 'auth.users.getSubscription'],
['[GET]:offline/users/subscription', 'auth.users.getOfflineSubscriptionByToken'],
['[POST]:users/:userUuid/requests', 'auth.users.createRequest'],
])
resolveEndpointOrMethodIdentifier(method: string, endpoint: string, ...params: string[]): string {
if (!this.isConfiguredForHomeServer) {
if (params.length > 0) {
return params.reduce((acc, param) => acc.replace(/:[a-zA-Z0-9]+/, param), endpoint)
}
return endpoint
}
const identifier = this.endpointToIdentifierMap.get(`[${method}]:${endpoint}`)
if (!identifier) {
throw new Error(`Endpoint ${endpoint} not found`)
}
return identifier
}
}

View file

@ -0,0 +1,3 @@
export interface EndpointResolverInterface {
resolveEndpointOrMethodIdentifier(method: string, endpoint: string, ...params: string[]): string
}

View file

@ -1,3 +0,0 @@
export * from './Cache/CrossServiceTokenCacheInterface'
export * from './Http/HttpService'
export * from './Http/HttpServiceInterface'

View file

@ -1,4 +1,2 @@
export * from './Bootstrap' export * from './Bootstrap'
export * from './Controller' export * from './Controller'
export * from './Infra'
export * from './Service'

View file

@ -84,14 +84,14 @@ void container.load().then((container) => {
const env: Env = new Env() const env: Env = new Env()
env.load() env.load()
const logger: Logger = container.get(TYPES.Logger) const logger: Logger = container.get(TYPES.Auth_Logger)
logger.info(`Starting ${backupFrequency} ${backupProvider} backup requesting...`) logger.info(`Starting ${backupFrequency} ${backupProvider} backup requesting...`)
const settingRepository: SettingRepositoryInterface = container.get(TYPES.SettingRepository) const settingRepository: SettingRepositoryInterface = container.get(TYPES.Auth_SettingRepository)
const roleService: RoleServiceInterface = container.get(TYPES.RoleService) const roleService: RoleServiceInterface = container.get(TYPES.Auth_RoleService)
const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.DomainEventFactory) const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.Auth_DomainEventFactory)
const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.DomainEventPublisher) const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.Auth_DomainEventPublisher)
Promise.resolve(requestBackups(settingRepository, roleService, domainEventFactory, domainEventPublisher)) Promise.resolve(requestBackups(settingRepository, roleService, domainEventFactory, domainEventPublisher))
.then(() => { .then(() => {

View file

@ -25,12 +25,12 @@ void container.load().then((container) => {
const env: Env = new Env() const env: Env = new Env()
env.load() env.load()
const logger: Logger = container.get(TYPES.Logger) const logger: Logger = container.get(TYPES.Auth_Logger)
logger.info('Starting sessions and session traces cleanup') logger.info('Starting sessions and session traces cleanup')
const cleanupSessionTraces: CleanupSessionTraces = container.get(TYPES.CleanupSessionTraces) const cleanupSessionTraces: CleanupSessionTraces = container.get(TYPES.Auth_CleanupSessionTraces)
const cleanupExpiredSessions: CleanupExpiredSessions = container.get(TYPES.CleanupExpiredSessions) const cleanupExpiredSessions: CleanupExpiredSessions = container.get(TYPES.Auth_CleanupExpiredSessions)
Promise.resolve(cleanup(cleanupSessionTraces, cleanupExpiredSessions)) Promise.resolve(cleanup(cleanupSessionTraces, cleanupExpiredSessions))
.then(() => { .then(() => {

View file

@ -44,7 +44,7 @@ void container.load().then((container) => {
server.setConfig((app) => { server.setConfig((app) => {
app.use((_request: Request, response: Response, next: NextFunction) => { app.use((_request: Request, response: Response, next: NextFunction) => {
response.setHeader('X-Auth-Version', container.get(TYPES.VERSION)) response.setHeader('X-Auth-Version', container.get(TYPES.Auth_VERSION))
next() next()
}) })
app.use(json()) app.use(json())
@ -52,7 +52,7 @@ void container.load().then((container) => {
app.use(cors()) app.use(cors())
}) })
const logger: winston.Logger = container.get(TYPES.Logger) const logger: winston.Logger = container.get(TYPES.Auth_Logger)
server.setErrorConfig((app) => { server.setErrorConfig((app) => {
app.use((error: Record<string, unknown>, _request: Request, response: Response, _next: NextFunction) => { app.use((error: Record<string, unknown>, _request: Request, response: Response, _next: NextFunction) => {

View file

@ -15,12 +15,12 @@ void container.load().then((container) => {
const env: Env = new Env() const env: Env = new Env()
env.load() env.load()
const logger: Logger = container.get(TYPES.Logger) const logger: Logger = container.get(TYPES.Auth_Logger)
logger.info('Starting session traces cleanup') logger.info('Starting session traces cleanup')
const persistStats: PersistStatistics = container.get(TYPES.PersistStatistics) const persistStats: PersistStatistics = container.get(TYPES.Auth_PersistStatistics)
const timer: TimerInterface = container.get(TYPES.Timer) const timer: TimerInterface = container.get(TYPES.Auth_Timer)
Promise.resolve( Promise.resolve(
persistStats.execute({ persistStats.execute({

View file

@ -72,15 +72,15 @@ void container.load().then((container) => {
const env: Env = new Env() const env: Env = new Env()
env.load() env.load()
const logger: Logger = container.get(TYPES.Logger) const logger: Logger = container.get(TYPES.Auth_Logger)
logger.info(`Starting email backup requesting for ${backupEmail} ...`) logger.info(`Starting email backup requesting for ${backupEmail} ...`)
const settingRepository: SettingRepositoryInterface = container.get(TYPES.SettingRepository) const settingRepository: SettingRepositoryInterface = container.get(TYPES.Auth_SettingRepository)
const userRepository: UserRepositoryInterface = container.get(TYPES.UserRepository) const userRepository: UserRepositoryInterface = container.get(TYPES.Auth_UserRepository)
const roleService: RoleServiceInterface = container.get(TYPES.RoleService) const roleService: RoleServiceInterface = container.get(TYPES.Auth_RoleService)
const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.DomainEventFactory) const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.Auth_DomainEventFactory)
const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.DomainEventPublisher) const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.Auth_DomainEventPublisher)
Promise.resolve( Promise.resolve(
requestBackups(userRepository, settingRepository, roleService, domainEventFactory, domainEventPublisher), requestBackups(userRepository, settingRepository, roleService, domainEventFactory, domainEventPublisher),

View file

@ -18,11 +18,13 @@ void container.load().then((container) => {
const env: Env = new Env() const env: Env = new Env()
env.load() env.load()
const logger: Logger = container.get(TYPES.Logger) const logger: Logger = container.get(TYPES.Auth_Logger)
logger.info('Starting worker...') logger.info('Starting worker...')
const subscriberFactory: DomainEventSubscriberFactoryInterface = container.get(TYPES.DomainEventSubscriberFactory) const subscriberFactory: DomainEventSubscriberFactoryInterface = container.get(
TYPES.Auth_DomainEventSubscriberFactory,
)
subscriberFactory.create().start() subscriberFactory.create().start()
setInterval(() => logger.info('Alive and kicking!'), 20 * 60 * 1000) setInterval(() => logger.info('Alive and kicking!'), 20 * 60 * 1000)

View file

@ -15,6 +15,7 @@
"setup:env": "cp .env.sample .env", "setup:env": "cp .env.sample .env",
"build": "tsc --build", "build": "tsc --build",
"lint": "eslint . --ext .ts", "lint": "eslint . --ext .ts",
"lint:fix": "eslint . --fix --ext .ts",
"pretest": "yarn lint && yarn build", "pretest": "yarn lint && yarn build",
"test": "jest --coverage --config=./jest.config.js --maxWorkers=50%", "test": "jest --coverage --config=./jest.config.js --maxWorkers=50%",
"start": "yarn node dist/bin/server.js", "start": "yarn node dist/bin/server.js",

File diff suppressed because it is too large Load diff

View file

@ -28,29 +28,6 @@ const maxQueryExecutionTime = env.get('DB_MAX_QUERY_EXECUTION_TIME', true)
? +env.get('DB_MAX_QUERY_EXECUTION_TIME', true) ? +env.get('DB_MAX_QUERY_EXECUTION_TIME', true)
: 45_000 : 45_000
const inReplicaMode = env.get('DB_REPLICA_HOST', true) ? true : false
const replicationConfig = {
master: {
host: env.get('DB_HOST'),
port: parseInt(env.get('DB_PORT')),
username: env.get('DB_USERNAME'),
password: env.get('DB_PASSWORD'),
database: env.get('DB_DATABASE'),
},
slaves: [
{
host: env.get('DB_REPLICA_HOST', true),
port: parseInt(env.get('DB_PORT')),
username: env.get('DB_USERNAME'),
password: env.get('DB_PASSWORD'),
database: env.get('DB_DATABASE'),
},
],
removeNodeErrorCount: 10,
restoreNodeTimeout: 5,
}
const commonDataSourceOptions = { const commonDataSourceOptions = {
maxQueryExecutionTime, maxQueryExecutionTime,
entities: [ entities: [
@ -71,29 +48,59 @@ const commonDataSourceOptions = {
TypeORMEmergencyAccessInvitation, TypeORMEmergencyAccessInvitation,
TypeORMCacheEntry, TypeORMCacheEntry,
], ],
migrations: [`dist/migrations/${isConfiguredForMySQL ? 'mysql' : 'sqlite'}/*.js`], migrations: [`${__dirname}/../../migrations/${isConfiguredForMySQL ? 'mysql' : 'sqlite'}/*.js`],
migrationsRun: true, migrationsRun: true,
logging: <LoggerOptions>env.get('DB_DEBUG_LEVEL'), logging: <LoggerOptions>env.get('DB_DEBUG_LEVEL', true) ?? 'info',
} }
const mySQLDataSourceOptions: MysqlConnectionOptions = { let dataSource: DataSource
...commonDataSourceOptions, if (isConfiguredForMySQL) {
type: 'mysql', const inReplicaMode = env.get('DB_REPLICA_HOST', true) ? true : false
charset: 'utf8mb4',
supportBigNumbers: true, const replicationConfig = {
bigNumberStrings: false, master: {
replication: inReplicaMode ? replicationConfig : undefined, host: env.get('DB_HOST'),
host: inReplicaMode ? undefined : env.get('DB_HOST'), port: parseInt(env.get('DB_PORT')),
port: inReplicaMode ? undefined : parseInt(env.get('DB_PORT')), username: env.get('DB_USERNAME'),
username: inReplicaMode ? undefined : env.get('DB_USERNAME'), password: env.get('DB_PASSWORD'),
password: inReplicaMode ? undefined : env.get('DB_PASSWORD'), database: env.get('DB_DATABASE'),
database: inReplicaMode ? undefined : env.get('DB_DATABASE'), },
slaves: [
{
host: env.get('DB_REPLICA_HOST', true),
port: parseInt(env.get('DB_PORT')),
username: env.get('DB_USERNAME'),
password: env.get('DB_PASSWORD'),
database: env.get('DB_DATABASE'),
},
],
removeNodeErrorCount: 10,
restoreNodeTimeout: 5,
}
const mySQLDataSourceOptions: MysqlConnectionOptions = {
...commonDataSourceOptions,
type: 'mysql',
charset: 'utf8mb4',
supportBigNumbers: true,
bigNumberStrings: false,
replication: inReplicaMode ? replicationConfig : undefined,
host: inReplicaMode ? undefined : env.get('DB_HOST'),
port: inReplicaMode ? undefined : parseInt(env.get('DB_PORT')),
username: inReplicaMode ? undefined : env.get('DB_USERNAME'),
password: inReplicaMode ? undefined : env.get('DB_PASSWORD'),
database: inReplicaMode ? undefined : env.get('DB_DATABASE'),
}
dataSource = new DataSource(mySQLDataSourceOptions)
} else {
const sqliteDataSourceOptions: SqliteConnectionOptions = {
...commonDataSourceOptions,
type: 'sqlite',
database: `data/${env.get('DB_DATABASE')}.sqlite`,
}
dataSource = new DataSource(sqliteDataSourceOptions)
} }
const sqliteDataSourceOptions: SqliteConnectionOptions = { export const AppDataSource = dataSource
...commonDataSourceOptions,
type: 'sqlite',
database: `data/${env.get('DB_DATABASE')}.sqlite`,
}
export const AppDataSource = new DataSource(isConfiguredForMySQL ? mySQLDataSourceOptions : sqliteDataSourceOptions)

View file

@ -0,0 +1,37 @@
import {
ControllerContainerInterface,
ServiceContainerInterface,
ServiceIdentifier,
ServiceInterface,
} from '@standardnotes/domain-core'
import { ContainerConfigLoader } from './Container'
export class Service implements ServiceInterface {
constructor(
private serviceContainer: ServiceContainerInterface,
private controllerContainer: ControllerContainerInterface,
) {
this.serviceContainer.register(ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue(), this)
}
async handleRequest(request: never, response: never, endpointOrMethodIdentifier: string): Promise<unknown> {
const method = this.controllerContainer.get(endpointOrMethodIdentifier)
if (!method) {
throw new Error(`Method ${endpointOrMethodIdentifier} not found`)
}
return method(request, response)
}
async getContainer(): Promise<unknown> {
const config = new ContainerConfigLoader()
return config.load(this.controllerContainer)
}
getId(): ServiceIdentifier {
return ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue()
}
}

View file

@ -1,217 +1,227 @@
const TYPES = { const TYPES = {
Logger: Symbol.for('Logger'), Auth_Logger: Symbol.for('Auth_Logger'),
Redis: Symbol.for('Redis'), Auth_Redis: Symbol.for('Auth_Redis'),
SNS: Symbol.for('SNS'), Auth_SNS: Symbol.for('Auth_SNS'),
SQS: Symbol.for('SQS'), Auth_SQS: Symbol.for('Auth_SQS'),
// Mapping // Mapping
SessionTracePersistenceMapper: Symbol.for('SessionTracePersistenceMapper'), Auth_SessionTracePersistenceMapper: Symbol.for('Auth_SessionTracePersistenceMapper'),
AuthenticatorChallengePersistenceMapper: Symbol.for('AuthenticatorChallengePersistenceMapper'), Auth_AuthenticatorChallengePersistenceMapper: Symbol.for('Auth_AuthenticatorChallengePersistenceMapper'),
AuthenticatorPersistenceMapper: Symbol.for('AuthenticatorPersistenceMapper'), Auth_AuthenticatorPersistenceMapper: Symbol.for('Auth_AuthenticatorPersistenceMapper'),
AuthenticatorHttpMapper: Symbol.for('AuthenticatorHttpMapper'), Auth_AuthenticatorHttpMapper: Symbol.for('Auth_AuthenticatorHttpMapper'),
CacheEntryPersistenceMapper: Symbol.for('CacheEntryPersistenceMapper'), Auth_CacheEntryPersistenceMapper: Symbol.for('Auth_CacheEntryPersistenceMapper'),
// Controller // Controller
AuthController: Symbol.for('AuthController'), Auth_ControllerContainer: Symbol.for('Auth_ControllerContainer'),
AuthenticatorsController: Symbol.for('AuthenticatorsController'), Auth_AuthController: Symbol.for('Auth_AuthController'),
SubscriptionInvitesController: Symbol.for('SubscriptionInvitesController'), Auth_AuthenticatorsController: Symbol.for('Auth_AuthenticatorsController'),
UserRequestsController: Symbol.for('UserRequestsController'), Auth_SubscriptionInvitesController: Symbol.for('Auth_SubscriptionInvitesController'),
Auth_UserRequestsController: Symbol.for('Auth_UserRequestsController'),
// Repositories // Repositories
UserRepository: Symbol.for('UserRepository'), Auth_UserRepository: Symbol.for('Auth_UserRepository'),
SessionRepository: Symbol.for('SessionRepository'), Auth_SessionRepository: Symbol.for('Auth_SessionRepository'),
EphemeralSessionRepository: Symbol.for('EphemeralSessionRepository'), Auth_EphemeralSessionRepository: Symbol.for('Auth_EphemeralSessionRepository'),
RevokedSessionRepository: Symbol.for('RevokedSessionRepository'), Auth_RevokedSessionRepository: Symbol.for('Auth_RevokedSessionRepository'),
SettingRepository: Symbol.for('SettingRepository'), Auth_SettingRepository: Symbol.for('Auth_SettingRepository'),
SubscriptionSettingRepository: Symbol.for('SubscriptionSettingRepository'), Auth_SubscriptionSettingRepository: Symbol.for('Auth_SubscriptionSettingRepository'),
OfflineSettingRepository: Symbol.for('OfflineSettingRepository'), Auth_OfflineSettingRepository: Symbol.for('Auth_OfflineSettingRepository'),
LockRepository: Symbol.for('LockRepository'), Auth_LockRepository: Symbol.for('Auth_LockRepository'),
RoleRepository: Symbol.for('RoleRepository'), Auth_RoleRepository: Symbol.for('Auth_RoleRepository'),
UserSubscriptionRepository: Symbol.for('UserSubscriptionRepository'), Auth_UserSubscriptionRepository: Symbol.for('Auth_UserSubscriptionRepository'),
OfflineUserSubscriptionRepository: Symbol.for('OfflineUserSubscriptionRepository'), Auth_OfflineUserSubscriptionRepository: Symbol.for('Auth_OfflineUserSubscriptionRepository'),
SubscriptionTokenRepository: Symbol.for('SubscriptionTokenRepository'), Auth_SubscriptionTokenRepository: Symbol.for('Auth_SubscriptionTokenRepository'),
OfflineSubscriptionTokenRepository: Symbol.for('OfflineSubscriptionTokenRepository'), Auth_OfflineSubscriptionTokenRepository: Symbol.for('Auth_OfflineSubscriptionTokenRepository'),
SharedSubscriptionInvitationRepository: Symbol.for('SharedSubscriptionInvitationRepository'), Auth_SharedSubscriptionInvitationRepository: Symbol.for('Auth_SharedSubscriptionInvitationRepository'),
PKCERepository: Symbol.for('PKCERepository'), Auth_PKCERepository: Symbol.for('Auth_PKCERepository'),
SessionTraceRepository: Symbol.for('SessionTraceRepository'), Auth_SessionTraceRepository: Symbol.for('Auth_SessionTraceRepository'),
AuthenticatorRepository: Symbol.for('AuthenticatorRepository'), Auth_AuthenticatorRepository: Symbol.for('Auth_AuthenticatorRepository'),
AuthenticatorChallengeRepository: Symbol.for('AuthenticatorChallengeRepository'), Auth_AuthenticatorChallengeRepository: Symbol.for('Auth_AuthenticatorChallengeRepository'),
CacheEntryRepository: Symbol.for('CacheEntryRepository'), Auth_CacheEntryRepository: Symbol.for('Auth_CacheEntryRepository'),
// ORM // ORM
ORMOfflineSettingRepository: Symbol.for('ORMOfflineSettingRepository'), Auth_ORMOfflineSettingRepository: Symbol.for('Auth_ORMOfflineSettingRepository'),
ORMOfflineUserSubscriptionRepository: Symbol.for('ORMOfflineUserSubscriptionRepository'), Auth_ORMOfflineUserSubscriptionRepository: Symbol.for('Auth_ORMOfflineUserSubscriptionRepository'),
ORMRevokedSessionRepository: Symbol.for('ORMRevokedSessionRepository'), Auth_ORMRevokedSessionRepository: Symbol.for('Auth_ORMRevokedSessionRepository'),
ORMRoleRepository: Symbol.for('ORMRoleRepository'), Auth_ORMRoleRepository: Symbol.for('Auth_ORMRoleRepository'),
ORMSessionRepository: Symbol.for('ORMSessionRepository'), Auth_ORMSessionRepository: Symbol.for('Auth_ORMSessionRepository'),
ORMSettingRepository: Symbol.for('ORMSettingRepository'), Auth_ORMSettingRepository: Symbol.for('Auth_ORMSettingRepository'),
ORMSharedSubscriptionInvitationRepository: Symbol.for('ORMSharedSubscriptionInvitationRepository'), Auth_ORMSharedSubscriptionInvitationRepository: Symbol.for('Auth_ORMSharedSubscriptionInvitationRepository'),
ORMSubscriptionSettingRepository: Symbol.for('ORMSubscriptionSettingRepository'), Auth_ORMSubscriptionSettingRepository: Symbol.for('Auth_ORMSubscriptionSettingRepository'),
ORMUserRepository: Symbol.for('ORMUserRepository'), Auth_ORMUserRepository: Symbol.for('Auth_ORMUserRepository'),
ORMUserSubscriptionRepository: Symbol.for('ORMUserSubscriptionRepository'), Auth_ORMUserSubscriptionRepository: Symbol.for('Auth_ORMUserSubscriptionRepository'),
ORMSessionTraceRepository: Symbol.for('ORMSessionTraceRepository'), Auth_ORMSessionTraceRepository: Symbol.for('Auth_ORMSessionTraceRepository'),
ORMAuthenticatorRepository: Symbol.for('ORMAuthenticatorRepository'), Auth_ORMAuthenticatorRepository: Symbol.for('Auth_ORMAuthenticatorRepository'),
ORMAuthenticatorChallengeRepository: Symbol.for('ORMAuthenticatorChallengeRepository'), Auth_ORMAuthenticatorChallengeRepository: Symbol.for('Auth_ORMAuthenticatorChallengeRepository'),
ORMCacheEntryRepository: Symbol.for('ORMCacheEntryRepository'), Auth_ORMCacheEntryRepository: Symbol.for('Auth_ORMCacheEntryRepository'),
// Middleware // Middleware
AuthMiddleware: Symbol.for('AuthMiddleware'), Auth_AuthMiddleware: Symbol.for('Auth_AuthMiddleware'),
ApiGatewayAuthMiddleware: Symbol.for('ApiGatewayAuthMiddleware'), Auth_ApiGatewayAuthMiddleware: Symbol.for('Auth_ApiGatewayAuthMiddleware'),
ApiGatewayOfflineAuthMiddleware: Symbol.for('ApiGatewayOfflineAuthMiddleware'), Auth_ApiGatewayOfflineAuthMiddleware: Symbol.for('Auth_ApiGatewayOfflineAuthMiddleware'),
OfflineUserAuthMiddleware: Symbol.for('OfflineUserAuthMiddleware'), Auth_OfflineUserAuthMiddleware: Symbol.for('Auth_OfflineUserAuthMiddleware'),
AuthMiddlewareWithoutResponse: Symbol.for('AuthMiddlewareWithoutResponse'), Auth_AuthMiddlewareWithoutResponse: Symbol.for('Auth_AuthMiddlewareWithoutResponse'),
LockMiddleware: Symbol.for('LockMiddleware'), Auth_LockMiddleware: Symbol.for('Auth_LockMiddleware'),
SessionMiddleware: Symbol.for('SessionMiddleware'), Auth_SessionMiddleware: Symbol.for('Auth_SessionMiddleware'),
// Projectors // Projectors
SessionProjector: Symbol.for('SessionProjector'), Auth_SessionProjector: Symbol.for('Auth_SessionProjector'),
UserProjector: Symbol.for('UserProjector'), Auth_UserProjector: Symbol.for('Auth_UserProjector'),
RoleProjector: Symbol.for('RoleProjector'), Auth_RoleProjector: Symbol.for('Auth_RoleProjector'),
PermissionProjector: Symbol.for('PermissionProjector'), Auth_PermissionProjector: Symbol.for('Auth_PermissionProjector'),
SettingProjector: Symbol.for('SettingProjector'), Auth_SettingProjector: Symbol.for('Auth_SettingProjector'),
SubscriptionSettingProjector: Symbol.for('SubscriptionSettingProjector'), Auth_SubscriptionSettingProjector: Symbol.for('Auth_SubscriptionSettingProjector'),
// Factories // Factories
SettingFactory: Symbol.for('SettingFactory'), Auth_SettingFactory: Symbol.for('Auth_SettingFactory'),
// env vars // env vars
JWT_SECRET: Symbol.for('JWT_SECRET'), Auth_JWT_SECRET: Symbol.for('Auth_JWT_SECRET'),
LEGACY_JWT_SECRET: Symbol.for('LEGACY_JWT_SECRET'), Auth_LEGACY_JWT_SECRET: Symbol.for('Auth_LEGACY_JWT_SECRET'),
AUTH_JWT_SECRET: Symbol.for('AUTH_JWT_SECRET'), Auth_AUTH_JWT_SECRET: Symbol.for('Auth_AUTH_JWT_SECRET'),
AUTH_JWT_TTL: Symbol.for('AUTH_JWT_TTL'), Auth_AUTH_JWT_TTL: Symbol.for('Auth_AUTH_JWT_TTL'),
VALET_TOKEN_SECRET: Symbol.for('VALET_TOKEN_SECRET'), Auth_VALET_TOKEN_SECRET: Symbol.for('Auth_VALET_TOKEN_SECRET'),
VALET_TOKEN_TTL: Symbol.for('VALET_TOKEN_TTL'), Auth_VALET_TOKEN_TTL: Symbol.for('Auth_VALET_TOKEN_TTL'),
WEB_SOCKET_CONNECTION_TOKEN_SECRET: Symbol.for('WEB_SOCKET_CONNECTION_TOKEN_SECRET'), Auth_WEB_SOCKET_CONNECTION_TOKEN_SECRET: Symbol.for('Auth_WEB_SOCKET_CONNECTION_TOKEN_SECRET'),
WEB_SOCKET_CONNECTION_TOKEN_TTL: Symbol.for('WEB_SOCKET_CONNECTION_TOKEN_TTL'), Auth_WEB_SOCKET_CONNECTION_TOKEN_TTL: Symbol.for('Auth_WEB_SOCKET_CONNECTION_TOKEN_TTL'),
ENCRYPTION_SERVER_KEY: Symbol.for('ENCRYPTION_SERVER_KEY'), Auth_ENCRYPTION_SERVER_KEY: Symbol.for('Auth_ENCRYPTION_SERVER_KEY'),
ACCESS_TOKEN_AGE: Symbol.for('ACCESS_TOKEN_AGE'), Auth_ACCESS_TOKEN_AGE: Symbol.for('Auth_ACCESS_TOKEN_AGE'),
REFRESH_TOKEN_AGE: Symbol.for('REFRESH_TOKEN_AGE'), Auth_REFRESH_TOKEN_AGE: Symbol.for('Auth_REFRESH_TOKEN_AGE'),
EPHEMERAL_SESSION_AGE: Symbol.for('EPHEMERAL_SESSION_AGE'), Auth_EPHEMERAL_SESSION_AGE: Symbol.for('Auth_EPHEMERAL_SESSION_AGE'),
MAX_LOGIN_ATTEMPTS: Symbol.for('MAX_LOGIN_ATTEMPTS'), Auth_MAX_LOGIN_ATTEMPTS: Symbol.for('Auth_MAX_LOGIN_ATTEMPTS'),
FAILED_LOGIN_LOCKOUT: Symbol.for('FAILED_LOGIN_LOCKOUT'), Auth_FAILED_LOGIN_LOCKOUT: Symbol.for('Auth_FAILED_LOGIN_LOCKOUT'),
PSEUDO_KEY_PARAMS_KEY: Symbol.for('PSEUDO_KEY_PARAMS_KEY'), Auth_PSEUDO_KEY_PARAMS_KEY: Symbol.for('Auth_PSEUDO_KEY_PARAMS_KEY'),
REDIS_URL: Symbol.for('REDIS_URL'), Auth_REDIS_URL: Symbol.for('Auth_REDIS_URL'),
DISABLE_USER_REGISTRATION: Symbol.for('DISABLE_USER_REGISTRATION'), Auth_DISABLE_USER_REGISTRATION: Symbol.for('Auth_DISABLE_USER_REGISTRATION'),
SNS_TOPIC_ARN: Symbol.for('SNS_TOPIC_ARN'), Auth_SNS_TOPIC_ARN: Symbol.for('Auth_SNS_TOPIC_ARN'),
SNS_AWS_REGION: Symbol.for('SNS_AWS_REGION'), Auth_SNS_AWS_REGION: Symbol.for('Auth_SNS_AWS_REGION'),
SQS_QUEUE_URL: Symbol.for('SQS_QUEUE_URL'), Auth_SQS_QUEUE_URL: Symbol.for('Auth_SQS_QUEUE_URL'),
SQS_AWS_REGION: Symbol.for('SQS_AWS_REGION'), Auth_SQS_AWS_REGION: Symbol.for('Auth_SQS_AWS_REGION'),
USER_SERVER_REGISTRATION_URL: Symbol.for('USER_SERVER_REGISTRATION_URL'), Auth_USER_SERVER_REGISTRATION_URL: Symbol.for('Auth_USER_SERVER_REGISTRATION_URL'),
USER_SERVER_AUTH_KEY: Symbol.for('USER_SERVER_AUTH_KEY'), Auth_USER_SERVER_AUTH_KEY: Symbol.for('Auth_USER_SERVER_AUTH_KEY'),
USER_SERVER_CHANGE_EMAIL_URL: Symbol.for('USER_SERVER_CHANGE_EMAIL_URL'), Auth_USER_SERVER_CHANGE_EMAIL_URL: Symbol.for('Auth_USER_SERVER_CHANGE_EMAIL_URL'),
NEW_RELIC_ENABLED: Symbol.for('NEW_RELIC_ENABLED'), Auth_NEW_RELIC_ENABLED: Symbol.for('Auth_NEW_RELIC_ENABLED'),
SYNCING_SERVER_URL: Symbol.for('SYNCING_SERVER_URL'), Auth_SYNCING_SERVER_URL: Symbol.for('Auth_SYNCING_SERVER_URL'),
VERSION: Symbol.for('VERSION'), Auth_VERSION: Symbol.for('Auth_VERSION'),
PAYMENTS_SERVER_URL: Symbol.for('PAYMENTS_SERVER_URL'), Auth_PAYMENTS_SERVER_URL: Symbol.for('Auth_PAYMENTS_SERVER_URL'),
SESSION_TRACE_DAYS_TTL: Symbol.for('SESSION_TRACE_DAYS_TTL'), Auth_SESSION_TRACE_DAYS_TTL: Symbol.for('Auth_SESSION_TRACE_DAYS_TTL'),
U2F_RELYING_PARTY_ID: Symbol.for('U2F_RELYING_PARTY_ID'), Auth_U2F_RELYING_PARTY_ID: Symbol.for('Auth_U2F_RELYING_PARTY_ID'),
U2F_RELYING_PARTY_NAME: Symbol.for('U2F_RELYING_PARTY_NAME'), Auth_U2F_RELYING_PARTY_NAME: Symbol.for('Auth_U2F_RELYING_PARTY_NAME'),
U2F_EXPECTED_ORIGIN: Symbol.for('U2F_EXPECTED_ORIGIN'), Auth_U2F_EXPECTED_ORIGIN: Symbol.for('Auth_U2F_EXPECTED_ORIGIN'),
U2F_REQUIRE_USER_VERIFICATION: Symbol.for('U2F_REQUIRE_USER_VERIFICATION'), Auth_U2F_REQUIRE_USER_VERIFICATION: Symbol.for('Auth_U2F_REQUIRE_USER_VERIFICATION'),
READONLY_USERS: Symbol.for('READONLY_USERS'), Auth_READONLY_USERS: Symbol.for('Auth_READONLY_USERS'),
// use cases // use cases
AuthenticateUser: Symbol.for('AuthenticateUser'), Auth_AuthenticateUser: Symbol.for('Auth_AuthenticateUser'),
AuthenticateRequest: Symbol.for('AuthenticateRequest'), Auth_AuthenticateRequest: Symbol.for('Auth_AuthenticateRequest'),
RefreshSessionToken: Symbol.for('RefreshSessionToken'), Auth_RefreshSessionToken: Symbol.for('Auth_RefreshSessionToken'),
VerifyMFA: Symbol.for('VerifyMFA'), Auth_VerifyMFA: Symbol.for('Auth_VerifyMFA'),
SignIn: Symbol.for('SignIn'), Auth_SignIn: Symbol.for('Auth_SignIn'),
ClearLoginAttempts: Symbol.for('ClearLoginAttempts'), Auth_ClearLoginAttempts: Symbol.for('Auth_ClearLoginAttempts'),
IncreaseLoginAttempts: Symbol.for('IncreaseLoginAttempts'), Auth_IncreaseLoginAttempts: Symbol.for('Auth_IncreaseLoginAttempts'),
GetUserKeyParams: Symbol.for('GetUserKeyParams'), Auth_GetUserKeyParams: Symbol.for('Auth_GetUserKeyParams'),
UpdateUser: Symbol.for('UpdateUser'), Auth_UpdateUser: Symbol.for('Auth_UpdateUser'),
Register: Symbol.for('Register'), Auth_Register: Symbol.for('Auth_Register'),
GetActiveSessionsForUser: Symbol.for('GetActiveSessionsForUser'), Auth_GetActiveSessionsForUser: Symbol.for('Auth_GetActiveSessionsForUser'),
DeletePreviousSessionsForUser: Symbol.for('DeletePreviousSessionsForUser'), Auth_DeletePreviousSessionsForUser: Symbol.for('Auth_DeletePreviousSessionsForUser'),
DeleteSessionForUser: Symbol.for('DeleteSessionForUser'), Auth_DeleteSessionForUser: Symbol.for('Auth_DeleteSessionForUser'),
ChangeCredentials: Symbol.for('ChangePassword'), Auth_ChangeCredentials: Symbol.for('Auth_ChangePassword'),
GetSettings: Symbol.for('GetSettings'), Auth_GetSettings: Symbol.for('Auth_GetSettings'),
GetSetting: Symbol.for('GetSetting'), Auth_GetSetting: Symbol.for('Auth_GetSetting'),
GetUserFeatures: Symbol.for('GetUserFeatures'), Auth_GetUserFeatures: Symbol.for('Auth_GetUserFeatures'),
UpdateSetting: Symbol.for('UpdateSetting'), Auth_UpdateSetting: Symbol.for('Auth_UpdateSetting'),
DeleteSetting: Symbol.for('DeleteSetting'), Auth_DeleteSetting: Symbol.for('Auth_DeleteSetting'),
DeleteAccount: Symbol.for('DeleteAccount'), Auth_DeleteAccount: Symbol.for('Auth_DeleteAccount'),
GetUserSubscription: Symbol.for('GetUserSubscription'), Auth_GetUserSubscription: Symbol.for('Auth_GetUserSubscription'),
GetUserOfflineSubscription: Symbol.for('GetUserOfflineSubscription'), Auth_GetUserOfflineSubscription: Symbol.for('Auth_GetUserOfflineSubscription'),
CreateSubscriptionToken: Symbol.for('CreateSubscriptionToken'), Auth_CreateSubscriptionToken: Symbol.for('Auth_CreateSubscriptionToken'),
AuthenticateSubscriptionToken: Symbol.for('AuthenticateSubscriptionToken'), Auth_AuthenticateSubscriptionToken: Symbol.for('Auth_AuthenticateSubscriptionToken'),
CreateOfflineSubscriptionToken: Symbol.for('CreateOfflineSubscriptionToken'), Auth_CreateOfflineSubscriptionToken: Symbol.for('Auth_CreateOfflineSubscriptionToken'),
AuthenticateOfflineSubscriptionToken: Symbol.for('AuthenticateOfflineSubscriptionToken'), Auth_AuthenticateOfflineSubscriptionToken: Symbol.for('Auth_AuthenticateOfflineSubscriptionToken'),
CreateValetToken: Symbol.for('CreateValetToken'), Auth_CreateValetToken: Symbol.for('Auth_CreateValetToken'),
CreateListedAccount: Symbol.for('CreateListedAccount'), Auth_CreateListedAccount: Symbol.for('Auth_CreateListedAccount'),
InviteToSharedSubscription: Symbol.for('InviteToSharedSubscription'), Auth_InviteToSharedSubscription: Symbol.for('Auth_InviteToSharedSubscription'),
AcceptSharedSubscriptionInvitation: Symbol.for('AcceptSharedSubscriptionInvitation'), Auth_AcceptSharedSubscriptionInvitation: Symbol.for('Auth_AcceptSharedSubscriptionInvitation'),
DeclineSharedSubscriptionInvitation: Symbol.for('DeclineSharedSubscriptionInvitation'), Auth_DeclineSharedSubscriptionInvitation: Symbol.for('Auth_DeclineSharedSubscriptionInvitation'),
CancelSharedSubscriptionInvitation: Symbol.for('CancelSharedSubscriptionInvitation'), Auth_CancelSharedSubscriptionInvitation: Symbol.for('Auth_CancelSharedSubscriptionInvitation'),
ListSharedSubscriptionInvitations: Symbol.for('ListSharedSubscriptionInvitations'), Auth_ListSharedSubscriptionInvitations: Symbol.for('Auth_ListSharedSubscriptionInvitations'),
VerifyPredicate: Symbol.for('VerifyPredicate'), Auth_VerifyPredicate: Symbol.for('Auth_VerifyPredicate'),
CreateCrossServiceToken: Symbol.for('CreateCrossServiceToken'), Auth_CreateCrossServiceToken: Symbol.for('Auth_CreateCrossServiceToken'),
ProcessUserRequest: Symbol.for('ProcessUserRequest'), Auth_ProcessUserRequest: Symbol.for('Auth_ProcessUserRequest'),
TraceSession: Symbol.for('TraceSession'), Auth_TraceSession: Symbol.for('Auth_TraceSession'),
CleanupSessionTraces: Symbol.for('CleanupSessionTraces'), Auth_CleanupSessionTraces: Symbol.for('Auth_CleanupSessionTraces'),
CleanupExpiredSessions: Symbol.for('CleanupExpiredSessions'), Auth_CleanupExpiredSessions: Symbol.for('Auth_CleanupExpiredSessions'),
PersistStatistics: Symbol.for('PersistStatistics'), Auth_PersistStatistics: Symbol.for('Auth_PersistStatistics'),
GenerateAuthenticatorRegistrationOptions: Symbol.for('GenerateAuthenticatorRegistrationOptions'), Auth_GenerateAuthenticatorRegistrationOptions: Symbol.for('Auth_GenerateAuthenticatorRegistrationOptions'),
VerifyAuthenticatorRegistrationResponse: Symbol.for('VerifyAuthenticatorRegistrationResponse'), Auth_VerifyAuthenticatorRegistrationResponse: Symbol.for('Auth_VerifyAuthenticatorRegistrationResponse'),
GenerateAuthenticatorAuthenticationOptions: Symbol.for('GenerateAuthenticatorAuthenticationOptions'), Auth_GenerateAuthenticatorAuthenticationOptions: Symbol.for('Auth_GenerateAuthenticatorAuthenticationOptions'),
VerifyAuthenticatorAuthenticationResponse: Symbol.for('VerifyAuthenticatorAuthenticationResponse'), Auth_VerifyAuthenticatorAuthenticationResponse: Symbol.for('Auth_VerifyAuthenticatorAuthenticationResponse'),
ListAuthenticators: Symbol.for('ListAuthenticators'), Auth_ListAuthenticators: Symbol.for('Auth_ListAuthenticators'),
DeleteAuthenticator: Symbol.for('DeleteAuthenticator'), Auth_DeleteAuthenticator: Symbol.for('Auth_DeleteAuthenticator'),
GenerateRecoveryCodes: Symbol.for('GenerateRecoveryCodes'), Auth_GenerateRecoveryCodes: Symbol.for('Auth_GenerateRecoveryCodes'),
SignInWithRecoveryCodes: Symbol.for('SignInWithRecoveryCodes'), Auth_SignInWithRecoveryCodes: Symbol.for('Auth_SignInWithRecoveryCodes'),
GetUserKeyParamsRecovery: Symbol.for('GetUserKeyParamsRecovery'), Auth_GetUserKeyParamsRecovery: Symbol.for('Auth_GetUserKeyParamsRecovery'),
// Handlers // Handlers
UserRegisteredEventHandler: Symbol.for('UserRegisteredEventHandler'), Auth_UserRegisteredEventHandler: Symbol.for('Auth_UserRegisteredEventHandler'),
AccountDeletionRequestedEventHandler: Symbol.for('AccountDeletionRequestedEventHandler'), Auth_AccountDeletionRequestedEventHandler: Symbol.for('Auth_AccountDeletionRequestedEventHandler'),
SubscriptionPurchasedEventHandler: Symbol.for('SubscriptionPurchasedEventHandler'), Auth_SubscriptionPurchasedEventHandler: Symbol.for('Auth_SubscriptionPurchasedEventHandler'),
SubscriptionCancelledEventHandler: Symbol.for('SubscriptionCancelledEventHandler'), Auth_SubscriptionCancelledEventHandler: Symbol.for('Auth_SubscriptionCancelledEventHandler'),
SubscriptionReassignedEventHandler: Symbol.for('SubscriptionReassignedEventHandler'), Auth_SubscriptionReassignedEventHandler: Symbol.for('Auth_SubscriptionReassignedEventHandler'),
SubscriptionRenewedEventHandler: Symbol.for('SubscriptionRenewedEventHandler'), Auth_SubscriptionRenewedEventHandler: Symbol.for('Auth_SubscriptionRenewedEventHandler'),
SubscriptionRefundedEventHandler: Symbol.for('SubscriptionRefundedEventHandler'), Auth_SubscriptionRefundedEventHandler: Symbol.for('Auth_SubscriptionRefundedEventHandler'),
SubscriptionExpiredEventHandler: Symbol.for('SubscriptionExpiredEventHandler'), Auth_SubscriptionExpiredEventHandler: Symbol.for('Auth_SubscriptionExpiredEventHandler'),
SubscriptionSyncRequestedEventHandler: Symbol.for('SubscriptionSyncRequestedEventHandler'), Auth_SubscriptionSyncRequestedEventHandler: Symbol.for('Auth_SubscriptionSyncRequestedEventHandler'),
ExtensionKeyGrantedEventHandler: Symbol.for('ExtensionKeyGrantedEventHandler'), Auth_ExtensionKeyGrantedEventHandler: Symbol.for('Auth_ExtensionKeyGrantedEventHandler'),
UserEmailChangedEventHandler: Symbol.for('UserEmailChangedEventHandler'), Auth_UserEmailChangedEventHandler: Symbol.for('Auth_UserEmailChangedEventHandler'),
FileUploadedEventHandler: Symbol.for('FileUploadedEventHandler'), Auth_FileUploadedEventHandler: Symbol.for('Auth_FileUploadedEventHandler'),
FileRemovedEventHandler: Symbol.for('FileRemovedEventHandler'), Auth_FileRemovedEventHandler: Symbol.for('Auth_FileRemovedEventHandler'),
ListedAccountCreatedEventHandler: Symbol.for('ListedAccountCreatedEventHandler'), Auth_ListedAccountCreatedEventHandler: Symbol.for('Auth_ListedAccountCreatedEventHandler'),
ListedAccountDeletedEventHandler: Symbol.for('ListedAccountDeletedEventHandler'), Auth_ListedAccountDeletedEventHandler: Symbol.for('Auth_ListedAccountDeletedEventHandler'),
UserDisabledSessionUserAgentLoggingEventHandler: Symbol.for('UserDisabledSessionUserAgentLoggingEventHandler'), Auth_UserDisabledSessionUserAgentLoggingEventHandler: Symbol.for(
SharedSubscriptionInvitationCreatedEventHandler: Symbol.for('SharedSubscriptionInvitationCreatedEventHandler'), 'Auth_UserDisabledSessionUserAgentLoggingEventHandler',
PredicateVerificationRequestedEventHandler: Symbol.for('PredicateVerificationRequestedEventHandler'), ),
EmailSubscriptionUnsubscribedEventHandler: Symbol.for('EmailSubscriptionUnsubscribedEventHandler'), Auth_SharedSubscriptionInvitationCreatedEventHandler: Symbol.for(
'Auth_SharedSubscriptionInvitationCreatedEventHandler',
),
Auth_PredicateVerificationRequestedEventHandler: Symbol.for('Auth_PredicateVerificationRequestedEventHandler'),
Auth_EmailSubscriptionUnsubscribedEventHandler: Symbol.for('Auth_EmailSubscriptionUnsubscribedEventHandler'),
// Services // Services
DeviceDetector: Symbol.for('DeviceDetector'), Auth_DeviceDetector: Symbol.for('Auth_DeviceDetector'),
SessionService: Symbol.for('SessionService'), Auth_SessionService: Symbol.for('Auth_SessionService'),
SettingService: Symbol.for('SettingService'), Auth_SettingService: Symbol.for('Auth_SettingService'),
SubscriptionSettingService: Symbol.for('SubscriptionSettingService'), Auth_SubscriptionSettingService: Symbol.for('Auth_SubscriptionSettingService'),
OfflineSettingService: Symbol.for('OfflineSettingService'), Auth_OfflineSettingService: Symbol.for('Auth_OfflineSettingService'),
AuthResponseFactory20161215: Symbol.for('AuthResponseFactory20161215'), Auth_AuthResponseFactory20161215: Symbol.for('Auth_AuthResponseFactory20161215'),
AuthResponseFactory20190520: Symbol.for('AuthResponseFactory20190520'), Auth_AuthResponseFactory20190520: Symbol.for('Auth_AuthResponseFactory20190520'),
AuthResponseFactory20200115: Symbol.for('AuthResponseFactory20200115'), Auth_AuthResponseFactory20200115: Symbol.for('Auth_AuthResponseFactory20200115'),
AuthResponseFactoryResolver: Symbol.for('AuthResponseFactoryResolver'), Auth_AuthResponseFactoryResolver: Symbol.for('Auth_AuthResponseFactoryResolver'),
KeyParamsFactory: Symbol.for('KeyParamsFactory'), Auth_KeyParamsFactory: Symbol.for('Auth_KeyParamsFactory'),
SessionTokenDecoder: Symbol.for('SessionTokenDecoder'), Auth_SessionTokenDecoder: Symbol.for('Auth_SessionTokenDecoder'),
FallbackSessionTokenDecoder: Symbol.for('FallbackSessionTokenDecoder'), Auth_FallbackSessionTokenDecoder: Symbol.for('Auth_FallbackSessionTokenDecoder'),
CrossServiceTokenDecoder: Symbol.for('CrossServiceTokenDecoder'), Auth_CrossServiceTokenDecoder: Symbol.for('Auth_CrossServiceTokenDecoder'),
OfflineUserTokenDecoder: Symbol.for('OfflineUserTokenDecoder'), Auth_OfflineUserTokenDecoder: Symbol.for('Auth_OfflineUserTokenDecoder'),
OfflineUserTokenEncoder: Symbol.for('OfflineUserTokenEncoder'), Auth_OfflineUserTokenEncoder: Symbol.for('Auth_OfflineUserTokenEncoder'),
CrossServiceTokenEncoder: Symbol.for('CrossServiceTokenEncoder'), Auth_CrossServiceTokenEncoder: Symbol.for('Auth_CrossServiceTokenEncoder'),
SessionTokenEncoder: Symbol.for('SessionTokenEncoder'), Auth_SessionTokenEncoder: Symbol.for('Auth_SessionTokenEncoder'),
ValetTokenEncoder: Symbol.for('ValetTokenEncoder'), Auth_ValetTokenEncoder: Symbol.for('Auth_ValetTokenEncoder'),
WebSocketConnectionTokenDecoder: Symbol.for('WebSocketConnectionTokenDecoder'), Auth_WebSocketConnectionTokenDecoder: Symbol.for('Auth_WebSocketConnectionTokenDecoder'),
AuthenticationMethodResolver: Symbol.for('AuthenticationMethodResolver'), Auth_AuthenticationMethodResolver: Symbol.for('Auth_AuthenticationMethodResolver'),
DomainEventPublisher: Symbol.for('DomainEventPublisher'), Auth_DomainEventPublisher: Symbol.for('Auth_DomainEventPublisher'),
DomainEventSubscriberFactory: Symbol.for('DomainEventSubscriberFactory'), Auth_DomainEventSubscriberFactory: Symbol.for('Auth_DomainEventSubscriberFactory'),
DomainEventFactory: Symbol.for('DomainEventFactory'), Auth_DomainEventFactory: Symbol.for('Auth_DomainEventFactory'),
DomainEventMessageHandler: Symbol.for('DomainEventMessageHandler'), Auth_DomainEventMessageHandler: Symbol.for('Auth_DomainEventMessageHandler'),
HTTPClient: Symbol.for('HTTPClient'), Auth_HTTPClient: Symbol.for('Auth_HTTPClient'),
Crypter: Symbol.for('Crypter'), Auth_Crypter: Symbol.for('Auth_Crypter'),
CryptoNode: Symbol.for('CryptoNode'), Auth_CryptoNode: Symbol.for('Auth_CryptoNode'),
Timer: Symbol.for('Timer'), Auth_Timer: Symbol.for('Auth_Timer'),
ContenDecoder: Symbol.for('ContenDecoder'), Auth_ContenDecoder: Symbol.for('Auth_ContenDecoder'),
WebSocketsClientService: Symbol.for('WebSocketClientService'), Auth_WebSocketsClientService: Symbol.for('Auth_WebSocketClientService'),
RoleService: Symbol.for('RoleService'), Auth_RoleService: Symbol.for('Auth_RoleService'),
RoleToSubscriptionMap: Symbol.for('RoleToSubscriptionMap'), Auth_RoleToSubscriptionMap: Symbol.for('Auth_RoleToSubscriptionMap'),
SettingsAssociationService: Symbol.for('SettingsAssociationService'), Auth_SettingsAssociationService: Symbol.for('Auth_SettingsAssociationService'),
SubscriptionSettingsAssociationService: Symbol.for('SubscriptionSettingsAssociationService'), Auth_SubscriptionSettingsAssociationService: Symbol.for('Auth_SubscriptionSettingsAssociationService'),
FeatureService: Symbol.for('FeatureService'), Auth_FeatureService: Symbol.for('Auth_FeatureService'),
SettingDecrypter: Symbol.for('SettingDecrypter'), Auth_SettingDecrypter: Symbol.for('Auth_SettingDecrypter'),
SettingInterpreter: Symbol.for('SettingInterpreter'), Auth_SettingInterpreter: Symbol.for('Auth_SettingInterpreter'),
ProtocolVersionSelector: Symbol.for('ProtocolVersionSelector'), Auth_ProtocolVersionSelector: Symbol.for('Auth_ProtocolVersionSelector'),
BooleanSelector: Symbol.for('BooleanSelector'), Auth_BooleanSelector: Symbol.for('Auth_BooleanSelector'),
UserSubscriptionService: Symbol.for('UserSubscriptionService'), Auth_UserSubscriptionService: Symbol.for('Auth_UserSubscriptionService'),
Auth_InversifyExpressAuthController: Symbol.for('Auth_InversifyExpressAuthController'),
Auth_InversifyExpressAuthenticatorsController: Symbol.for('Auth_InversifyExpressAuthenticatorsController'),
Auth_InversifyExpressSubscriptionInvitesController: Symbol.for('Auth_InversifyExpressSubscriptionInvitesController'),
Auth_InversifyExpressUserRequestsController: Symbol.for('Auth_InversifyExpressUserRequestsController'),
Auth_InversifyExpressWebSocketsController: Symbol.for('Auth_InversifyExpressWebSocketsController'),
} }
export default TYPES export default TYPES

View file

@ -0,0 +1 @@
export * from './Service'

View file

@ -8,6 +8,7 @@ import * as express from 'express'
import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting' import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting'
import { CreateSubscriptionToken } from '../Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken' import { CreateSubscriptionToken } from '../Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken'
import { CreateOfflineSubscriptionToken } from '../Domain/UseCase/CreateOfflineSubscriptionToken/CreateOfflineSubscriptionToken' import { CreateOfflineSubscriptionToken } from '../Domain/UseCase/CreateOfflineSubscriptionToken/CreateOfflineSubscriptionToken'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('AdminController', () => { describe('AdminController', () => {
let deleteSetting: DeleteSetting let deleteSetting: DeleteSetting
@ -16,9 +17,16 @@ describe('AdminController', () => {
let createOfflineSubscriptionToken: CreateOfflineSubscriptionToken let createOfflineSubscriptionToken: CreateOfflineSubscriptionToken
let request: express.Request let request: express.Request
let user: User let user: User
let controllerContainer: ControllerContainerInterface
const createController = () => const createController = () =>
new AdminController(deleteSetting, userRepository, createSubscriptionToken, createOfflineSubscriptionToken) new AdminController(
deleteSetting,
userRepository,
createSubscriptionToken,
createOfflineSubscriptionToken,
controllerContainer,
)
beforeEach(() => { beforeEach(() => {
user = {} as jest.Mocked<User> user = {} as jest.Mocked<User>
@ -50,6 +58,9 @@ describe('AdminController', () => {
body: {}, body: {},
params: {}, params: {},
} as jest.Mocked<express.Request> } as jest.Mocked<express.Request>
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
}) })
it('should return error if missing email parameter', async () => { it('should return error if missing email parameter', async () => {

View file

@ -1,4 +1,4 @@
import { Username } from '@standardnotes/domain-core' import { ControllerContainerInterface, Username } from '@standardnotes/domain-core'
import { SettingName } from '@standardnotes/settings' import { SettingName } from '@standardnotes/settings'
import { Request } from 'express' import { Request } from 'express'
import { inject } from 'inversify' import { inject } from 'inversify'
@ -20,13 +20,20 @@ import { UserRepositoryInterface } from '../Domain/User/UserRepositoryInterface'
@controller('/admin') @controller('/admin')
export class AdminController extends BaseHttpController { export class AdminController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.DeleteSetting) private doDeleteSetting: DeleteSetting, @inject(TYPES.Auth_DeleteSetting) private doDeleteSetting: DeleteSetting,
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken, @inject(TYPES.Auth_CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken,
@inject(TYPES.CreateOfflineSubscriptionToken) @inject(TYPES.Auth_CreateOfflineSubscriptionToken)
private createOfflineSubscriptionToken: CreateOfflineSubscriptionToken, private createOfflineSubscriptionToken: CreateOfflineSubscriptionToken,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) { ) {
super() super()
this.controllerContainer.register('admin.getUser', this.getUser.bind(this))
this.controllerContainer.register('admin.deleteMFASetting', this.deleteMFASetting.bind(this))
this.controllerContainer.register('admin.createToken', this.createToken.bind(this))
this.controllerContainer.register('admin.createOfflineToken', this.createOfflineToken.bind(this))
this.controllerContainer.register('admin.disableEmailBackups', this.disableEmailBackups.bind(this))
} }
@httpGet('/user/:email') @httpGet('/user/:email')

View file

@ -8,8 +8,8 @@ import TYPES from '../Bootstrap/Types'
@injectable() @injectable()
export class ApiGatewayAuthMiddleware extends BaseMiddleware { export class ApiGatewayAuthMiddleware extends BaseMiddleware {
constructor( constructor(
@inject(TYPES.CrossServiceTokenDecoder) private tokenDecoder: TokenDecoderInterface<CrossServiceTokenData>, @inject(TYPES.Auth_CrossServiceTokenDecoder) private tokenDecoder: TokenDecoderInterface<CrossServiceTokenData>,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) { ) {
super() super()
} }

View file

@ -8,8 +8,8 @@ import TYPES from '../Bootstrap/Types'
@injectable() @injectable()
export class ApiGatewayOfflineAuthMiddleware extends BaseMiddleware { export class ApiGatewayOfflineAuthMiddleware extends BaseMiddleware {
constructor( constructor(
@inject(TYPES.OfflineUserTokenDecoder) private tokenDecoder: TokenDecoderInterface<OfflineUserTokenData>, @inject(TYPES.Auth_OfflineUserTokenDecoder) private tokenDecoder: TokenDecoderInterface<OfflineUserTokenData>,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) { ) {
super() super()
} }

View file

@ -13,6 +13,7 @@ import { SignInWithRecoveryCodes } from '../Domain/UseCase/SignInWithRecoveryCod
import { GetUserKeyParamsRecovery } from '../Domain/UseCase/GetUserKeyParamsRecovery/GetUserKeyParamsRecovery' import { GetUserKeyParamsRecovery } from '../Domain/UseCase/GetUserKeyParamsRecovery/GetUserKeyParamsRecovery'
import { GenerateRecoveryCodes } from '../Domain/UseCase/GenerateRecoveryCodes/GenerateRecoveryCodes' import { GenerateRecoveryCodes } from '../Domain/UseCase/GenerateRecoveryCodes/GenerateRecoveryCodes'
import { Logger } from 'winston' import { Logger } from 'winston'
import { SessionServiceInterface } from '../Domain/Session/SessionServiceInterface'
describe('AuthController', () => { describe('AuthController', () => {
let clearLoginAttempts: ClearLoginAttempts let clearLoginAttempts: ClearLoginAttempts
@ -25,6 +26,7 @@ describe('AuthController', () => {
let getUserKeyParamsRecovery: GetUserKeyParamsRecovery let getUserKeyParamsRecovery: GetUserKeyParamsRecovery
let doGenerateRecoveryCodes: GenerateRecoveryCodes let doGenerateRecoveryCodes: GenerateRecoveryCodes
let logger: Logger let logger: Logger
let sessionService: SessionServiceInterface
const createController = () => const createController = () =>
new AuthController( new AuthController(
@ -36,6 +38,7 @@ describe('AuthController', () => {
getUserKeyParamsRecovery, getUserKeyParamsRecovery,
doGenerateRecoveryCodes, doGenerateRecoveryCodes,
logger, logger,
sessionService,
) )
beforeEach(() => { beforeEach(() => {
@ -58,6 +61,9 @@ describe('AuthController', () => {
logger = {} as jest.Mocked<Logger> logger = {} as jest.Mocked<Logger>
logger.debug = jest.fn() logger.debug = jest.fn()
sessionService = {} as jest.Mocked<SessionServiceInterface>
sessionService.deleteSessionByToken = jest.fn().mockReturnValue('1-2-3')
}) })
it('should register a user', async () => { it('should register a user', async () => {

View file

@ -1,4 +1,3 @@
import { inject, injectable } from 'inversify'
import { DomainEventPublisherInterface } from '@standardnotes/domain-events' import { DomainEventPublisherInterface } from '@standardnotes/domain-events'
import { import {
ApiVersion, ApiVersion,
@ -7,10 +6,9 @@ import {
UserDeletionResponseBody, UserDeletionResponseBody,
UserRegistrationResponseBody, UserRegistrationResponseBody,
} from '@standardnotes/api' } from '@standardnotes/api'
import { HttpResponse, HttpStatusCode } from '@standardnotes/responses' import { ErrorTag, HttpResponse, HttpStatusCode } from '@standardnotes/responses'
import { ProtocolVersion } from '@standardnotes/common' import { ProtocolVersion } from '@standardnotes/common'
import TYPES from '../Bootstrap/Types'
import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts' import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts'
import { Register } from '../Domain/UseCase/Register' import { Register } from '../Domain/UseCase/Register'
import { DomainEventFactoryInterface } from '../Domain/Event/DomainEventFactoryInterface' import { DomainEventFactoryInterface } from '../Domain/Event/DomainEventFactoryInterface'
@ -24,18 +22,19 @@ import { GenerateRecoveryCodesResponseBody } from '../Infra/Http/Response/Genera
import { GenerateRecoveryCodes } from '../Domain/UseCase/GenerateRecoveryCodes/GenerateRecoveryCodes' import { GenerateRecoveryCodes } from '../Domain/UseCase/GenerateRecoveryCodes/GenerateRecoveryCodes'
import { GenerateRecoveryCodesRequestParams } from '../Infra/Http/Request/GenerateRecoveryCodesRequestParams' import { GenerateRecoveryCodesRequestParams } from '../Infra/Http/Request/GenerateRecoveryCodesRequestParams'
import { Logger } from 'winston' import { Logger } from 'winston'
import { SessionServiceInterface } from '../Domain/Session/SessionServiceInterface'
@injectable()
export class AuthController implements UserServerInterface { export class AuthController implements UserServerInterface {
constructor( constructor(
@inject(TYPES.ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts, private clearLoginAttempts: ClearLoginAttempts,
@inject(TYPES.Register) private registerUser: Register, private registerUser: Register,
@inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, private domainEventPublisher: DomainEventPublisherInterface,
@inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, private domainEventFactory: DomainEventFactoryInterface,
@inject(TYPES.SignInWithRecoveryCodes) private doSignInWithRecoveryCodes: SignInWithRecoveryCodes, private doSignInWithRecoveryCodes: SignInWithRecoveryCodes,
@inject(TYPES.GetUserKeyParamsRecovery) private getUserKeyParamsRecovery: GetUserKeyParamsRecovery, private getUserKeyParamsRecovery: GetUserKeyParamsRecovery,
@inject(TYPES.GenerateRecoveryCodes) private doGenerateRecoveryCodes: GenerateRecoveryCodes, private doGenerateRecoveryCodes: GenerateRecoveryCodes,
@inject(TYPES.Logger) private logger: Logger, private logger: Logger,
private sessionService: SessionServiceInterface,
) {} ) {}
async deleteAccount(_params: never): Promise<HttpResponse<UserDeletionResponseBody>> { async deleteAccount(_params: never): Promise<HttpResponse<UserDeletionResponseBody>> {
@ -200,4 +199,33 @@ export class AuthController implements UserServerInterface {
}, },
} }
} }
async signOut(params: Record<string, unknown>): Promise<HttpResponse> {
if (params.readOnlyAccess) {
return {
status: HttpStatusCode.Unauthorized,
data: {
error: {
tag: ErrorTag.ReadOnlyAccess,
message: 'Session has read-only access.',
},
},
}
}
const userUuid = await this.sessionService.deleteSessionByToken(
(params.authorizationHeader as string).replace('Bearer ', ''),
)
let headers = undefined
if (userUuid !== null) {
headers = new Map([['x-invalidate-cache', userUuid]])
}
return {
status: HttpStatusCode.NoContent,
data: {},
headers,
}
}
} }

View file

@ -8,8 +8,8 @@ import { AuthenticateRequest } from '../Domain/UseCase/AuthenticateRequest'
@injectable() @injectable()
export class AuthMiddleware extends BaseMiddleware { export class AuthMiddleware extends BaseMiddleware {
constructor( constructor(
@inject(TYPES.AuthenticateRequest) private authenticateRequest: AuthenticateRequest, @inject(TYPES.Auth_AuthenticateRequest) private authenticateRequest: AuthenticateRequest,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) { ) {
super() super()
} }

View file

@ -6,7 +6,7 @@ import { AuthenticateRequest } from '../Domain/UseCase/AuthenticateRequest'
@injectable() @injectable()
export class AuthMiddlewareWithoutResponse extends BaseMiddleware { export class AuthMiddlewareWithoutResponse extends BaseMiddleware {
constructor(@inject(TYPES.AuthenticateRequest) private authenticateRequest: AuthenticateRequest) { constructor(@inject(TYPES.Auth_AuthenticateRequest) private authenticateRequest: AuthenticateRequest) {
super() super()
} }

View file

@ -6,6 +6,7 @@ import { FeaturesController } from './FeaturesController'
import { results } from 'inversify-express-utils' import { results } from 'inversify-express-utils'
import { User } from '../Domain/User/User' import { User } from '../Domain/User/User'
import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatures' import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatures'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('FeaturesController', () => { describe('FeaturesController', () => {
let getUserFeatures: GetUserFeatures let getUserFeatures: GetUserFeatures
@ -13,10 +14,14 @@ describe('FeaturesController', () => {
let request: express.Request let request: express.Request
let response: express.Response let response: express.Response
let user: User let user: User
let controllerContainer: ControllerContainerInterface
const createController = () => new FeaturesController(getUserFeatures) const createController = () => new FeaturesController(getUserFeatures, controllerContainer)
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
user = {} as jest.Mocked<User> user = {} as jest.Mocked<User>
user.uuid = '123' user.uuid = '123'

View file

@ -9,14 +9,20 @@ import {
} from 'inversify-express-utils' } from 'inversify-express-utils'
import TYPES from '../Bootstrap/Types' import TYPES from '../Bootstrap/Types'
import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatures' import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatures'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/users/:userUuid/features') @controller('/users/:userUuid/features')
export class FeaturesController extends BaseHttpController { export class FeaturesController extends BaseHttpController {
constructor(@inject(TYPES.GetUserFeatures) private doGetUserFeatures: GetUserFeatures) { constructor(
@inject(TYPES.Auth_GetUserFeatures) private doGetUserFeatures: GetUserFeatures,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) {
super() super()
this.controllerContainer.register('auth.users.getFeatures', this.getFeatures.bind(this))
} }
@httpGet('/', TYPES.ApiGatewayAuthMiddleware) @httpGet('/', TYPES.Auth_ApiGatewayAuthMiddleware)
async getFeatures(request: Request, response: Response): Promise<results.JsonResult> { async getFeatures(request: Request, response: Response): Promise<results.JsonResult> {
if (request.params.userUuid !== response.locals.user.uuid) { if (request.params.userUuid !== response.locals.user.uuid) {
return this.json( return this.json(

View file

@ -14,8 +14,8 @@ import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatur
@controller('/internal') @controller('/internal')
export class InternalController extends BaseHttpController { export class InternalController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.GetUserFeatures) private doGetUserFeatures: GetUserFeatures, @inject(TYPES.Auth_GetUserFeatures) private doGetUserFeatures: GetUserFeatures,
@inject(TYPES.GetSetting) private doGetSetting: GetSetting, @inject(TYPES.Auth_GetSetting) private doGetSetting: GetSetting,
) { ) {
super() super()
} }

View file

@ -6,6 +6,7 @@ import { results } from 'inversify-express-utils'
import { ListedController } from './ListedController' import { ListedController } from './ListedController'
import { User } from '../Domain/User/User' import { User } from '../Domain/User/User'
import { CreateListedAccount } from '../Domain/UseCase/CreateListedAccount/CreateListedAccount' import { CreateListedAccount } from '../Domain/UseCase/CreateListedAccount/CreateListedAccount'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('ListedController', () => { describe('ListedController', () => {
let createListedAccount: CreateListedAccount let createListedAccount: CreateListedAccount
@ -13,10 +14,14 @@ describe('ListedController', () => {
let request: express.Request let request: express.Request
let response: express.Response let response: express.Response
let user: User let user: User
let controllerContainer: ControllerContainerInterface
const createController = () => new ListedController(createListedAccount) const createController = () => new ListedController(createListedAccount, controllerContainer)
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
user = {} as jest.Mocked<User> user = {} as jest.Mocked<User>
user.uuid = '123' user.uuid = '123'

View file

@ -5,14 +5,20 @@ import { Request, Response } from 'express'
import TYPES from '../Bootstrap/Types' import TYPES from '../Bootstrap/Types'
import { CreateListedAccount } from '../Domain/UseCase/CreateListedAccount/CreateListedAccount' import { CreateListedAccount } from '../Domain/UseCase/CreateListedAccount/CreateListedAccount'
import { ErrorTag } from '@standardnotes/responses' import { ErrorTag } from '@standardnotes/responses'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/listed') @controller('/listed')
export class ListedController extends BaseHttpController { export class ListedController extends BaseHttpController {
constructor(@inject(TYPES.CreateListedAccount) private doCreateListedAccount: CreateListedAccount) { constructor(
@inject(TYPES.Auth_CreateListedAccount) private doCreateListedAccount: CreateListedAccount,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) {
super() super()
this.controllerContainer.register('auth.users.createListedAccount', this.createListedAccount.bind(this))
} }
@httpPost('/', TYPES.ApiGatewayAuthMiddleware) @httpPost('/', TYPES.Auth_ApiGatewayAuthMiddleware)
async createListedAccount(_request: Request, response: Response): Promise<results.JsonResult> { async createListedAccount(_request: Request, response: Response): Promise<results.JsonResult> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(

View file

@ -10,8 +10,8 @@ import { UserRepositoryInterface } from '../Domain/User/UserRepositoryInterface'
@injectable() @injectable()
export class LockMiddleware extends BaseMiddleware { export class LockMiddleware extends BaseMiddleware {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.LockRepository) private lockRepository: LockRepositoryInterface, @inject(TYPES.Auth_LockRepository) private lockRepository: LockRepositoryInterface,
) { ) {
super() super()
} }

View file

@ -14,6 +14,7 @@ import { GetUserOfflineSubscription } from '../Domain/UseCase/GetUserOfflineSubs
import { OfflineUserTokenData, TokenEncoderInterface } from '@standardnotes/security' import { OfflineUserTokenData, TokenEncoderInterface } from '@standardnotes/security'
import { SubscriptionName } from '@standardnotes/common' import { SubscriptionName } from '@standardnotes/common'
import { Logger } from 'winston' import { Logger } from 'winston'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('OfflineController', () => { describe('OfflineController', () => {
let getUserFeatures: GetUserFeatures let getUserFeatures: GetUserFeatures
@ -28,6 +29,8 @@ describe('OfflineController', () => {
let response: express.Response let response: express.Response
let user: User let user: User
let controllerContainer: ControllerContainerInterface
const createController = () => const createController = () =>
new OfflineController( new OfflineController(
getUserFeatures, getUserFeatures,
@ -37,9 +40,13 @@ describe('OfflineController', () => {
tokenEncoder, tokenEncoder,
jwtTTL, jwtTTL,
logger, logger,
controllerContainer,
) )
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
user = {} as jest.Mocked<User> user = {} as jest.Mocked<User>
user.uuid = '123' user.uuid = '123'

View file

@ -15,23 +15,30 @@ import { CreateOfflineSubscriptionToken } from '../Domain/UseCase/CreateOfflineS
import { GetUserOfflineSubscription } from '../Domain/UseCase/GetUserOfflineSubscription/GetUserOfflineSubscription' import { GetUserOfflineSubscription } from '../Domain/UseCase/GetUserOfflineSubscription/GetUserOfflineSubscription'
import { Logger } from 'winston' import { Logger } from 'winston'
import { OfflineUserTokenData, TokenEncoderInterface } from '@standardnotes/security' import { OfflineUserTokenData, TokenEncoderInterface } from '@standardnotes/security'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/offline') @controller('/offline')
export class OfflineController extends BaseHttpController { export class OfflineController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.GetUserFeatures) private doGetUserFeatures: GetUserFeatures, @inject(TYPES.Auth_GetUserFeatures) private doGetUserFeatures: GetUserFeatures,
@inject(TYPES.GetUserOfflineSubscription) private getUserOfflineSubscription: GetUserOfflineSubscription, @inject(TYPES.Auth_GetUserOfflineSubscription) private getUserOfflineSubscription: GetUserOfflineSubscription,
@inject(TYPES.CreateOfflineSubscriptionToken) @inject(TYPES.Auth_CreateOfflineSubscriptionToken)
private createOfflineSubscriptionToken: CreateOfflineSubscriptionToken, private createOfflineSubscriptionToken: CreateOfflineSubscriptionToken,
@inject(TYPES.AuthenticateOfflineSubscriptionToken) private authenticateToken: AuthenticateOfflineSubscriptionToken, @inject(TYPES.Auth_AuthenticateOfflineSubscriptionToken)
@inject(TYPES.OfflineUserTokenEncoder) private tokenEncoder: TokenEncoderInterface<OfflineUserTokenData>, private authenticateToken: AuthenticateOfflineSubscriptionToken,
@inject(TYPES.AUTH_JWT_TTL) private jwtTTL: number, @inject(TYPES.Auth_OfflineUserTokenEncoder) private tokenEncoder: TokenEncoderInterface<OfflineUserTokenData>,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_AUTH_JWT_TTL) private jwtTTL: number,
@inject(TYPES.Auth_Logger) private logger: Logger,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) { ) {
super() super()
this.controllerContainer.register('auth.offline.features', this.getOfflineFeatures.bind(this))
this.controllerContainer.register('auth.offline.subscriptionTokens.create', this.createToken.bind(this))
this.controllerContainer.register('auth.users.getOfflineSubscriptionByToken', this.getSubscription.bind(this))
} }
@httpGet('/features', TYPES.OfflineUserAuthMiddleware) @httpGet('/features', TYPES.Auth_OfflineUserAuthMiddleware)
async getOfflineFeatures(_request: Request, response: Response): Promise<results.JsonResult> { async getOfflineFeatures(_request: Request, response: Response): Promise<results.JsonResult> {
const result = await this.doGetUserFeatures.execute({ const result = await this.doGetUserFeatures.execute({
email: response.locals.offlineUserEmail, email: response.locals.offlineUserEmail,
@ -119,7 +126,7 @@ export class OfflineController extends BaseHttpController {
return this.json({ authToken }) return this.json({ authToken })
} }
@httpGet('/users/subscription', TYPES.ApiGatewayOfflineAuthMiddleware) @httpGet('/users/subscription', TYPES.Auth_ApiGatewayOfflineAuthMiddleware)
async getSubscription(_request: Request, response: Response): Promise<results.JsonResult> { async getSubscription(_request: Request, response: Response): Promise<results.JsonResult> {
const result = await this.getUserOfflineSubscription.execute({ const result = await this.getUserOfflineSubscription.execute({
userEmail: response.locals.userEmail, userEmail: response.locals.userEmail,

View file

@ -9,8 +9,8 @@ import { OfflineSettingRepositoryInterface } from '../Domain/Setting/OfflineSett
@injectable() @injectable()
export class OfflineUserAuthMiddleware extends BaseMiddleware { export class OfflineUserAuthMiddleware extends BaseMiddleware {
constructor( constructor(
@inject(TYPES.OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface, @inject(TYPES.Auth_OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) { ) {
super() super()
} }

View file

@ -7,6 +7,7 @@ import { results } from 'inversify-express-utils'
import { RefreshSessionToken } from '../Domain/UseCase/RefreshSessionToken' import { RefreshSessionToken } from '../Domain/UseCase/RefreshSessionToken'
import { DeletePreviousSessionsForUser } from '../Domain/UseCase/DeletePreviousSessionsForUser' import { DeletePreviousSessionsForUser } from '../Domain/UseCase/DeletePreviousSessionsForUser'
import { DeleteSessionForUser } from '../Domain/UseCase/DeleteSessionForUser' import { DeleteSessionForUser } from '../Domain/UseCase/DeleteSessionForUser'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('SessionController', () => { describe('SessionController', () => {
let deleteSessionForUser: DeleteSessionForUser let deleteSessionForUser: DeleteSessionForUser
@ -14,11 +15,15 @@ describe('SessionController', () => {
let refreshSessionToken: RefreshSessionToken let refreshSessionToken: RefreshSessionToken
let request: express.Request let request: express.Request
let response: express.Response let response: express.Response
let controllerContainer: ControllerContainerInterface
const createController = () => const createController = () =>
new SessionController(deleteSessionForUser, deletePreviousSessionsForUser, refreshSessionToken) new SessionController(deleteSessionForUser, deletePreviousSessionsForUser, refreshSessionToken, controllerContainer)
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
deleteSessionForUser = {} as jest.Mocked<DeleteSessionForUser> deleteSessionForUser = {} as jest.Mocked<DeleteSessionForUser>
deleteSessionForUser.execute = jest.fn().mockReturnValue({ success: true }) deleteSessionForUser.execute = jest.fn().mockReturnValue({ success: true })

View file

@ -13,18 +13,25 @@ import TYPES from '../Bootstrap/Types'
import { DeletePreviousSessionsForUser } from '../Domain/UseCase/DeletePreviousSessionsForUser' import { DeletePreviousSessionsForUser } from '../Domain/UseCase/DeletePreviousSessionsForUser'
import { DeleteSessionForUser } from '../Domain/UseCase/DeleteSessionForUser' import { DeleteSessionForUser } from '../Domain/UseCase/DeleteSessionForUser'
import { RefreshSessionToken } from '../Domain/UseCase/RefreshSessionToken' import { RefreshSessionToken } from '../Domain/UseCase/RefreshSessionToken'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/session') @controller('/session')
export class SessionController extends BaseHttpController { export class SessionController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.DeleteSessionForUser) private deleteSessionForUser: DeleteSessionForUser, @inject(TYPES.Auth_DeleteSessionForUser) private deleteSessionForUser: DeleteSessionForUser,
@inject(TYPES.DeletePreviousSessionsForUser) private deletePreviousSessionsForUser: DeletePreviousSessionsForUser, @inject(TYPES.Auth_DeletePreviousSessionsForUser)
@inject(TYPES.RefreshSessionToken) private refreshSessionToken: RefreshSessionToken, private deletePreviousSessionsForUser: DeletePreviousSessionsForUser,
@inject(TYPES.Auth_RefreshSessionToken) private refreshSessionToken: RefreshSessionToken,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) { ) {
super() super()
this.controllerContainer.register('auth.session.delete', this.deleteSession.bind(this))
this.controllerContainer.register('auth.session.deleteAll', this.deleteAllSessions.bind(this))
this.controllerContainer.register('auth.session.refresh', this.refresh.bind(this))
} }
@httpDelete('/', TYPES.AuthMiddleware, TYPES.SessionMiddleware) @httpDelete('/', TYPES.Auth_AuthMiddleware, TYPES.Auth_SessionMiddleware)
async deleteSession(request: Request, response: Response): Promise<results.JsonResult | void> { async deleteSession(request: Request, response: Response): Promise<results.JsonResult | void> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(
@ -80,7 +87,7 @@ export class SessionController extends BaseHttpController {
response.status(204).send() response.status(204).send()
} }
@httpDelete('/all', TYPES.AuthMiddleware, TYPES.SessionMiddleware) @httpDelete('/all', TYPES.Auth_AuthMiddleware, TYPES.Auth_SessionMiddleware)
async deleteAllSessions(_request: Request, response: Response): Promise<results.JsonResult | void> { async deleteAllSessions(_request: Request, response: Response): Promise<results.JsonResult | void> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(

View file

@ -10,6 +10,7 @@ import { GetActiveSessionsForUser } from '../Domain/UseCase/GetActiveSessionsFor
import { AuthenticateRequest } from '../Domain/UseCase/AuthenticateRequest' import { AuthenticateRequest } from '../Domain/UseCase/AuthenticateRequest'
import { User } from '../Domain/User/User' import { User } from '../Domain/User/User'
import { CreateCrossServiceToken } from '../Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken' import { CreateCrossServiceToken } from '../Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('SessionsController', () => { describe('SessionsController', () => {
let getActiveSessionsForUser: GetActiveSessionsForUser let getActiveSessionsForUser: GetActiveSessionsForUser
@ -20,11 +21,21 @@ describe('SessionsController', () => {
let response: express.Response let response: express.Response
let user: User let user: User
let createCrossServiceToken: CreateCrossServiceToken let createCrossServiceToken: CreateCrossServiceToken
let controllerContainer: ControllerContainerInterface
const createController = () => const createController = () =>
new SessionsController(getActiveSessionsForUser, authenticateRequest, sessionProjector, createCrossServiceToken) new SessionsController(
getActiveSessionsForUser,
authenticateRequest,
sessionProjector,
createCrossServiceToken,
controllerContainer,
)
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
session = {} as jest.Mocked<Session> session = {} as jest.Mocked<Session>
user = {} as jest.Mocked<User> user = {} as jest.Mocked<User>

View file

@ -16,16 +16,20 @@ import { User } from '../Domain/User/User'
import { ProjectorInterface } from '../Projection/ProjectorInterface' import { ProjectorInterface } from '../Projection/ProjectorInterface'
import { SessionProjector } from '../Projection/SessionProjector' import { SessionProjector } from '../Projection/SessionProjector'
import { CreateCrossServiceToken } from '../Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken' import { CreateCrossServiceToken } from '../Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/sessions') @controller('/sessions')
export class SessionsController extends BaseHttpController { export class SessionsController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.GetActiveSessionsForUser) private getActiveSessionsForUser: GetActiveSessionsForUser, @inject(TYPES.Auth_GetActiveSessionsForUser) private getActiveSessionsForUser: GetActiveSessionsForUser,
@inject(TYPES.AuthenticateRequest) private authenticateRequest: AuthenticateRequest, @inject(TYPES.Auth_AuthenticateRequest) private authenticateRequest: AuthenticateRequest,
@inject(TYPES.SessionProjector) private sessionProjector: ProjectorInterface<Session>, @inject(TYPES.Auth_SessionProjector) private sessionProjector: ProjectorInterface<Session>,
@inject(TYPES.CreateCrossServiceToken) private createCrossServiceToken: CreateCrossServiceToken, @inject(TYPES.Auth_CreateCrossServiceToken) private createCrossServiceToken: CreateCrossServiceToken,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) { ) {
super() super()
this.controllerContainer.register('auth.sessions.list', this.getSessions.bind(this))
} }
@httpPost('/validate') @httpPost('/validate')
@ -56,7 +60,7 @@ export class SessionsController extends BaseHttpController {
return this.json({ authToken: result.token }) return this.json({ authToken: result.token })
} }
@httpGet('/', TYPES.AuthMiddleware, TYPES.SessionMiddleware) @httpGet('/', TYPES.Auth_AuthMiddleware, TYPES.Auth_SessionMiddleware)
async getSessions(_request: Request, response: Response): Promise<results.JsonResult> { async getSessions(_request: Request, response: Response): Promise<results.JsonResult> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json([]) return this.json([])

View file

@ -10,6 +10,7 @@ import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting'
import { UpdateSetting } from '../Domain/UseCase/UpdateSetting/UpdateSetting' import { UpdateSetting } from '../Domain/UseCase/UpdateSetting/UpdateSetting'
import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting' import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting'
import { EncryptionVersion } from '../Domain/Encryption/EncryptionVersion' import { EncryptionVersion } from '../Domain/Encryption/EncryptionVersion'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('SettingsController', () => { describe('SettingsController', () => {
let deleteSetting: DeleteSetting let deleteSetting: DeleteSetting
@ -20,10 +21,15 @@ describe('SettingsController', () => {
let request: express.Request let request: express.Request
let response: express.Response let response: express.Response
let user: User let user: User
let controllerContainer: ControllerContainerInterface
const createController = () => new SettingsController(getSettings, getSetting, updateSetting, deleteSetting) const createController = () =>
new SettingsController(getSettings, getSetting, updateSetting, deleteSetting, controllerContainer)
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
deleteSetting = {} as jest.Mocked<DeleteSetting> deleteSetting = {} as jest.Mocked<DeleteSetting>
deleteSetting.execute = jest.fn().mockReturnValue({ success: true }) deleteSetting.execute = jest.fn().mockReturnValue({ success: true })

View file

@ -16,19 +16,26 @@ import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting'
import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting' import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting'
import { GetSettings } from '../Domain/UseCase/GetSettings/GetSettings' import { GetSettings } from '../Domain/UseCase/GetSettings/GetSettings'
import { UpdateSetting } from '../Domain/UseCase/UpdateSetting/UpdateSetting' import { UpdateSetting } from '../Domain/UseCase/UpdateSetting/UpdateSetting'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/users/:userUuid') @controller('/users/:userUuid')
export class SettingsController extends BaseHttpController { export class SettingsController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.GetSettings) private doGetSettings: GetSettings, @inject(TYPES.Auth_GetSettings) private doGetSettings: GetSettings,
@inject(TYPES.GetSetting) private doGetSetting: GetSetting, @inject(TYPES.Auth_GetSetting) private doGetSetting: GetSetting,
@inject(TYPES.UpdateSetting) private doUpdateSetting: UpdateSetting, @inject(TYPES.Auth_UpdateSetting) private doUpdateSetting: UpdateSetting,
@inject(TYPES.DeleteSetting) private doDeleteSetting: DeleteSetting, @inject(TYPES.Auth_DeleteSetting) private doDeleteSetting: DeleteSetting,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) { ) {
super() super()
this.controllerContainer.register('auth.users.getSettings', this.getSettings.bind(this))
this.controllerContainer.register('auth.users.getSetting', this.getSetting.bind(this))
this.controllerContainer.register('auth.users.updateSetting', this.updateSetting.bind(this))
this.controllerContainer.register('auth.users.deleteSetting', this.deleteSetting.bind(this))
} }
@httpGet('/settings', TYPES.ApiGatewayAuthMiddleware) @httpGet('/settings', TYPES.Auth_ApiGatewayAuthMiddleware)
async getSettings(request: Request, response: Response): Promise<results.JsonResult> { async getSettings(request: Request, response: Response): Promise<results.JsonResult> {
if (request.params.userUuid !== response.locals.user.uuid) { if (request.params.userUuid !== response.locals.user.uuid) {
return this.json( return this.json(
@ -47,7 +54,7 @@ export class SettingsController extends BaseHttpController {
return this.json(result) return this.json(result)
} }
@httpGet('/settings/:settingName', TYPES.ApiGatewayAuthMiddleware) @httpGet('/settings/:settingName', TYPES.Auth_ApiGatewayAuthMiddleware)
async getSetting(request: Request, response: Response): Promise<results.JsonResult> { async getSetting(request: Request, response: Response): Promise<results.JsonResult> {
if (request.params.userUuid !== response.locals.user.uuid) { if (request.params.userUuid !== response.locals.user.uuid) {
return this.json( return this.json(
@ -70,7 +77,7 @@ export class SettingsController extends BaseHttpController {
return this.json(result, 400) return this.json(result, 400)
} }
@httpPut('/settings', TYPES.ApiGatewayAuthMiddleware) @httpPut('/settings', TYPES.Auth_ApiGatewayAuthMiddleware)
async updateSetting(request: Request, response: Response): Promise<results.JsonResult | results.StatusCodeResult> { async updateSetting(request: Request, response: Response): Promise<results.JsonResult | results.StatusCodeResult> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(
@ -117,7 +124,7 @@ export class SettingsController extends BaseHttpController {
return this.json(result, result.statusCode) return this.json(result, result.statusCode)
} }
@httpDelete('/settings/:settingName', TYPES.ApiGatewayAuthMiddleware) @httpDelete('/settings/:settingName', TYPES.Auth_ApiGatewayAuthMiddleware)
async deleteSetting(request: Request, response: Response): Promise<results.JsonResult> { async deleteSetting(request: Request, response: Response): Promise<results.JsonResult> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(

View file

@ -26,14 +26,14 @@ import { ListSharedSubscriptionInvitations } from '../Domain/UseCase/ListSharedS
@injectable() @injectable()
export class SubscriptionInvitesController implements SubscriptionServerInterface { export class SubscriptionInvitesController implements SubscriptionServerInterface {
constructor( constructor(
@inject(TYPES.InviteToSharedSubscription) private inviteToSharedSubscription: InviteToSharedSubscription, @inject(TYPES.Auth_InviteToSharedSubscription) private inviteToSharedSubscription: InviteToSharedSubscription,
@inject(TYPES.AcceptSharedSubscriptionInvitation) @inject(TYPES.Auth_AcceptSharedSubscriptionInvitation)
private acceptSharedSubscriptionInvitation: AcceptSharedSubscriptionInvitation, private acceptSharedSubscriptionInvitation: AcceptSharedSubscriptionInvitation,
@inject(TYPES.DeclineSharedSubscriptionInvitation) @inject(TYPES.Auth_DeclineSharedSubscriptionInvitation)
private declineSharedSubscriptionInvitation: DeclineSharedSubscriptionInvitation, private declineSharedSubscriptionInvitation: DeclineSharedSubscriptionInvitation,
@inject(TYPES.CancelSharedSubscriptionInvitation) @inject(TYPES.Auth_CancelSharedSubscriptionInvitation)
private cancelSharedSubscriptionInvitation: CancelSharedSubscriptionInvitation, private cancelSharedSubscriptionInvitation: CancelSharedSubscriptionInvitation,
@inject(TYPES.ListSharedSubscriptionInvitations) @inject(TYPES.Auth_ListSharedSubscriptionInvitations)
private listSharedSubscriptionInvitations: ListSharedSubscriptionInvitations, private listSharedSubscriptionInvitations: ListSharedSubscriptionInvitations,
) {} ) {}

View file

@ -6,6 +6,7 @@ import { results } from 'inversify-express-utils'
import { User } from '../Domain/User/User' import { User } from '../Domain/User/User'
import { SubscriptionSettingsController } from './SubscriptionSettingsController' import { SubscriptionSettingsController } from './SubscriptionSettingsController'
import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting' import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('SubscriptionSettingsController', () => { describe('SubscriptionSettingsController', () => {
let getSetting: GetSetting let getSetting: GetSetting
@ -13,10 +14,14 @@ describe('SubscriptionSettingsController', () => {
let request: express.Request let request: express.Request
let response: express.Response let response: express.Response
let user: User let user: User
let controllerContainer: ControllerContainerInterface
const createController = () => new SubscriptionSettingsController(getSetting) const createController = () => new SubscriptionSettingsController(getSetting, controllerContainer)
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
user = {} as jest.Mocked<User> user = {} as jest.Mocked<User>
user.uuid = '123' user.uuid = '123'

View file

@ -9,14 +9,20 @@ import {
} from 'inversify-express-utils' } from 'inversify-express-utils'
import TYPES from '../Bootstrap/Types' import TYPES from '../Bootstrap/Types'
import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting' import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/users/:userUuid') @controller('/users/:userUuid')
export class SubscriptionSettingsController extends BaseHttpController { export class SubscriptionSettingsController extends BaseHttpController {
constructor(@inject(TYPES.GetSetting) private doGetSetting: GetSetting) { constructor(
@inject(TYPES.Auth_GetSetting) private doGetSetting: GetSetting,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) {
super() super()
this.controllerContainer.register('auth.users.getSubscriptionSetting', this.getSubscriptionSetting.bind(this))
} }
@httpGet('/subscription-settings/:subscriptionSettingName', TYPES.ApiGatewayAuthMiddleware) @httpGet('/subscription-settings/:subscriptionSettingName', TYPES.Auth_ApiGatewayAuthMiddleware)
async getSubscriptionSetting(request: Request, response: Response): Promise<results.JsonResult> { async getSubscriptionSetting(request: Request, response: Response): Promise<results.JsonResult> {
const result = await this.doGetSetting.execute({ const result = await this.doGetSetting.execute({
userUuid: response.locals.user.uuid, userUuid: response.locals.user.uuid,

View file

@ -13,6 +13,7 @@ import { Role } from '../Domain/Role/Role'
import { SettingServiceInterface } from '../Domain/Setting/SettingServiceInterface' import { SettingServiceInterface } from '../Domain/Setting/SettingServiceInterface'
import { Setting } from '../Domain/Setting/Setting' import { Setting } from '../Domain/Setting/Setting'
import { CrossServiceTokenData, TokenEncoderInterface } from '@standardnotes/security' import { CrossServiceTokenData, TokenEncoderInterface } from '@standardnotes/security'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('SubscriptionTokensController', () => { describe('SubscriptionTokensController', () => {
let createSubscriptionToken: CreateSubscriptionToken let createSubscriptionToken: CreateSubscriptionToken
@ -29,6 +30,8 @@ describe('SubscriptionTokensController', () => {
let user: User let user: User
let role: Role let role: Role
let controllerContainer: ControllerContainerInterface
const createController = () => const createController = () =>
new SubscriptionTokensController( new SubscriptionTokensController(
createSubscriptionToken, createSubscriptionToken,
@ -38,9 +41,13 @@ describe('SubscriptionTokensController', () => {
roleProjector, roleProjector,
tokenEncoder, tokenEncoder,
jwtTTL, jwtTTL,
controllerContainer,
) )
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
user = {} as jest.Mocked<User> user = {} as jest.Mocked<User>
user.uuid = '123' user.uuid = '123'
user.roles = Promise.resolve([role]) user.roles = Promise.resolve([role])

View file

@ -18,22 +18,26 @@ import { AuthenticateSubscriptionToken } from '../Domain/UseCase/AuthenticateSub
import { CreateSubscriptionToken } from '../Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken' import { CreateSubscriptionToken } from '../Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken'
import { User } from '../Domain/User/User' import { User } from '../Domain/User/User'
import { ProjectorInterface } from '../Projection/ProjectorInterface' import { ProjectorInterface } from '../Projection/ProjectorInterface'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/subscription-tokens') @controller('/subscription-tokens')
export class SubscriptionTokensController extends BaseHttpController { export class SubscriptionTokensController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken, @inject(TYPES.Auth_CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken,
@inject(TYPES.AuthenticateSubscriptionToken) private authenticateToken: AuthenticateSubscriptionToken, @inject(TYPES.Auth_AuthenticateSubscriptionToken) private authenticateToken: AuthenticateSubscriptionToken,
@inject(TYPES.SettingService) private settingService: SettingServiceInterface, @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface,
@inject(TYPES.UserProjector) private userProjector: ProjectorInterface<User>, @inject(TYPES.Auth_UserProjector) private userProjector: ProjectorInterface<User>,
@inject(TYPES.RoleProjector) private roleProjector: ProjectorInterface<Role>, @inject(TYPES.Auth_RoleProjector) private roleProjector: ProjectorInterface<Role>,
@inject(TYPES.CrossServiceTokenEncoder) private tokenEncoder: TokenEncoderInterface<CrossServiceTokenData>, @inject(TYPES.Auth_CrossServiceTokenEncoder) private tokenEncoder: TokenEncoderInterface<CrossServiceTokenData>,
@inject(TYPES.AUTH_JWT_TTL) private jwtTTL: number, @inject(TYPES.Auth_AUTH_JWT_TTL) private jwtTTL: number,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) { ) {
super() super()
this.controllerContainer.register('auth.subscription-tokens.create', this.createToken.bind(this))
} }
@httpPost('/', TYPES.ApiGatewayAuthMiddleware) @httpPost('/', TYPES.Auth_ApiGatewayAuthMiddleware)
async createToken(_request: Request, response: Response): Promise<results.JsonResult> { async createToken(_request: Request, response: Response): Promise<results.JsonResult> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(

View file

@ -6,7 +6,7 @@ import { ProcessUserRequest } from '../Domain/UseCase/ProcessUserRequest/Process
@injectable() @injectable()
export class UserRequestsController implements UserRequestServerInterface { export class UserRequestsController implements UserRequestServerInterface {
constructor(@inject(TYPES.ProcessUserRequest) private processUserRequest: ProcessUserRequest) {} constructor(@inject(TYPES.Auth_ProcessUserRequest) private processUserRequest: ProcessUserRequest) {}
async submitUserRequest(params: UserRequestRequestParams): Promise<HttpResponse<UserRequestResponseBody>> { async submitUserRequest(params: UserRequestRequestParams): Promise<HttpResponse<UserRequestResponseBody>> {
const result = await this.processUserRequest.execute({ const result = await this.processUserRequest.execute({

View file

@ -13,6 +13,7 @@ import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts'
import { IncreaseLoginAttempts } from '../Domain/UseCase/IncreaseLoginAttempts' import { IncreaseLoginAttempts } from '../Domain/UseCase/IncreaseLoginAttempts'
import { ChangeCredentials } from '../Domain/UseCase/ChangeCredentials/ChangeCredentials' import { ChangeCredentials } from '../Domain/UseCase/ChangeCredentials/ChangeCredentials'
import { InviteToSharedSubscription } from '../Domain/UseCase/InviteToSharedSubscription/InviteToSharedSubscription' import { InviteToSharedSubscription } from '../Domain/UseCase/InviteToSharedSubscription/InviteToSharedSubscription'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('UsersController', () => { describe('UsersController', () => {
let updateUser: UpdateUser let updateUser: UpdateUser
@ -27,6 +28,7 @@ describe('UsersController', () => {
let request: express.Request let request: express.Request
let response: express.Response let response: express.Response
let user: User let user: User
let controllerContainer: ControllerContainerInterface
const createController = () => const createController = () =>
new UsersController( new UsersController(
@ -37,9 +39,13 @@ describe('UsersController', () => {
clearLoginAttempts, clearLoginAttempts,
increaseLoginAttempts, increaseLoginAttempts,
changeCredentials, changeCredentials,
controllerContainer,
) )
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
updateUser = {} as jest.Mocked<UpdateUser> updateUser = {} as jest.Mocked<UpdateUser>
updateUser.execute = jest.fn() updateUser.execute = jest.fn()

View file

@ -19,22 +19,29 @@ import { GetUserSubscription } from '../Domain/UseCase/GetUserSubscription/GetUs
import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts' import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts'
import { IncreaseLoginAttempts } from '../Domain/UseCase/IncreaseLoginAttempts' import { IncreaseLoginAttempts } from '../Domain/UseCase/IncreaseLoginAttempts'
import { ChangeCredentials } from '../Domain/UseCase/ChangeCredentials/ChangeCredentials' import { ChangeCredentials } from '../Domain/UseCase/ChangeCredentials/ChangeCredentials'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
@controller('/users') @controller('/users')
export class UsersController extends BaseHttpController { export class UsersController extends BaseHttpController {
constructor( constructor(
@inject(TYPES.UpdateUser) private updateUser: UpdateUser, @inject(TYPES.Auth_UpdateUser) private updateUser: UpdateUser,
@inject(TYPES.GetUserKeyParams) private getUserKeyParams: GetUserKeyParams, @inject(TYPES.Auth_GetUserKeyParams) private getUserKeyParams: GetUserKeyParams,
@inject(TYPES.DeleteAccount) private doDeleteAccount: DeleteAccount, @inject(TYPES.Auth_DeleteAccount) private doDeleteAccount: DeleteAccount,
@inject(TYPES.GetUserSubscription) private doGetUserSubscription: GetUserSubscription, @inject(TYPES.Auth_GetUserSubscription) private doGetUserSubscription: GetUserSubscription,
@inject(TYPES.ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts, @inject(TYPES.Auth_ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts,
@inject(TYPES.IncreaseLoginAttempts) private increaseLoginAttempts: IncreaseLoginAttempts, @inject(TYPES.Auth_IncreaseLoginAttempts) private increaseLoginAttempts: IncreaseLoginAttempts,
@inject(TYPES.ChangeCredentials) private changeCredentialsUseCase: ChangeCredentials, @inject(TYPES.Auth_ChangeCredentials) private changeCredentialsUseCase: ChangeCredentials,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) { ) {
super() super()
this.controllerContainer.register('auth.users.update', this.update.bind(this))
this.controllerContainer.register('auth.users.getKeyParams', this.keyParams.bind(this))
this.controllerContainer.register('auth.users.getSubscription', this.getSubscription.bind(this))
this.controllerContainer.register('auth.users.updateCredentials', this.changeCredentials.bind(this))
} }
@httpPatch('/:userId', TYPES.ApiGatewayAuthMiddleware) @httpPatch('/:userId', TYPES.Auth_ApiGatewayAuthMiddleware)
async update(request: Request, response: Response): Promise<results.JsonResult | void> { async update(request: Request, response: Response): Promise<results.JsonResult | void> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(
@ -125,7 +132,7 @@ export class UsersController extends BaseHttpController {
return this.json({ message: result.message }, result.responseCode) return this.json({ message: result.message }, result.responseCode)
} }
@httpGet('/:userUuid/subscription', TYPES.ApiGatewayAuthMiddleware) @httpGet('/:userUuid/subscription', TYPES.Auth_ApiGatewayAuthMiddleware)
async getSubscription(request: Request, response: Response): Promise<results.JsonResult> { async getSubscription(request: Request, response: Response): Promise<results.JsonResult> {
if (request.params.userUuid !== response.locals.user.uuid) { if (request.params.userUuid !== response.locals.user.uuid) {
return this.json( return this.json(
@ -149,7 +156,7 @@ export class UsersController extends BaseHttpController {
return this.json(result, 400) return this.json(result, 400)
} }
@httpPut('/:userId/attributes/credentials', TYPES.AuthMiddleware) @httpPut('/:userId/attributes/credentials', TYPES.Auth_AuthMiddleware)
async changeCredentials(request: Request, response: Response): Promise<results.JsonResult | void> { async changeCredentials(request: Request, response: Response): Promise<results.JsonResult | void> {
if (response.locals.readOnlyAccess) { if (response.locals.readOnlyAccess) {
return this.json( return this.json(

View file

@ -4,15 +4,20 @@ import { Request, Response } from 'express'
import { results } from 'inversify-express-utils' import { results } from 'inversify-express-utils'
import { ValetTokenController } from './ValetTokenController' import { ValetTokenController } from './ValetTokenController'
import { CreateValetToken } from '../Domain/UseCase/CreateValetToken/CreateValetToken' import { CreateValetToken } from '../Domain/UseCase/CreateValetToken/CreateValetToken'
import { ControllerContainerInterface } from '@standardnotes/domain-core'
describe('ValetTokenController', () => { describe('ValetTokenController', () => {
let createValetToken: CreateValetToken let createValetToken: CreateValetToken
let request: Request let request: Request
let response: Response let response: Response
let controllerContainer: ControllerContainerInterface
const createController = () => new ValetTokenController(createValetToken) const createController = () => new ValetTokenController(createValetToken, controllerContainer)
beforeEach(() => { beforeEach(() => {
controllerContainer = {} as jest.Mocked<ControllerContainerInterface>
controllerContainer.register = jest.fn()
createValetToken = {} as jest.Mocked<CreateValetToken> createValetToken = {} as jest.Mocked<CreateValetToken>
createValetToken.execute = jest.fn().mockReturnValue({ success: true, valetToken: 'foobar' }) createValetToken.execute = jest.fn().mockReturnValue({ success: true, valetToken: 'foobar' })

View file

@ -9,15 +9,20 @@ import {
} from 'inversify-express-utils' } from 'inversify-express-utils'
import { CreateValetTokenPayload, ErrorTag } from '@standardnotes/responses' import { CreateValetTokenPayload, ErrorTag } from '@standardnotes/responses'
import { ValetTokenOperation } from '@standardnotes/security' import { ValetTokenOperation } from '@standardnotes/security'
import { Uuid } from '@standardnotes/domain-core' import { ControllerContainerInterface, Uuid } from '@standardnotes/domain-core'
import TYPES from '../Bootstrap/Types' import TYPES from '../Bootstrap/Types'
import { CreateValetToken } from '../Domain/UseCase/CreateValetToken/CreateValetToken' import { CreateValetToken } from '../Domain/UseCase/CreateValetToken/CreateValetToken'
@controller('/valet-tokens', TYPES.ApiGatewayAuthMiddleware) @controller('/valet-tokens', TYPES.Auth_ApiGatewayAuthMiddleware)
export class ValetTokenController extends BaseHttpController { export class ValetTokenController extends BaseHttpController {
constructor(@inject(TYPES.CreateValetToken) private createValetKey: CreateValetToken) { constructor(
@inject(TYPES.Auth_CreateValetToken) private createValetKey: CreateValetToken,
@inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface,
) {
super() super()
this.controllerContainer.register('auth.valet-tokens.create', this.create.bind(this))
} }
@httpPost('/') @httpPost('/')

View file

@ -15,9 +15,9 @@ import { AuthResponseFactoryInterface } from './AuthResponseFactoryInterface'
@injectable() @injectable()
export class AuthResponseFactory20161215 implements AuthResponseFactoryInterface { export class AuthResponseFactory20161215 implements AuthResponseFactoryInterface {
constructor( constructor(
@inject(TYPES.UserProjector) protected userProjector: ProjectorInterface<User>, @inject(TYPES.Auth_UserProjector) protected userProjector: ProjectorInterface<User>,
@inject(TYPES.SessionTokenEncoder) protected tokenEncoder: TokenEncoderInterface<SessionTokenData>, @inject(TYPES.Auth_SessionTokenEncoder) protected tokenEncoder: TokenEncoderInterface<SessionTokenData>,
@inject(TYPES.Logger) protected logger: Logger, @inject(TYPES.Auth_Logger) protected logger: Logger,
) {} ) {}
async createResponse(dto: { async createResponse(dto: {

View file

@ -23,13 +23,13 @@ import { AuthResponse20200115 } from './AuthResponse20200115'
@injectable() @injectable()
export class AuthResponseFactory20200115 extends AuthResponseFactory20190520 { export class AuthResponseFactory20200115 extends AuthResponseFactory20190520 {
constructor( constructor(
@inject(TYPES.SessionService) private sessionService: SessionServiceInterface, @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface,
@inject(TYPES.KeyParamsFactory) private keyParamsFactory: KeyParamsFactoryInterface, @inject(TYPES.Auth_KeyParamsFactory) private keyParamsFactory: KeyParamsFactoryInterface,
@inject(TYPES.UserProjector) userProjector: ProjectorInterface<User>, @inject(TYPES.Auth_UserProjector) userProjector: ProjectorInterface<User>,
@inject(TYPES.SessionTokenEncoder) protected override tokenEncoder: TokenEncoderInterface<SessionTokenData>, @inject(TYPES.Auth_SessionTokenEncoder) protected override tokenEncoder: TokenEncoderInterface<SessionTokenData>,
@inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface,
@inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface,
@inject(TYPES.Logger) logger: Logger, @inject(TYPES.Auth_Logger) logger: Logger,
) { ) {
super(userProjector, tokenEncoder, logger) super(userProjector, tokenEncoder, logger)
} }

View file

@ -11,10 +11,10 @@ import { AuthResponseFactoryResolverInterface } from './AuthResponseFactoryResol
@injectable() @injectable()
export class AuthResponseFactoryResolver implements AuthResponseFactoryResolverInterface { export class AuthResponseFactoryResolver implements AuthResponseFactoryResolverInterface {
constructor( constructor(
@inject(TYPES.AuthResponseFactory20161215) private authResponseFactory20161215: AuthResponseFactory20161215, @inject(TYPES.Auth_AuthResponseFactory20161215) private authResponseFactory20161215: AuthResponseFactory20161215,
@inject(TYPES.AuthResponseFactory20190520) private authResponseFactory20190520: AuthResponseFactory20190520, @inject(TYPES.Auth_AuthResponseFactory20190520) private authResponseFactory20190520: AuthResponseFactory20190520,
@inject(TYPES.AuthResponseFactory20200115) private authResponseFactory20200115: AuthResponseFactory20200115, @inject(TYPES.Auth_AuthResponseFactory20200115) private authResponseFactory20200115: AuthResponseFactory20200115,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
resolveAuthResponseFactoryVersion(apiVersion: string): AuthResponseFactoryInterface { resolveAuthResponseFactoryVersion(apiVersion: string): AuthResponseFactoryInterface {

View file

@ -9,10 +9,10 @@ import { AuthenticationMethodResolverInterface } from './AuthenticationMethodRes
@injectable() @injectable()
export class AuthenticationMethodResolver implements AuthenticationMethodResolverInterface { export class AuthenticationMethodResolver implements AuthenticationMethodResolverInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.SessionService) private sessionService: SessionServiceInterface, @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface,
@inject(TYPES.SessionTokenDecoder) private sessionTokenDecoder: TokenDecoderInterface<SessionTokenData>, @inject(TYPES.Auth_SessionTokenDecoder) private sessionTokenDecoder: TokenDecoderInterface<SessionTokenData>,
@inject(TYPES.FallbackSessionTokenDecoder) @inject(TYPES.Auth_FallbackSessionTokenDecoder)
private fallbackSessionTokenDecoder: TokenDecoderInterface<SessionTokenData>, private fallbackSessionTokenDecoder: TokenDecoderInterface<SessionTokenData>,
) {} ) {}

View file

@ -9,9 +9,9 @@ import { CrypterInterface } from './CrypterInterface'
@injectable() @injectable()
export class CrypterNode implements CrypterInterface { export class CrypterNode implements CrypterInterface {
constructor( constructor(
@inject(TYPES.ENCRYPTION_SERVER_KEY) private encryptionServerKey: string, @inject(TYPES.Auth_ENCRYPTION_SERVER_KEY) private encryptionServerKey: string,
@inject(TYPES.CryptoNode) private cryptoNode: CryptoNode, @inject(TYPES.Auth_CryptoNode) private cryptoNode: CryptoNode,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) { ) {
const keyBuffer = Buffer.from(encryptionServerKey, 'hex') const keyBuffer = Buffer.from(encryptionServerKey, 'hex')
const { byteLength } = keyBuffer const { byteLength } = keyBuffer

View file

@ -30,7 +30,7 @@ import { DomainEventFactoryInterface } from './DomainEventFactoryInterface'
@injectable() @injectable()
export class DomainEventFactory implements DomainEventFactoryInterface { export class DomainEventFactory implements DomainEventFactoryInterface {
constructor(@inject(TYPES.Timer) private timer: TimerInterface) {} constructor(@inject(TYPES.Auth_Timer) private timer: TimerInterface) {}
createSessionCreatedEvent(dto: { userUuid: string }): SessionCreatedEvent { createSessionCreatedEvent(dto: { userUuid: string }): SessionCreatedEvent {
return { return {

View file

@ -15,10 +15,10 @@ import { TimerInterface } from '@standardnotes/time'
@injectable() @injectable()
export class FeatureService implements FeatureServiceInterface { export class FeatureService implements FeatureServiceInterface {
constructor( constructor(
@inject(TYPES.RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface, @inject(TYPES.Auth_RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface,
@inject(TYPES.OfflineUserSubscriptionRepository) @inject(TYPES.Auth_OfflineUserSubscriptionRepository)
private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface,
@inject(TYPES.Timer) private timer: TimerInterface, @inject(TYPES.Auth_Timer) private timer: TimerInterface,
) {} ) {}
async userIsEntitledToFeature(user: User, featureIdentifier: string): Promise<boolean> { async userIsEntitledToFeature(user: User, featureIdentifier: string): Promise<boolean> {

View file

@ -10,11 +10,12 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
@injectable() @injectable()
export class AccountDeletionRequestedEventHandler implements DomainEventHandlerInterface { export class AccountDeletionRequestedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface,
@inject(TYPES.EphemeralSessionRepository) private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, @inject(TYPES.Auth_EphemeralSessionRepository)
@inject(TYPES.RevokedSessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, private ephemeralSessionRepository: EphemeralSessionRepositoryInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_RevokedSessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: AccountDeletionRequestedEvent): Promise<void> { async handle(event: AccountDeletionRequestedEvent): Promise<void> {

View file

@ -16,11 +16,11 @@ import { Username } from '@standardnotes/domain-core'
@injectable() @injectable()
export class ExtensionKeyGrantedEventHandler implements DomainEventHandlerInterface { export class ExtensionKeyGrantedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.SettingService) private settingService: SettingServiceInterface, @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface,
@inject(TYPES.OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface, @inject(TYPES.Auth_OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface,
@inject(TYPES.ContenDecoder) private contentDecoder: ContentDecoderInterface, @inject(TYPES.Auth_ContenDecoder) private contentDecoder: ContentDecoderInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: ExtensionKeyGrantedEvent): Promise<void> { async handle(event: ExtensionKeyGrantedEvent): Promise<void> {

View file

@ -12,9 +12,10 @@ import { UserSubscriptionServiceInterface } from '../Subscription/UserSubscripti
@injectable() @injectable()
export class FileRemovedEventHandler implements DomainEventHandlerInterface { export class FileRemovedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface,
@inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, @inject(TYPES.Auth_SubscriptionSettingService)
@inject(TYPES.Logger) private logger: Logger, private subscriptionSettingService: SubscriptionSettingServiceInterface,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: FileRemovedEvent): Promise<void> { async handle(event: FileRemovedEvent): Promise<void> {

View file

@ -13,10 +13,11 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
@injectable() @injectable()
export class FileUploadedEventHandler implements DomainEventHandlerInterface { export class FileUploadedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface,
@inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, @inject(TYPES.Auth_SubscriptionSettingService)
@inject(TYPES.Logger) private logger: Logger, private subscriptionSettingService: SubscriptionSettingServiceInterface,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: FileUploadedEvent): Promise<void> { async handle(event: FileUploadedEvent): Promise<void> {

View file

@ -11,9 +11,9 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
@injectable() @injectable()
export class ListedAccountCreatedEventHandler implements DomainEventHandlerInterface { export class ListedAccountCreatedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.SettingService) private settingService: SettingServiceInterface, @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: ListedAccountCreatedEvent): Promise<void> { async handle(event: ListedAccountCreatedEvent): Promise<void> {

View file

@ -11,9 +11,9 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
@injectable() @injectable()
export class ListedAccountDeletedEventHandler implements DomainEventHandlerInterface { export class ListedAccountDeletedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.SettingService) private settingService: SettingServiceInterface, @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: ListedAccountDeletedEvent): Promise<void> { async handle(event: ListedAccountDeletedEvent): Promise<void> {

View file

@ -16,11 +16,11 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
@injectable() @injectable()
export class PredicateVerificationRequestedEventHandler implements DomainEventHandlerInterface { export class PredicateVerificationRequestedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.VerifyPredicate) private verifyPredicate: VerifyPredicate, @inject(TYPES.Auth_VerifyPredicate) private verifyPredicate: VerifyPredicate,
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface,
@inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: PredicateVerificationRequestedEvent): Promise<void> { async handle(event: PredicateVerificationRequestedEvent): Promise<void> {

View file

@ -8,7 +8,7 @@ import { AcceptSharedSubscriptionInvitation } from '../UseCase/AcceptSharedSubsc
@injectable() @injectable()
export class SharedSubscriptionInvitationCreatedEventHandler implements DomainEventHandlerInterface { export class SharedSubscriptionInvitationCreatedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.AcceptSharedSubscriptionInvitation) @inject(TYPES.Auth_AcceptSharedSubscriptionInvitation)
private acceptSharedSubscriptionInvitation: AcceptSharedSubscriptionInvitation, private acceptSharedSubscriptionInvitation: AcceptSharedSubscriptionInvitation,
) {} ) {}

View file

@ -8,8 +8,9 @@ import { OfflineUserSubscriptionRepositoryInterface } from '../Subscription/Offl
@injectable() @injectable()
export class SubscriptionCancelledEventHandler implements DomainEventHandlerInterface { export class SubscriptionCancelledEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, @inject(TYPES.Auth_UserSubscriptionRepository)
@inject(TYPES.OfflineUserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface,
@inject(TYPES.Auth_OfflineUserSubscriptionRepository)
private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface,
) {} ) {}

View file

@ -12,12 +12,13 @@ import { Username } from '@standardnotes/domain-core'
@injectable() @injectable()
export class SubscriptionExpiredEventHandler implements DomainEventHandlerInterface { export class SubscriptionExpiredEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, @inject(TYPES.Auth_UserSubscriptionRepository)
@inject(TYPES.OfflineUserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface,
@inject(TYPES.Auth_OfflineUserSubscriptionRepository)
private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface,
@inject(TYPES.RoleService) private roleService: RoleServiceInterface, @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: SubscriptionExpiredEvent): Promise<void> { async handle(event: SubscriptionExpiredEvent): Promise<void> {

View file

@ -17,13 +17,15 @@ import { Username } from '@standardnotes/domain-core'
@injectable() @injectable()
export class SubscriptionPurchasedEventHandler implements DomainEventHandlerInterface { export class SubscriptionPurchasedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, @inject(TYPES.Auth_UserSubscriptionRepository)
@inject(TYPES.OfflineUserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface,
@inject(TYPES.Auth_OfflineUserSubscriptionRepository)
private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface,
@inject(TYPES.RoleService) private roleService: RoleServiceInterface, @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface,
@inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, @inject(TYPES.Auth_SubscriptionSettingService)
@inject(TYPES.Logger) private logger: Logger, private subscriptionSettingService: SubscriptionSettingServiceInterface,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: SubscriptionPurchasedEvent): Promise<void> { async handle(event: SubscriptionPurchasedEvent): Promise<void> {

View file

@ -18,12 +18,14 @@ import { Username } from '@standardnotes/domain-core'
@injectable() @injectable()
export class SubscriptionReassignedEventHandler implements DomainEventHandlerInterface { export class SubscriptionReassignedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, @inject(TYPES.Auth_UserSubscriptionRepository)
@inject(TYPES.RoleService) private roleService: RoleServiceInterface, private userSubscriptionRepository: UserSubscriptionRepositoryInterface,
@inject(TYPES.SettingService) private settingService: SettingServiceInterface, @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface,
@inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_SubscriptionSettingService)
private subscriptionSettingService: SubscriptionSettingServiceInterface,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: SubscriptionReassignedEvent): Promise<void> { async handle(event: SubscriptionReassignedEvent): Promise<void> {

View file

@ -12,12 +12,13 @@ import { Username } from '@standardnotes/domain-core'
@injectable() @injectable()
export class SubscriptionRefundedEventHandler implements DomainEventHandlerInterface { export class SubscriptionRefundedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, @inject(TYPES.Auth_UserSubscriptionRepository)
@inject(TYPES.OfflineUserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface,
@inject(TYPES.Auth_OfflineUserSubscriptionRepository)
private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface,
@inject(TYPES.RoleService) private roleService: RoleServiceInterface, @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: SubscriptionRefundedEvent): Promise<void> { async handle(event: SubscriptionRefundedEvent): Promise<void> {

View file

@ -13,12 +13,13 @@ import { Username } from '@standardnotes/domain-core'
@injectable() @injectable()
export class SubscriptionRenewedEventHandler implements DomainEventHandlerInterface { export class SubscriptionRenewedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, @inject(TYPES.Auth_UserSubscriptionRepository)
@inject(TYPES.OfflineUserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface,
@inject(TYPES.Auth_OfflineUserSubscriptionRepository)
private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface,
@inject(TYPES.RoleService) private roleService: RoleServiceInterface, @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: SubscriptionRenewedEvent): Promise<void> { async handle(event: SubscriptionRenewedEvent): Promise<void> {

View file

@ -24,16 +24,18 @@ import { Username } from '@standardnotes/domain-core'
@injectable() @injectable()
export class SubscriptionSyncRequestedEventHandler implements DomainEventHandlerInterface { export class SubscriptionSyncRequestedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface,
@inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, @inject(TYPES.Auth_UserSubscriptionRepository)
@inject(TYPES.OfflineUserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface,
@inject(TYPES.Auth_OfflineUserSubscriptionRepository)
private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface,
@inject(TYPES.RoleService) private roleService: RoleServiceInterface, @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface,
@inject(TYPES.SettingService) private settingService: SettingServiceInterface, @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface,
@inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, @inject(TYPES.Auth_SubscriptionSettingService)
@inject(TYPES.OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface, private subscriptionSettingService: SubscriptionSettingServiceInterface,
@inject(TYPES.ContenDecoder) private contentDecoder: ContentDecoderInterface, @inject(TYPES.Auth_OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_ContenDecoder) private contentDecoder: ContentDecoderInterface,
@inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: SubscriptionSyncRequestedEvent): Promise<void> { async handle(event: SubscriptionSyncRequestedEvent): Promise<void> {

View file

@ -8,8 +8,8 @@ import { SessionRepositoryInterface } from '../Session/SessionRepositoryInterfac
@injectable() @injectable()
export class UserDisabledSessionUserAgentLoggingEventHandler implements DomainEventHandlerInterface { export class UserDisabledSessionUserAgentLoggingEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface,
@inject(TYPES.SessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, @inject(TYPES.Auth_SessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface,
) {} ) {}
async handle(event: UserDisabledSessionUserAgentLoggingEvent): Promise<void> { async handle(event: UserDisabledSessionUserAgentLoggingEvent): Promise<void> {

View file

@ -8,10 +8,10 @@ import TYPES from '../../Bootstrap/Types'
@injectable() @injectable()
export class UserEmailChangedEventHandler implements DomainEventHandlerInterface { export class UserEmailChangedEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.HTTPClient) private httpClient: AxiosInstance, @inject(TYPES.Auth_HTTPClient) private httpClient: AxiosInstance,
@inject(TYPES.USER_SERVER_CHANGE_EMAIL_URL) private userServerChangeEmailUrl: string, @inject(TYPES.Auth_USER_SERVER_CHANGE_EMAIL_URL) private userServerChangeEmailUrl: string,
@inject(TYPES.USER_SERVER_AUTH_KEY) private userServerAuthKey: string, @inject(TYPES.Auth_USER_SERVER_AUTH_KEY) private userServerAuthKey: string,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: UserEmailChangedEvent): Promise<void> { async handle(event: UserEmailChangedEvent): Promise<void> {

View file

@ -8,10 +8,10 @@ import TYPES from '../../Bootstrap/Types'
@injectable() @injectable()
export class UserRegisteredEventHandler implements DomainEventHandlerInterface { export class UserRegisteredEventHandler implements DomainEventHandlerInterface {
constructor( constructor(
@inject(TYPES.HTTPClient) private httpClient: AxiosInstance, @inject(TYPES.Auth_HTTPClient) private httpClient: AxiosInstance,
@inject(TYPES.USER_SERVER_REGISTRATION_URL) private userServerRegistrationUrl: string, @inject(TYPES.Auth_USER_SERVER_REGISTRATION_URL) private userServerRegistrationUrl: string,
@inject(TYPES.USER_SERVER_AUTH_KEY) private userServerAuthKey: string, @inject(TYPES.Auth_USER_SERVER_AUTH_KEY) private userServerAuthKey: string,
@inject(TYPES.Logger) private logger: Logger, @inject(TYPES.Auth_Logger) private logger: Logger,
) {} ) {}
async handle(event: UserRegisteredEvent): Promise<void> { async handle(event: UserRegisteredEvent): Promise<void> {

Some files were not shown because too many files have changed in this diff Show more