diff --git a/jest.config.js b/jest.config.js index e3ef75a7..4a5b465e 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,185 +1,4 @@ -// For a detailed explanation regarding each configuration property, visit: -// https://jestjs.io/docs/en/configuration.html - module.exports = { - // All imported modules in your tests should be mocked automatically - // automock: false, - - // Stop running tests after `n` failures - // bail: 0, - - // The directory where Jest should store its cached dependency information - // cacheDirectory: "/private/var/folders/5r/ln_bl59d4h37b4j27kr915ww0000gn/T/jest_dx", - - // Automatically clear mock calls and instances between every test - // clearMocks: false, - - // Indicates whether the coverage information should be collected while executing the test - // collectCoverage: false, - - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: undefined, - - // The directory where Jest should output its coverage files - coverageDirectory: 'coverage', - - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "/node_modules/" - // ], - - // Indicates which provider should be used to instrument code for coverage - // coverageProvider: "babel", - - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], - - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: undefined, - - // A path to a custom dependency extractor - // dependencyExtractor: undefined, - - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, - - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], - - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: undefined, - - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: undefined, - - // A set of global variables that need to be available in all test environments - // globals: {}, - - // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. - // maxWorkers: "50%", - - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], - - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "json", - // "jsx", - // "ts", - // "tsx", - // "node" - // ], - - // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], - - // Activates notifications for test results - // notify: false, - - // An enum that specifies notification mode. Requires { notify: true } - // notifyMode: "failure-change", - - // A preset that is used as a base for Jest's configuration - // preset: undefined, - - // Run tests from one or more projects - // projects: undefined, - - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, - - // Automatically reset mock state between every test - // resetMocks: false, - - // Reset the module registry before running each individual test - // resetModules: false, - - // A path to a custom resolver - // resolver: undefined, - - // Automatically restore mock state between every test - // restoreMocks: false, - - // The root directory that Jest should scan for tests and modules within - // rootDir: undefined, - - // A list of paths to directories that Jest should use to search for files in - roots: ['/src'], - - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", - - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], - - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], - - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], - - // The test environment that will be used for testing + preset: 'ts-jest', testEnvironment: 'node', - - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, - - // Adds a location field to test results - // testLocationInResults: false, - - // The glob patterns Jest uses to detect test files - testMatch: ['**/__tests__/**/*.+(ts|tsx)', '**/?(*.)+(spec|test).+(ts|tsx)'], - - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - // testPathIgnorePatterns: [ - // "/node_modules/" - // ], - - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], - - // This option allows the use of a custom results processor - // testResultsProcessor: undefined, - - // This option allows use of a custom test runner - // testRunner: "jasmine2", - - // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href - // testURL: "http://localhost", - - // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" - // timers: "real", - - // A map from regular expressions to paths to transformers - transform: { - '^.+\\.(ts|tsx)$': 'ts-jest', - }, - - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "/node_modules/" - // ], - - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, - - // Indicates whether each individual test should be reported during the run - // verbose: undefined, - - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], - - // Whether to use watchman for file crawling - // watchman: true, }; diff --git a/package-lock.json b/package-lock.json index 2eccf406..60fdedb8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2260,9 +2260,9 @@ } }, "@types/jest": { - "version": "26.0.9", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-26.0.9.tgz", - "integrity": "sha512-k4qFfJ5AUKrWok5KYXp2EPm89b0P/KZpl7Vg4XuOTVVQEhLDBDBU3iBFrjjdgd8fLw96aAtmnwhXHl63bWeBQQ==", + "version": "26.0.10", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-26.0.10.tgz", + "integrity": "sha512-i2m0oyh8w/Lum7wWK/YOZJakYF8Mx08UaKA1CtbmFeDquVhAEdA7znacsVSf2hJ1OQ/OfVMGN90pw/AtzF8s/Q==", "dev": true, "requires": { "jest-diff": "^25.2.1", @@ -11741,11 +11741,12 @@ "integrity": "sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==" }, "ts-jest": { - "version": "26.1.4", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-26.1.4.tgz", - "integrity": "sha512-Nd7diUX6NZWfWq6FYyvcIPR/c7GbEF75fH1R6coOp3fbNzbRJBZZAn0ueVS0r8r9ral1VcrpneAFAwB3TsVS1Q==", + "version": "26.2.0", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-26.2.0.tgz", + "integrity": "sha512-9+y2qwzXdAImgLSYLXAb/Rhq9+K4rbt0417b8ai987V60g2uoNWBBmMkYgutI7D8Zhu+IbCSHbBtrHxB9d7xyA==", "dev": true, "requires": { + "@types/jest": "26.x", "bs-logger": "0.x", "buffer-from": "1.x", "fast-json-stable-stringify": "2.x", @@ -11862,14 +11863,6 @@ "tslib": "^1.8.1" } }, - "tsyringe": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.3.0.tgz", - "integrity": "sha512-Vzty1M/EQXSsEE8aoIOLl1l793chcPyQAnFJaS1mFDtFvNPY+jknSPwMIF6yfcjua+2GTgwxWFzuA3cjIx4NZA==", - "requires": { - "tslib": "^1.9.3" - } - }, "tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", diff --git a/package.json b/package.json index ff467fa5..2bd3bb08 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "@types/express": "^4.17.6", "@types/express-rate-limit": "^5.0.0", "@types/hapi__joi": "^17.1.4", - "@types/jest": "^26.0.7", + "@types/jest": "^26.0.10", "@types/morgan": "^1.9.1", "@types/node": "^14.0.26", "@typescript-eslint/eslint-plugin": "^3.1.0", @@ -70,7 +70,7 @@ "npm-run-all": "^4.1.5", "prettier": "^1.19.1", "rimraf": "^3.0.2", - "ts-jest": "^26.1.4", + "ts-jest": "^26.2.0", "ts-node": "^8.10.2", "tsc-watch": "^4.2.8" }, diff --git a/src/controllers/EventController.ts b/src/controllers/EventController.ts index 6c96e076..46f5e001 100644 --- a/src/controllers/EventController.ts +++ b/src/controllers/EventController.ts @@ -9,7 +9,7 @@ import { UseBefore, CurrentUser, } from 'routing-controllers'; -import { ResponseSchema } from 'routing-controllers-openapi'; +import { ResponseSchema, OpenAPI } from 'routing-controllers-openapi'; import { Event, AppUser } from '@Entities'; import { @@ -47,6 +47,7 @@ export class EventController { @Post('/') @UseBefore(OfficerAuthMiddleware) @ResponseSchema(EventResponse) + @OpenAPI({ security: [{ TokenAuth: [] }] }) async createEvent(@Body() eventRequest: EventRequest): Promise { const event = this.eventMapper.requestToNewEntity(eventRequest); const savedEvent = await this.eventService.saveEvent(event); @@ -77,6 +78,7 @@ export class EventController { @Post('/:eventID') @UseBefore(OfficerAuthMiddleware) @ResponseSchema(EventResponse) + @OpenAPI({ security: [{ TokenAuth: [] }] }) async updateEvent( @Param('eventID') id: number, @Body() eventRequest: EventRequest @@ -93,6 +95,7 @@ export class EventController { @Delete('/:eventID') @UseBefore(OfficerAuthMiddleware) @ResponseSchema(EventResponse) + @OpenAPI({ security: [{ TokenAuth: [] }] }) async deleteEvent(@Param('eventID') eventID: number): Promise { const deletedEvent = await this.eventService.deleteEvent(eventID); if (deletedEvent === undefined) { @@ -105,6 +108,7 @@ export class EventController { @Post('/:eventID/signin') @OnUndefined(409) @ResponseSchema(AttendanceResponse) + @OpenAPI({ security: [{ TokenAuth: [] }] }) async signInToEvent( @Param('eventID') eventID: number, @Body() appUserRequest: AppUserEventRequest, @@ -125,6 +129,7 @@ export class EventController { @Post('/:eventID/rsvp') @OnUndefined(409) @ResponseSchema(RSVPResponse) + @OpenAPI({ security: [{ TokenAuth: [] }] }) async rsvpForEvent( @Param('eventID') eventID: number, @Body() appUserRequest: AppUserEventRequest, diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index 4fb76fbd..d9b964ce 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -1,16 +1,18 @@ import { JsonController, Get, Param, CurrentUser, ForbiddenError } from 'routing-controllers'; -import { ResponseSchema } from 'routing-controllers-openapi'; +import { ResponseSchema, OpenAPI } from 'routing-controllers-openapi'; import { AppUser, AppUserRole } from '@Entities'; import { AppUserService, AppUserServiceImpl } from '@Services'; -import { AppUserRolesResponse } from '@Payloads'; +import { AppUserRolesResponse, AppUserProfileResponse } from '@Payloads'; +import { AppUserMapper, AppUserMapperImpl } from '@Mappers'; @JsonController('/api/users') export class UserController { - constructor(private appUserService: AppUserService) {} + constructor(private appUserService: AppUserService, private appUserMapper: AppUserMapper) {} @Get('/:userID/roles') @ResponseSchema(AppUserRolesResponse) + @OpenAPI({ security: [{ TokenAuth: [] }] }) async getUserRole( @Param('userID') userID: number, @CurrentUser({ required: true }) appUser: AppUser @@ -29,6 +31,19 @@ export class UserController { return { role: queriedRoleFromId }; } + + @Get('/:userID') + @ResponseSchema(AppUserProfileResponse) + async getUserProfile( + @Param('userID') userID: number, + @CurrentUser({ required: true }) appUser: AppUser + ): Promise { + const { id } = appUser; + + const appUserObj: AppUser = await this.appUserService.getAppUserById(userID); + + return this.appUserMapper.entityToProfileResponse(appUserObj); + } } -export const UserControllerImpl = new UserController(AppUserServiceImpl); +export const UserControllerImpl = new UserController(AppUserServiceImpl, AppUserMapperImpl); diff --git a/src/entities/AppUser.ts b/src/entities/AppUser.ts index 8ae0502a..5b94a5b5 100644 --- a/src/entities/AppUser.ts +++ b/src/entities/AppUser.ts @@ -36,7 +36,7 @@ export class AppUser { @Column({ nullable: true }) graduationYear: string; - @ManyToOne(() => InductionClass, { nullable: true }) + @ManyToOne(() => InductionClass, { nullable: true, eager: true }) inductionClass: InductionClass; @Column({ diff --git a/src/mappers/AppUserMapper.ts b/src/mappers/AppUserMapper.ts index 2d1014da..113b0d21 100644 --- a/src/mappers/AppUserMapper.ts +++ b/src/mappers/AppUserMapper.ts @@ -1,4 +1,9 @@ -import { AppUserEventRequest, AppUserEventResponse, AppUserRolesResponse } from '@Payloads'; +import { + AppUserEventRequest, + AppUserEventResponse, + AppUserRolesResponse, + AppUserProfileResponse, +} from '@Payloads'; import { AppUser } from '@Entities'; import { AppUserService, AppUserServiceImpl } from '@Services'; @@ -80,6 +85,23 @@ export class AppUserMapper { return appUserResponse; } + + /** + * Converts an AppUser entity to an AppUserProfileResponse payload and returns the newly created + * response payload to the caller. + * + * @param {AppUser} appUser The AppUser entity to be ocnverted to an AppUserProfileResponse payload. + * @returns {AppUserProfileResponse} An AppUserProfileResponse instance. + */ + entityToProfileResponse(appUser: AppUser): AppUserProfileResponse { + const plainAppUserProfile: Object = classToPlain(appUser); + const appUserProfileResponse: AppUserProfileResponse = plainToClass( + AppUserProfileResponse, + plainAppUserProfile + ); + + return appUserProfileResponse; + } } export const AppUserMapperImpl = new AppUserMapper(AppUserServiceImpl); diff --git a/src/payloads/AppUser.ts b/src/payloads/AppUser.ts index a94517c8..2898b269 100644 --- a/src/payloads/AppUser.ts +++ b/src/payloads/AppUser.ts @@ -1,6 +1,6 @@ -import { IsEnum, IsInt, IsString, IsEmail } from 'class-validator'; +import { IsEnum, IsInt, IsString, IsEmail, IsInstance, IsDateString } from 'class-validator'; -import { AppUserRole } from '@Entities'; +import { AppUserRole, InductionClass } from '@Entities'; export class AppUserPKPayload { @IsInt() @@ -46,3 +46,37 @@ export class AppUserRolesResponse { @IsEnum(AppUserRole) role: string; } + +export class AppUserInductionClass { + @IsString() + quarter: string; + + @IsString() + name: string; + + @IsDateString() + startDate: string; + + @IsDateString() + endDate: string; +} + +export class AppUserProfileResponse { + @IsString() + firstName: string; + + @IsString() + lastName: string; + + @IsString() + email: string; + + @IsString() + major: string; + + @IsString() + graduationYear: string; + + @IsInstance(AppUserInductionClass) + inductionClass: AppUserInductionClass; +} diff --git a/src/payloads/index.ts b/src/payloads/index.ts index 51153b92..90a4e384 100644 --- a/src/payloads/index.ts +++ b/src/payloads/index.ts @@ -10,6 +10,7 @@ export { AppUserEventRequest, AppUserEventResponse, AppUserRolesResponse, + AppUserProfileResponse, } from './AppUser'; export { AttendanceResponse } from './Attendance'; export { RSVPResponse } from './RSVP'; diff --git a/src/routers/DocsRouter.ts b/src/routers/DocsRouter.ts index 3cdf5548..31d0395a 100644 --- a/src/routers/DocsRouter.ts +++ b/src/routers/DocsRouter.ts @@ -7,6 +7,9 @@ import { classToPlain } from 'class-transformer'; import { controllers } from '../controllers'; import redoc from 'redoc-express'; +// TODO move this into a constants folder or config or sth +const SecuritySchemeName = 'TokenAuth'; + const rcOptions = { controllers: controllers, }; @@ -29,6 +32,12 @@ const openAPISpec = routingControllersToSpec(rcMetadataStorage, rcOptions, { }, }); +openAPISpec.components.securitySchemes = {}; +openAPISpec.components.securitySchemes[SecuritySchemeName] = { + type: 'http', + scheme: 'bearer', +}; + export const DocsRouter = express.Router(); DocsRouter.get( diff --git a/src/services/AuthenticationService.ts b/src/services/AuthenticationService.ts index dd217e30..4f25b1f8 100644 --- a/src/services/AuthenticationService.ts +++ b/src/services/AuthenticationService.ts @@ -8,18 +8,24 @@ export class AuthenticationService { constructor(private appUserService: AppUserService) {} async firebaseVerifyIdToken(token: string): Promise { + const splitToken: string[] = token.split(' '); + const userToken = splitToken[1]; + try { - const tokenResult = await admin.auth().verifyIdToken(token); + const tokenResult = await admin.auth().verifyIdToken(userToken); - if (tokenResult != null) { + if (tokenResult == null) { return undefined; } - const { - claims: { user_id }, - } = tokenResult; + const { user_id } = tokenResult; + const id = parseInt(user_id, 10); + + if (isNaN(id)) { + return undefined; + } - return await this.appUserService.getAppUserById(user_id); + return await this.appUserService.getAppUserById(id); } catch { return undefined; } @@ -39,12 +45,10 @@ export class AuthenticationService { const { devAuth } = config; if (devAuth === 'development') { - // Inject local token resolution function? return await this.localVerifyIdToken(token); } if (devAuth === 'production') { - // Inject production token resolution functinon? return await this.firebaseVerifyIdToken(token); }