diff --git a/openapitools-config.json b/openapitools-config.json index 3570d978..5740f1e6 100644 --- a/openapitools-config.json +++ b/openapitools-config.json @@ -2,6 +2,9 @@ "apiPackage": "api", "enumNameSuffix": "", "enumPropertyNaming": "UPPERCASE", + "fileNaming": "kebab-case", + "generateAliasAsModel": true, + "importFileExtension": ".js", "modelPackage": "models", "supportsES6": true, "withInterfaces": true, diff --git a/scripts/generate-client.js b/scripts/generate-client.js index 37f5abf3..90481cfb 100644 --- a/scripts/generate-client.js +++ b/scripts/generate-client.js @@ -56,7 +56,7 @@ const getOpenApiCommand = (params) => { const { url, path, config, filter } = params; const configFile = config ? `-c ${config}` : ''; const filterString = filter ? `--openapi-normalizer FILTER="${filter}"` : ''; - const command = `openapi-generator-cli generate -i ${url} -g typescript-axios -o ${path} ${configFile} --skip-validate-spec ${filterString}`; + const command = `openapi-generator-cli generate -i ${url} -g typescript-fetch -o ${path} ${configFile} --skip-validate-spec ${filterString}`; return command; }; diff --git a/src/infra/authorization/authorization-api-client/.openapi-generator-ignore b/src/infra/authorization/authorization-api-client/.openapi-generator-ignore index bbc533d6..48fc051b 100644 --- a/src/infra/authorization/authorization-api-client/.openapi-generator-ignore +++ b/src/infra/authorization/authorization-api-client/.openapi-generator-ignore @@ -32,7 +32,9 @@ models/* # list of allowed files in the "models" folder !models/action.ts +!models/api-validation-error.ts !models/authorization-body-params.ts !models/authorization-context-params.ts !models/authorized-reponse.ts -!models/index.ts \ No newline at end of file +!models/index.ts +!models/permission.ts \ No newline at end of file diff --git a/src/infra/authorization/authorization-api-client/.openapi-generator/FILES b/src/infra/authorization/authorization-api-client/.openapi-generator/FILES index b0b81500..f99506fa 100644 --- a/src/infra/authorization/authorization-api-client/.openapi-generator/FILES +++ b/src/infra/authorization/authorization-api-client/.openapi-generator/FILES @@ -1,11 +1,295 @@ -api.ts -api/authorization-api.ts -base.ts -common.ts -configuration.ts +apis/authorization-api.ts +apis/index.ts index.ts +models/account-by-id-body-params.ts +models/account-response.ts +models/account-search-list-response.ts models/action.ts +models/alert-response.ts +models/api-validation-error.ts models/authorization-body-params.ts models/authorization-context-params.ts models/authorized-reponse.ts +models/basic-tool-config-params.ts +models/board-column-board-response.ts +models/board-context-response.ts +models/board-element-response-content.ts +models/board-element-response.ts +models/board-external-reference-type.ts +models/board-layout.ts +models/board-lesson-response.ts +models/board-parent-type.ts +models/board-response.ts +models/board-submission-controller-create-element201-response.ts +models/board-task-response.ts +models/board-task-status-response.ts +models/card-controller-create-element201-response.ts +models/card-list-response.ts +models/card-response-elements-inner.ts +models/card-response.ts +models/card-skeleton-response.ts +models/change-language-params.ts +models/class-info-response.ts +models/class-info-search-list-response.ts +models/class-request-context.ts +models/class-response.ts +models/class-sort-query-type.ts +models/collaborative-text-editor-element-response.ts +models/collaborative-text-editor-parent-type.ts +models/collaborative-text-editor-response.ts +models/collapsable-body-params.ts +models/color-body-params.ts +models/column-response.ts +models/config-response.ts +models/consent-request-body.ts +models/consent-response.ts +models/consent-session-response.ts +models/consents-response.ts +models/content-element-type.ts +models/context-external-tool-body-params.ts +models/context-external-tool-configuration-status-response.ts +models/context-external-tool-configuration-template-list-response.ts +models/context-external-tool-configuration-template-response.ts +models/context-external-tool-count-per-context-response.ts +models/context-external-tool-post-params.ts +models/context-external-tool-response.ts +models/context-external-tool-search-list-response.ts +models/copy-api-response.ts +models/county-response.ts +models/course-common-cartridge-metadata-response.ts +models/course-export-body-params.ts +models/course-info-data-response.ts +models/course-info-list-response.ts +models/course-info-response.ts +models/course-metadata-list-response.ts +models/course-metadata-response.ts +models/course-sort-props.ts +models/course-status.ts +models/course-sync-body-params.ts +models/create-board-body-params.ts +models/create-board-response.ts +models/create-card-body-params.ts +models/create-content-element-body-params.ts +models/create-media-element-body-params.ts +models/create-news-params.ts +models/create-room-body-params.ts +models/create-submission-item-body-params.ts +models/custom-parameter-entry-param.ts +models/custom-parameter-entry-response.ts +models/custom-parameter-post-params.ts +models/custom-parameter-response.ts +models/dashboard-grid-element-response.ts +models/dashboard-grid-sub-element-response.ts +models/dashboard-response.ts +models/deleted-element-content.ts +models/deleted-element-response.ts +models/drawing-content-body.ts +models/drawing-element-content-body.ts +models/drawing-element-content.ts +models/drawing-element-response.ts +models/element-controller-update-element201-response.ts +models/entity-not-found-error.ts +models/external-source-response.ts +models/external-tool-bulk-create-params.ts +models/external-tool-content-body.ts +models/external-tool-create-params.ts +models/external-tool-element-content-body.ts +models/external-tool-element-content.ts +models/external-tool-element-response.ts +models/external-tool-medium-params.ts +models/external-tool-medium-response.ts +models/external-tool-metadata-response.ts +models/external-tool-response-config.ts +models/external-tool-response.ts +models/external-tool-search-list-response.ts +models/external-tool-update-params-config.ts +models/external-tool-update-params.ts +models/federal-state-response.ts +models/file-content-body.ts +models/file-element-content-body.ts +models/file-element-content.ts +models/file-element-response.ts +models/file-storage-type.ts +models/forbidden-operation-error.ts +models/force-migration-params.ts +models/get-meta-tag-data-body.ts +models/group-list-response.ts +models/group-response.ts +models/group-user-response.ts +models/import-user-list-response.ts +models/import-user-response.ts models/index.ts +models/instance-feature.ts +models/language-type.ts +models/layout-body-params.ts +models/ldap-authorization-body-params.ts +models/lesson-content-response.ts +models/lesson-copy-api-params.ts +models/lesson-linked-task-response.ts +models/lesson-metadata-list-response.ts +models/lesson-metadata-response.ts +models/lesson-response.ts +models/link-content-body.ts +models/link-element-content-body.ts +models/link-element-content.ts +models/link-element-response.ts +models/local-authorization-body-params.ts +models/login-request-body.ts +models/login-response.ts +models/lti-message-type.ts +models/lti-privacy-permission.ts +models/lti11-tool-config-create-params.ts +models/lti11-tool-config-update-params.ts +models/material-response.ts +models/me-account-response.ts +models/me-response.ts +models/me-role-response.ts +models/me-school-logo-response.ts +models/me-school-response.ts +models/me-user-response.ts +models/media-available-line-element-response.ts +models/media-available-line-response.ts +models/media-board-colors.ts +models/media-board-layout-type.ts +models/media-board-response.ts +models/media-external-tool-element-content.ts +models/media-external-tool-element-response.ts +models/media-line-response-elements-inner.ts +models/media-line-response.ts +models/message-origin.ts +models/message.ts +models/meta-tag-extractor-response.ts +models/move-card-body-params.ts +models/move-column-body-params.ts +models/move-content-element-body.ts +models/move-element-body-params.ts +models/move-element-params.ts +models/move-element-position-params.ts +models/news-list-response.ts +models/news-response.ts +models/news-target-model.ts +models/o-auth-token-dto.ts +models/oauth-client-create-body.ts +models/oauth-client-response.ts +models/oauth-client-update-body.ts +models/oauth-config-response.ts +models/oauth-provider-login-response.ts +models/oauth2-authorization-body-params.ts +models/oauth2-migration-params.ts +models/oauth2-tool-config-create-params.ts +models/oauth2-tool-config-update-params.ts +models/oidc-context-response.ts +models/parent-consent-response.ts +models/patch-group-params.ts +models/patch-my-account-params.ts +models/patch-my-password-params.ts +models/patch-order-params.ts +models/patch-visibility-params.ts +models/period-response.ts +models/permission.ts +models/provider-config-response.ts +models/pseudonym-response.ts +models/public-system-list-response.ts +models/public-system-response.ts +models/redirect-response.ts +models/rename-body-params.ts +models/resolved-user-response.ts +models/rich-text-content-body.ts +models/rich-text-element-content-body.ts +models/rich-text-element-content.ts +models/rich-text-element-response.ts +models/rich-text.ts +models/role-name.ts +models/room-color.ts +models/room-details-response.ts +models/room-item-response.ts +models/room-list-response.ts +models/school-controller-get-provisioning-options200-response.ts +models/school-exists-response.ts +models/school-external-tool-configuration-status-response.ts +models/school-external-tool-configuration-template-list-response.ts +models/school-external-tool-configuration-template-response.ts +models/school-external-tool-metadata-response.ts +models/school-external-tool-post-params.ts +models/school-external-tool-response.ts +models/school-external-tool-search-list-response.ts +models/school-feature.ts +models/school-for-external-invite-response.ts +models/school-for-ldap-login-response.ts +models/school-info-response.ts +models/school-logo.ts +models/school-permissions-params.ts +models/school-purpose.ts +models/school-response.ts +models/school-system-response.ts +models/school-update-body-params.ts +models/school-year-query-type.ts +models/school-year-response.ts +models/schul-conne-x-provisioning-options-params.ts +models/schul-conne-x-provisioning-options-response.ts +models/schulcloud-theme.ts +models/set-height-body-params.ts +models/share-token-body-params.ts +models/share-token-import-body-params.ts +models/share-token-info-response.ts +models/share-token-payload-response.ts +models/share-token-response.ts +models/single-column-board-response.ts +models/student-permission-params.ts +models/submission-container-content-body.ts +models/submission-container-element-content-body.ts +models/submission-container-element-content.ts +models/submission-container-element-response.ts +models/submission-item-response-elements-inner.ts +models/submission-item-response.ts +models/submission-status-list-response.ts +models/submission-status-response.ts +models/submissions-response.ts +models/successful-response.ts +models/system-for-ldap-login-response.ts +models/system-type.ts +models/target-info-response.ts +models/target-user-id-params.ts +models/task-copy-api-params.ts +models/task-list-response.ts +models/task-response.ts +models/task-status-response.ts +models/teacher-permission-params.ts +models/team-permissions-body.ts +models/timestamps-response.ts +models/timezone.ts +models/tool-config-type.ts +models/tool-context-type.ts +models/tool-context-types-list-response.ts +models/tool-launch-request-response.ts +models/tool-reference-list-response.ts +models/tool-reference-response.ts +models/update-board-title-params.ts +models/update-element-content-body-params-data.ts +models/update-element-content-body-params.ts +models/update-flag-params.ts +models/update-match-params.ts +models/update-news-params.ts +models/update-room-body-params.ts +models/update-submission-item-body-params.ts +models/user-consent-response.ts +models/user-data-response.ts +models/user-info-response.ts +models/user-list-response.ts +models/user-login-migration-mandatory-params.ts +models/user-login-migration-response.ts +models/user-login-migration-search-list-response.ts +models/user-match-list-response.ts +models/user-match-response.ts +models/user-response.ts +models/validation-error.ts +models/video-conference-create-params.ts +models/video-conference-info-response.ts +models/video-conference-join-response.ts +models/video-conference-options-response.ts +models/video-conference-scope.ts +models/video-conference-state-response.ts +models/visibility-body-params.ts +models/visibility-settings-response.ts +models/years-response.ts +runtime.ts diff --git a/src/infra/authorization/authorization-api-client/api.ts b/src/infra/authorization/authorization-api-client/api.ts deleted file mode 100644 index fc2c3721..00000000 --- a/src/infra/authorization/authorization-api-client/api.ts +++ /dev/null @@ -1,18 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/** - * Schulcloud-Verbund-Software Server API - * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. - * - * The version of the OpenAPI document: 3.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - - -export * from './api/authorization-api'; - diff --git a/src/infra/authorization/authorization-api-client/api/authorization-api.ts b/src/infra/authorization/authorization-api-client/api/authorization-api.ts deleted file mode 100644 index cd72a7e6..00000000 --- a/src/infra/authorization/authorization-api-client/api/authorization-api.ts +++ /dev/null @@ -1,159 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/** - * Schulcloud-Verbund-Software Server API - * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. - * - * The version of the OpenAPI document: 3.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -import type { Configuration } from '../configuration'; -import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; -import globalAxios from 'axios'; -// Some imports not used depending on template conditions -// @ts-ignore -import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common'; -// @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, type RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../base'; -// @ts-ignore -import type { ApiValidationError } from '../models'; -// @ts-ignore -import type { AuthorizationBodyParams } from '../models'; -// @ts-ignore -import type { AuthorizedReponse } from '../models'; -/** - * AuthorizationApi - axios parameter creator - * @export - */ -export const AuthorizationApiAxiosParamCreator = function (configuration?: Configuration) { - return { - /** - * - * @summary Checks if user is authorized to perform the given operation. - * @param {AuthorizationBodyParams} authorizationBodyParams - * @param {*} [options] Override http request option. - * @throws {RequiredError} - */ - authorizationReferenceControllerAuthorizeByReference: async (authorizationBodyParams: AuthorizationBodyParams, options: RawAxiosRequestConfig = {}): Promise => { - // verify required parameter 'authorizationBodyParams' is not null or undefined - assertParamExists('authorizationReferenceControllerAuthorizeByReference', 'authorizationBodyParams', authorizationBodyParams) - const localVarPath = `/authorization/by-reference`; - // use dummy base URL string because the URL constructor only accepts absolute URLs. - const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); - let baseOptions; - if (configuration) { - baseOptions = configuration.baseOptions; - } - - const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; - const localVarHeaderParameter = {} as any; - const localVarQueryParameter = {} as any; - - // authentication bearer required - // http bearer authentication required - await setBearerAuthToObject(localVarHeaderParameter, configuration) - - - - localVarHeaderParameter['Content-Type'] = 'application/json'; - - setSearchParams(localVarUrlObj, localVarQueryParameter); - let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; - localVarRequestOptions.data = serializeDataIfNeeded(authorizationBodyParams, localVarRequestOptions, configuration) - - return { - url: toPathString(localVarUrlObj), - options: localVarRequestOptions, - }; - }, - } -}; - -/** - * AuthorizationApi - functional programming interface - * @export - */ -export const AuthorizationApiFp = function(configuration?: Configuration) { - const localVarAxiosParamCreator = AuthorizationApiAxiosParamCreator(configuration) - return { - /** - * - * @summary Checks if user is authorized to perform the given operation. - * @param {AuthorizationBodyParams} authorizationBodyParams - * @param {*} [options] Override http request option. - * @throws {RequiredError} - */ - async authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { - const localVarAxiosArgs = await localVarAxiosParamCreator.authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams, options); - const localVarOperationServerIndex = configuration?.serverIndex ?? 0; - const localVarOperationServerBasePath = operationServerMap['AuthorizationApi.authorizationReferenceControllerAuthorizeByReference']?.[localVarOperationServerIndex]?.url; - return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); - }, - } -}; - -/** - * AuthorizationApi - factory interface - * @export - */ -export const AuthorizationApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { - const localVarFp = AuthorizationApiFp(configuration) - return { - /** - * - * @summary Checks if user is authorized to perform the given operation. - * @param {AuthorizationBodyParams} authorizationBodyParams - * @param {*} [options] Override http request option. - * @throws {RequiredError} - */ - authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: RawAxiosRequestConfig): AxiosPromise { - return localVarFp.authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams, options).then((request) => request(axios, basePath)); - }, - }; -}; - -/** - * AuthorizationApi - interface - * @export - * @interface AuthorizationApi - */ -export interface AuthorizationApiInterface { - /** - * - * @summary Checks if user is authorized to perform the given operation. - * @param {AuthorizationBodyParams} authorizationBodyParams - * @param {*} [options] Override http request option. - * @throws {RequiredError} - * @memberof AuthorizationApiInterface - */ - authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: RawAxiosRequestConfig): AxiosPromise; - -} - -/** - * AuthorizationApi - object-oriented interface - * @export - * @class AuthorizationApi - * @extends {BaseAPI} - */ -export class AuthorizationApi extends BaseAPI implements AuthorizationApiInterface { - /** - * - * @summary Checks if user is authorized to perform the given operation. - * @param {AuthorizationBodyParams} authorizationBodyParams - * @param {*} [options] Override http request option. - * @throws {RequiredError} - * @memberof AuthorizationApi - */ - public authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams: AuthorizationBodyParams, options?: RawAxiosRequestConfig) { - return AuthorizationApiFp(this.configuration).authorizationReferenceControllerAuthorizeByReference(authorizationBodyParams, options).then((request) => request(this.axios, this.basePath)); - } -} - diff --git a/src/infra/authorization/authorization-api-client/apis/authorization-api.ts b/src/infra/authorization/authorization-api-client/apis/authorization-api.ts new file mode 100644 index 00000000..924ef9af --- /dev/null +++ b/src/infra/authorization/authorization-api-client/apis/authorization-api.ts @@ -0,0 +1,108 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime.js'; +import type { + ApiValidationError, + AuthorizationBodyParams, + AuthorizedReponse, +} from '../models/index.js'; +import { + ApiValidationErrorFromJSON, + ApiValidationErrorToJSON, + AuthorizationBodyParamsFromJSON, + AuthorizationBodyParamsToJSON, + AuthorizedReponseFromJSON, + AuthorizedReponseToJSON, +} from '../models/index.js'; + +export interface AuthorizationReferenceControllerAuthorizeByReferenceRequest { + authorizationBodyParams: AuthorizationBodyParams; +} + +/** + * AuthorizationApi - interface + * + * @export + * @interface AuthorizationApiInterface + */ +export interface AuthorizationApiInterface { + /** + * + * @summary Checks if user is authorized to perform the given operation. + * @param {AuthorizationBodyParams} authorizationBodyParams + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof AuthorizationApiInterface + */ + authorizationReferenceControllerAuthorizeByReferenceRaw(requestParameters: AuthorizationReferenceControllerAuthorizeByReferenceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * Checks if user is authorized to perform the given operation. + */ + authorizationReferenceControllerAuthorizeByReference(requestParameters: AuthorizationReferenceControllerAuthorizeByReferenceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise; + +} + +/** + * + */ +export class AuthorizationApi extends runtime.BaseAPI implements AuthorizationApiInterface { + + /** + * Checks if user is authorized to perform the given operation. + */ + async authorizationReferenceControllerAuthorizeByReferenceRaw(requestParameters: AuthorizationReferenceControllerAuthorizeByReferenceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + if (requestParameters['authorizationBodyParams'] == null) { + throw new runtime.RequiredError( + 'authorizationBodyParams', + 'Required parameter "authorizationBodyParams" was null or undefined when calling authorizationReferenceControllerAuthorizeByReference().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("bearer", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/authorization/by-reference`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: AuthorizationBodyParamsToJSON(requestParameters['authorizationBodyParams']), + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => AuthorizedReponseFromJSON(jsonValue)); + } + + /** + * Checks if user is authorized to perform the given operation. + */ + async authorizationReferenceControllerAuthorizeByReference(requestParameters: AuthorizationReferenceControllerAuthorizeByReferenceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.authorizationReferenceControllerAuthorizeByReferenceRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/src/infra/authorization/authorization-api-client/apis/index.ts b/src/infra/authorization/authorization-api-client/apis/index.ts new file mode 100644 index 00000000..a1681b8a --- /dev/null +++ b/src/infra/authorization/authorization-api-client/apis/index.ts @@ -0,0 +1,3 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './authorization-api.js'; diff --git a/src/infra/authorization/authorization-api-client/base.ts b/src/infra/authorization/authorization-api-client/base.ts deleted file mode 100644 index 5bcf014a..00000000 --- a/src/infra/authorization/authorization-api-client/base.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/** - * Schulcloud-Verbund-Software Server API - * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. - * - * The version of the OpenAPI document: 3.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -import type { Configuration } from './configuration'; -// Some imports not used depending on template conditions -// @ts-ignore -import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; -import globalAxios from 'axios'; - -export const BASE_PATH = "http://localhost:3030/api/v3".replace(/\/+$/, ""); - -/** - * - * @export - */ -export const COLLECTION_FORMATS = { - csv: ",", - ssv: " ", - tsv: "\t", - pipes: "|", -}; - -/** - * - * @export - * @interface RequestArgs - */ -export interface RequestArgs { - url: string; - options: RawAxiosRequestConfig; -} - -/** - * - * @export - * @class BaseAPI - */ -export class BaseAPI { - protected configuration: Configuration | undefined; - - constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { - if (configuration) { - this.configuration = configuration; - this.basePath = configuration.basePath ?? basePath; - } - } -}; - -/** - * - * @export - * @class RequiredError - * @extends {Error} - */ -export class RequiredError extends Error { - constructor(public field: string, msg?: string) { - super(msg); - this.name = "RequiredError" - } -} - -interface ServerMap { - [key: string]: { - url: string, - description: string, - }[]; -} - -/** - * - * @export - */ -export const operationServerMap: ServerMap = { -} diff --git a/src/infra/authorization/authorization-api-client/common.ts b/src/infra/authorization/authorization-api-client/common.ts deleted file mode 100644 index 6c119efb..00000000 --- a/src/infra/authorization/authorization-api-client/common.ts +++ /dev/null @@ -1,150 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/** - * Schulcloud-Verbund-Software Server API - * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. - * - * The version of the OpenAPI document: 3.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -import type { Configuration } from "./configuration"; -import type { RequestArgs } from "./base"; -import type { AxiosInstance, AxiosResponse } from 'axios'; -import { RequiredError } from "./base"; - -/** - * - * @export - */ -export const DUMMY_BASE_URL = 'https://example.com' - -/** - * - * @throws {RequiredError} - * @export - */ -export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) { - if (paramValue === null || paramValue === undefined) { - throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`); - } -} - -/** - * - * @export - */ -export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) { - if (configuration && configuration.apiKey) { - const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? await configuration.apiKey(keyParamName) - : await configuration.apiKey; - object[keyParamName] = localVarApiKeyValue; - } -} - -/** - * - * @export - */ -export const setBasicAuthToObject = function (object: any, configuration?: Configuration) { - if (configuration && (configuration.username || configuration.password)) { - object["auth"] = { username: configuration.username, password: configuration.password }; - } -} - -/** - * - * @export - */ -export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) { - if (configuration && configuration.accessToken) { - const accessToken = typeof configuration.accessToken === 'function' - ? await configuration.accessToken() - : await configuration.accessToken; - object["Authorization"] = "Bearer " + accessToken; - } -} - -/** - * - * @export - */ -export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) { - if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? await configuration.accessToken(name, scopes) - : await configuration.accessToken; - object["Authorization"] = "Bearer " + localVarAccessTokenValue; - } -} - -function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { - if (parameter == null) return; - if (typeof parameter === "object") { - if (Array.isArray(parameter)) { - (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); - } - else { - Object.keys(parameter).forEach(currentKey => - setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) - ); - } - } - else { - if (urlSearchParams.has(key)) { - urlSearchParams.append(key, parameter); - } - else { - urlSearchParams.set(key, parameter); - } - } -} - -/** - * - * @export - */ -export const setSearchParams = function (url: URL, ...objects: any[]) { - const searchParams = new URLSearchParams(url.search); - setFlattenedQueryParams(searchParams, objects); - url.search = searchParams.toString(); -} - -/** - * - * @export - */ -export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) { - const nonString = typeof value !== 'string'; - const needsSerialization = nonString && configuration && configuration.isJsonMime - ? configuration.isJsonMime(requestOptions.headers['Content-Type']) - : nonString; - return needsSerialization - ? JSON.stringify(value !== undefined ? value : {}) - : (value || ""); -} - -/** - * - * @export - */ -export const toPathString = function (url: URL) { - return url.pathname + url.search + url.hash -} - -/** - * - * @export - */ -export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { - return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; - return axios.request(axiosRequestArgs); - }; -} diff --git a/src/infra/authorization/authorization-api-client/configuration.ts b/src/infra/authorization/authorization-api-client/configuration.ts deleted file mode 100644 index 8c97d307..00000000 --- a/src/infra/authorization/authorization-api-client/configuration.ts +++ /dev/null @@ -1,110 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/** - * Schulcloud-Verbund-Software Server API - * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. - * - * The version of the OpenAPI document: 3.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -export interface ConfigurationParameters { - apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); - username?: string; - password?: string; - accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); - basePath?: string; - serverIndex?: number; - baseOptions?: any; - formDataCtor?: new () => any; -} - -export class Configuration { - /** - * parameter for apiKey security - * @param name security name - * @memberof Configuration - */ - apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); - /** - * parameter for basic security - * - * @type {string} - * @memberof Configuration - */ - username?: string; - /** - * parameter for basic security - * - * @type {string} - * @memberof Configuration - */ - password?: string; - /** - * parameter for oauth2 security - * @param name security name - * @param scopes oauth2 scope - * @memberof Configuration - */ - accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); - /** - * override base path - * - * @type {string} - * @memberof Configuration - */ - basePath?: string; - /** - * override server index - * - * @type {number} - * @memberof Configuration - */ - serverIndex?: number; - /** - * base options for axios calls - * - * @type {any} - * @memberof Configuration - */ - baseOptions?: any; - /** - * The FormData constructor that will be used to create multipart form data - * requests. You can inject this here so that execution environments that - * do not support the FormData class can still run the generated client. - * - * @type {new () => FormData} - */ - formDataCtor?: new () => any; - - constructor(param: ConfigurationParameters = {}) { - this.apiKey = param.apiKey; - this.username = param.username; - this.password = param.password; - this.accessToken = param.accessToken; - this.basePath = param.basePath; - this.serverIndex = param.serverIndex; - this.baseOptions = param.baseOptions; - this.formDataCtor = param.formDataCtor; - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * @param mime - MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public isJsonMime(mime: string): boolean { - const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); - return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); - } -} diff --git a/src/infra/authorization/authorization-api-client/index.ts b/src/infra/authorization/authorization-api-client/index.ts index 8b762df6..89656b95 100644 --- a/src/infra/authorization/authorization-api-client/index.ts +++ b/src/infra/authorization/authorization-api-client/index.ts @@ -1,18 +1,5 @@ /* tslint:disable */ /* eslint-disable */ -/** - * Schulcloud-Verbund-Software Server API - * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. - * - * The version of the OpenAPI document: 3.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -export * from "./api"; -export * from "./configuration"; -export * from "./models"; +export * from './runtime.js'; +export * from './apis/index.js'; +export * from './models/index.js'; diff --git a/src/infra/authorization/authorization-api-client/models/action.ts b/src/infra/authorization/authorization-api-client/models/action.ts index c74334d3..545af1fb 100644 --- a/src/infra/authorization/authorization-api-client/models/action.ts +++ b/src/infra/authorization/authorization-api-client/models/action.ts @@ -13,19 +13,41 @@ */ - /** * * @export - * @enum {string} */ - export const Action = { READ: 'read', WRITE: 'write' } as const; - export type Action = typeof Action[keyof typeof Action]; +export function instanceOfAction(value: any): boolean { + for (const key in Action) { + if (Object.prototype.hasOwnProperty.call(Action, key)) { + if (Action[key as keyof typeof Action] === value) { + return true; + } + } + } + return false; +} + +export function ActionFromJSON(json: any): Action { + return ActionFromJSONTyped(json, false); +} + +export function ActionFromJSONTyped(json: any, ignoreDiscriminator: boolean): Action { + return json as Action; +} + +export function ActionToJSON(value?: Action | null): any { + return value as any; +} + +export function ActionToJSONTyped(value: any, ignoreDiscriminator: boolean): Action { + return value as Action; +} diff --git a/src/infra/authorization/authorization-api-client/models/api-validation-error.ts b/src/infra/authorization/authorization-api-client/models/api-validation-error.ts new file mode 100644 index 00000000..73b8e797 --- /dev/null +++ b/src/infra/authorization/authorization-api-client/models/api-validation-error.ts @@ -0,0 +1,101 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime.js'; +/** + * + * @export + * @interface ApiValidationError + */ +export interface ApiValidationError { + /** + * The response status code. + * @type {number} + * @memberof ApiValidationError + */ + code: number; + /** + * The error type. + * @type {string} + * @memberof ApiValidationError + */ + type: string; + /** + * The error title. + * @type {string} + * @memberof ApiValidationError + */ + title: string; + /** + * The error message. + * @type {string} + * @memberof ApiValidationError + */ + message: string; + /** + * The error details. + * @type {object} + * @memberof ApiValidationError + */ + details?: object; +} + +/** + * Check if a given object implements the ApiValidationError interface. + */ +export function instanceOfApiValidationError(value: object): value is ApiValidationError { + if (!('code' in value) || value['code'] === undefined) return false; + if (!('type' in value) || value['type'] === undefined) return false; + if (!('title' in value) || value['title'] === undefined) return false; + if (!('message' in value) || value['message'] === undefined) return false; + return true; +} + +export function ApiValidationErrorFromJSON(json: any): ApiValidationError { + return ApiValidationErrorFromJSONTyped(json, false); +} + +export function ApiValidationErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): ApiValidationError { + if (json == null) { + return json; + } + return { + + 'code': json['code'], + 'type': json['type'], + 'title': json['title'], + 'message': json['message'], + 'details': json['details'] == null ? undefined : json['details'], + }; +} + + export function ApiValidationErrorToJSON(json: any): ApiValidationError { + return ApiValidationErrorToJSONTyped(json, false); + } + + export function ApiValidationErrorToJSONTyped(value?: ApiValidationError | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'code': value['code'], + 'type': value['type'], + 'title': value['title'], + 'message': value['message'], + 'details': value['details'], + }; +} + diff --git a/src/infra/authorization/authorization-api-client/models/authorization-body-params.ts b/src/infra/authorization/authorization-api-client/models/authorization-body-params.ts index cea578bd..5a3ca960 100644 --- a/src/infra/authorization/authorization-api-client/models/authorization-body-params.ts +++ b/src/infra/authorization/authorization-api-client/models/authorization-body-params.ts @@ -12,10 +12,14 @@ * Do not edit the class manually. */ - -// May contain unused imports in some cases -// @ts-ignore -import type { AuthorizationContextParams } from './authorization-context-params'; +import { mapValues } from '../runtime.js'; +import type { AuthorizationContextParams } from './authorization-context-params.js'; +import { + AuthorizationContextParamsFromJSON, + AuthorizationContextParamsFromJSONTyped, + AuthorizationContextParamsToJSON, + AuthorizationContextParamsToJSONTyped, +} from './authorization-context-params.js'; /** * @@ -28,21 +32,25 @@ export interface AuthorizationBodyParams { * @type {AuthorizationContextParams} * @memberof AuthorizationBodyParams */ - 'context': AuthorizationContextParams; + context: AuthorizationContextParams; /** * The entity or domain object the operation should be performed on. * @type {string} * @memberof AuthorizationBodyParams */ - 'referenceType': AuthorizationBodyParamsReferenceType; + referenceType: AuthorizationBodyParamsReferenceType; /** * The id of the entity/domain object of the defined referenceType. * @type {string} * @memberof AuthorizationBodyParams */ - 'referenceId': string; + referenceId: string; } + +/** + * @export + */ export const AuthorizationBodyParamsReferenceType = { USERS: 'users', SCHOOLS: 'schools', @@ -58,7 +66,49 @@ export const AuthorizationBodyParamsReferenceType = { EXTERNAL_TOOLS: 'external-tools', INSTANCES: 'instances' } as const; - export type AuthorizationBodyParamsReferenceType = typeof AuthorizationBodyParamsReferenceType[keyof typeof AuthorizationBodyParamsReferenceType]; +/** + * Check if a given object implements the AuthorizationBodyParams interface. + */ +export function instanceOfAuthorizationBodyParams(value: object): value is AuthorizationBodyParams { + if (!('context' in value) || value['context'] === undefined) return false; + if (!('referenceType' in value) || value['referenceType'] === undefined) return false; + if (!('referenceId' in value) || value['referenceId'] === undefined) return false; + return true; +} + +export function AuthorizationBodyParamsFromJSON(json: any): AuthorizationBodyParams { + return AuthorizationBodyParamsFromJSONTyped(json, false); +} + +export function AuthorizationBodyParamsFromJSONTyped(json: any, ignoreDiscriminator: boolean): AuthorizationBodyParams { + if (json == null) { + return json; + } + return { + + 'context': AuthorizationContextParamsFromJSON(json['context']), + 'referenceType': json['referenceType'], + 'referenceId': json['referenceId'], + }; +} + + export function AuthorizationBodyParamsToJSON(json: any): AuthorizationBodyParams { + return AuthorizationBodyParamsToJSONTyped(json, false); + } + + export function AuthorizationBodyParamsToJSONTyped(value?: AuthorizationBodyParams | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'context': AuthorizationContextParamsToJSON(value['context']), + 'referenceType': value['referenceType'], + 'referenceId': value['referenceId'], + }; +} + diff --git a/src/infra/authorization/authorization-api-client/models/authorization-context-params.ts b/src/infra/authorization/authorization-api-client/models/authorization-context-params.ts index 055adfae..4233ced7 100644 --- a/src/infra/authorization/authorization-api-client/models/authorization-context-params.ts +++ b/src/infra/authorization/authorization-api-client/models/authorization-context-params.ts @@ -5,40 +5,78 @@ * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. * * The version of the OpenAPI document: 3.0 - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - -// May contain unused imports in some cases -// @ts-ignore -import type { Action } from './action'; -// May contain unused imports in some cases -// @ts-ignore -import type { Permission } from './permission'; +import type { Action } from './action.js'; +import { ActionFromJSON, ActionToJSON } from './action.js'; +import type { Permission } from './permission.js'; +import { PermissionFromJSON, PermissionToJSON } from './permission.js'; /** - * + * * @export * @interface AuthorizationContextParams */ export interface AuthorizationContextParams { - /** - * - * @type {Action} - * @memberof AuthorizationContextParams - */ - 'action': Action; - /** - * User permissions that are needed to execute the operation. - * @type {Array} - * @memberof AuthorizationContextParams - */ - 'requiredPermissions': Array; + /** + * + * @type {Action} + * @memberof AuthorizationContextParams + */ + action: Action; + /** + * User permissions that are needed to execute the operation. + * @type {Array} + * @memberof AuthorizationContextParams + */ + requiredPermissions: Array; } +/** + * Check if a given object implements the AuthorizationContextParams interface. + */ +export function instanceOfAuthorizationContextParams(value: object): value is AuthorizationContextParams { + if (!('action' in value) || value['action'] === undefined) return false; + if (!('requiredPermissions' in value) || value['requiredPermissions'] === undefined) return false; + return true; +} +export function AuthorizationContextParamsFromJSON(json: any): AuthorizationContextParams { + return AuthorizationContextParamsFromJSONTyped(json, false); +} +export function AuthorizationContextParamsFromJSONTyped( + json: any, + ignoreDiscriminator: boolean, +): AuthorizationContextParams { + if (json == null) { + return json; + } + return { + action: ActionFromJSON(json['action']), + requiredPermissions: (json['requiredPermissions'] as Array).map(PermissionFromJSON), + }; +} + +export function AuthorizationContextParamsToJSON(json: any): AuthorizationContextParams { + return AuthorizationContextParamsToJSONTyped(json, false); +} + +export function AuthorizationContextParamsToJSONTyped( + value?: AuthorizationContextParams | null, + ignoreDiscriminator: boolean = false, +): any { + if (value == null) { + return value; + } + + return { + action: ActionToJSON(value['action']), + requiredPermissions: (value['requiredPermissions'] as Array).map(PermissionToJSON), + }; +} diff --git a/src/infra/authorization/authorization-api-client/models/authorized-reponse.ts b/src/infra/authorization/authorization-api-client/models/authorized-reponse.ts index b69c757a..b0efb4a0 100644 --- a/src/infra/authorization/authorization-api-client/models/authorized-reponse.ts +++ b/src/infra/authorization/authorization-api-client/models/authorized-reponse.ts @@ -12,8 +12,7 @@ * Do not edit the class manually. */ - - +import { mapValues } from '../runtime.js'; /** * * @export @@ -25,12 +24,52 @@ export interface AuthorizedReponse { * @type {string} * @memberof AuthorizedReponse */ - 'userId': string; + userId: string; /** * * @type {boolean} * @memberof AuthorizedReponse */ - 'isAuthorized': boolean; + isAuthorized: boolean; +} + +/** + * Check if a given object implements the AuthorizedReponse interface. + */ +export function instanceOfAuthorizedReponse(value: object): value is AuthorizedReponse { + if (!('userId' in value) || value['userId'] === undefined) return false; + if (!('isAuthorized' in value) || value['isAuthorized'] === undefined) return false; + return true; +} + +export function AuthorizedReponseFromJSON(json: any): AuthorizedReponse { + return AuthorizedReponseFromJSONTyped(json, false); +} + +export function AuthorizedReponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): AuthorizedReponse { + if (json == null) { + return json; + } + return { + + 'userId': json['userId'], + 'isAuthorized': json['isAuthorized'], + }; +} + + export function AuthorizedReponseToJSON(json: any): AuthorizedReponse { + return AuthorizedReponseToJSONTyped(json, false); + } + + export function AuthorizedReponseToJSONTyped(value?: AuthorizedReponse | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'userId': value['userId'], + 'isAuthorized': value['isAuthorized'], + }; } diff --git a/src/infra/authorization/authorization-api-client/models/index.ts b/src/infra/authorization/authorization-api-client/models/index.ts index 6e494cd9..f1293724 100644 --- a/src/infra/authorization/authorization-api-client/models/index.ts +++ b/src/infra/authorization/authorization-api-client/models/index.ts @@ -1,4 +1,8 @@ +/* tslint:disable */ +/* eslint-disable */ export * from './action.js'; +export * from './api-validation-error.js'; export * from './authorization-body-params.js'; export * from './authorization-context-params.js'; export * from './authorized-reponse.js'; +export * from './permission.js'; diff --git a/src/infra/authorization/authorization-api-client/models/permission.ts b/src/infra/authorization/authorization-api-client/models/permission.ts new file mode 100644 index 00000000..51d32db8 --- /dev/null +++ b/src/infra/authorization/authorization-api-client/models/permission.ts @@ -0,0 +1,46 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime.js'; +/** + * + * @export + * @interface Permission + */ +export interface Permission extends Array { +} + +/** + * Check if a given object implements the Permission interface. + */ +export function instanceOfPermission(value: object): value is Permission { + return true; +} + +export function PermissionFromJSON(json: any): Permission { + return PermissionFromJSONTyped(json, false); +} + +export function PermissionFromJSONTyped(json: any, ignoreDiscriminator: boolean): Permission { + return json; +} + + export function PermissionToJSON(json: any): Permission { + return PermissionToJSONTyped(json, false); + } + + export function PermissionToJSONTyped(value?: Permission | null, ignoreDiscriminator: boolean = false): any { + return value; +} + diff --git a/src/infra/authorization/authorization-api-client/runtime.ts b/src/infra/authorization/authorization-api-client/runtime.ts new file mode 100644 index 00000000..1a4a0a90 --- /dev/null +++ b/src/infra/authorization/authorization-api-client/runtime.ts @@ -0,0 +1,426 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Schulcloud-Verbund-Software Server API + * This is v3 of Schulcloud-Verbund-Software Server. Checkout /docs for v1. + * + * The version of the OpenAPI document: 3.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const BASE_PATH = "http://localhost:3030/api/v3".replace(/\/+$/, ""); + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | Promise | ((name: string) => string | Promise); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + set config(configuration: Configuration) { + this.configuration = configuration; + } + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string | Promise) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export const DefaultConfig = new Configuration(); + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private middleware: Middleware[]; + + constructor(protected configuration = DefaultConfig) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + protected isJsonMime(mime: string | null | undefined): boolean { + if (!mime) { + return false; + } + return BaseAPI.jsonRegex.test(mime); + } + + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); + const response = await this.fetchApi(url, init); + if (response && (response.status >= 200 && response.status < 300)) { + return response; + } + throw new ResponseError(response, 'Response returned an error code'); + } + + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + + const headers = Object.assign({}, this.configuration.headers, context.headers); + Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {}); + + const initOverrideFn = + typeof initOverrides === "function" + ? initOverrides + : async () => initOverrides; + + const initParams = { + method: context.method, + headers, + body: context.body, + credentials: this.configuration.credentials, + }; + + const overriddenInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + }; + + let body: any; + if (isFormData(overriddenInit.body) + || (overriddenInit.body instanceof URLSearchParams) + || isBlob(overriddenInit.body)) { + body = overriddenInit.body; + } else if (this.isJsonMime(headers['Content-Type'])) { + body = JSON.stringify(overriddenInit.body); + } else { + body = overriddenInit.body; + } + + const init: RequestInit = { + ...overriddenInit, + body + }; + + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response: Response | undefined = undefined; + try { + response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); + } catch (e) { + for (const middleware of this.middleware) { + if (middleware.onError) { + response = await middleware.onError({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + error: e, + response: response ? response.clone() : undefined, + }) || response; + } + } + if (response === undefined) { + if (e instanceof Error) { + throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } + } + } + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +function isBlob(value: any): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob; +} + +function isFormData(value: any): value is FormData { + return typeof FormData !== "undefined" && value instanceof FormData; +} + +export class ResponseError extends Error { + override name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + } +} + +export class FetchError extends Error { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { + super(msg); + } +} + +export class RequiredError extends Error { + override name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map(key => querystringSingleKey(key, params[key], prefix)) + .filter(part => part.length > 0) + .join('&'); +} + +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key); + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Set) { + const valueAsArray = Array.from(value); + return querystringSingleKey(key, valueAsArray, keyPrefix); + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string; +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface ErrorContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + error: unknown; + response?: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; + onError?(context: ErrorContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/src/infra/authorization/authorization.module.ts b/src/infra/authorization/authorization.module.ts index b30dcdd1..b3f88a8f 100644 --- a/src/infra/authorization/authorization.module.ts +++ b/src/infra/authorization/authorization.module.ts @@ -1,10 +1,11 @@ import { Module } from '@nestjs/common'; import { LoggerModule } from '../logging/logger.module.js'; +import { AuthorizationApi } from './authorization-api-client/index.js'; import { AuthorizationService } from './authorization.service.js'; @Module({ imports: [LoggerModule], - providers: [AuthorizationService], + providers: [AuthorizationApi, AuthorizationService], exports: [AuthorizationService], }) export class AuthorizationModule {} diff --git a/src/infra/authorization/authorization.service.spec.ts b/src/infra/authorization/authorization.service.spec.ts index de7c093f..58f76fab 100644 --- a/src/infra/authorization/authorization.service.spec.ts +++ b/src/infra/authorization/authorization.service.spec.ts @@ -1,10 +1,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; -import { AxiosResponse } from 'axios'; import { HttpRequest } from 'uws'; import { Logger } from '../logging/logger.js'; -import { AuthorizationApi } from './authorization-api-client/api/authorization-api.js'; -import { AuthorizedReponse } from './authorization-api-client/models/authorized-reponse.js'; +import { AuthorizationApi, AuthorizedReponse } from './authorization-api-client/index.js'; import { AuthorizationService } from './authorization.service.js'; describe(AuthorizationService.name, () => { @@ -52,11 +50,9 @@ describe(AuthorizationService.name, () => { const setup = () => { const { req } = setupRequest(); - const response = createMock>({ - data: { - isAuthorized: true, - userId: '123', - }, + const response = createMock({ + isAuthorized: true, + userId: '123', }); authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockResolvedValueOnce(response); @@ -78,11 +74,9 @@ describe(AuthorizationService.name, () => { const setup = () => { const { req } = setupRequest(); - const response = createMock>({ - data: { - isAuthorized: false, - userId: '123', - }, + const response = createMock({ + isAuthorized: false, + userId: '123', }); authorizationApi.authorizationReferenceControllerAuthorizeByReference.mockResolvedValueOnce(response); diff --git a/src/infra/authorization/authorization.service.ts b/src/infra/authorization/authorization.service.ts index 09c2f11f..5fc4e629 100644 --- a/src/infra/authorization/authorization.service.ts +++ b/src/infra/authorization/authorization.service.ts @@ -1,13 +1,12 @@ import { Injectable } from '@nestjs/common'; -import { RawAxiosRequestConfig } from 'axios'; import { HttpRequest } from 'uws'; import { Logger } from '../logging/logger.js'; -import { AuthorizationApi } from './authorization-api-client/api/authorization-api.js'; -import { Action } from './authorization-api-client/models/action.js'; import { - AuthorizationBodyParams, + Action, + AuthorizationApi, AuthorizationBodyParamsReferenceType, -} from './authorization-api-client/models/authorization-body-params.js'; + AuthorizationReferenceControllerAuthorizeByReferenceRequest, +} from './authorization-api-client/index.js'; import { ResponsePayload } from './interfaces/response.payload.js'; import { ResponsePayloadBuilder } from './response.builder.js'; @@ -55,20 +54,23 @@ export class AuthorizationService { } private async fetchAuthorization(room: string, token: string): Promise { - const params: AuthorizationBodyParams = { - referenceType: AuthorizationBodyParamsReferenceType.BOARDNODES, - referenceId: room, - context: { - action: Action.READ, - requiredPermissions: ['COURSE_VIEW'], + const requestParameters: AuthorizationReferenceControllerAuthorizeByReferenceRequest = { + authorizationBodyParams: { + referenceType: AuthorizationBodyParamsReferenceType.BOARDNODES, + referenceId: room, + context: { + action: Action.READ, + requiredPermissions: [['COURSE_VIEW']], + }, }, }; - const options: RawAxiosRequestConfig = { headers: { authorization: `Bearer ${token}` } }; + // this.authorizationApi.configuration.accessToken = token; - const response = await this.authorizationApi.authorizationReferenceControllerAuthorizeByReference(params, options); + const response = + await this.authorizationApi.authorizationReferenceControllerAuthorizeByReference(requestParameters); - const { isAuthorized, userId } = response.data; + const { isAuthorized, userId } = response; if (!isAuthorized) { return this.createErrorResponsePayload(4401, 'Unauthorized'); }