Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EW-1004 implement getData method for TSP Strategy #5253

Merged
merged 18 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { SchoolNameRequiredLoggableException } from './school-name-required-loggable-exception';

describe(SchoolNameRequiredLoggableException.name, () => {
describe('getLogMessage', () => {
const setup = () => {
const fieldName = 'id_token';

const exception = new SchoolNameRequiredLoggableException(fieldName);

return { exception, fieldName };
};

it('should return a LogMessage', () => {
const { exception, fieldName } = setup();

const logMessage = exception.getLogMessage();

expect(logMessage).toEqual({
type: 'SCHOOL_NAME_REQUIRED',
message: 'External school name is required',
stack: exception.stack,
data: {
fieldName,
},
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { HttpStatus } from '@nestjs/common';
import { BusinessError } from '@shared/common';
import { ErrorLogMessage, Loggable, LogMessage, ValidationErrorLogMessage } from '@src/core/logger';

export class SchoolNameRequiredLoggableException extends BusinessError implements Loggable {
MajedAlaitwniCap marked this conversation as resolved.
Show resolved Hide resolved
constructor(private readonly fieldName: string) {
super(
{
type: 'SCHOOL_NAME_REQUIRED',
title: 'School name is required',
defaultMessage: 'External school name is required',
},
HttpStatus.INTERNAL_SERVER_ERROR
);
}

getLogMessage(): LogMessage | ErrorLogMessage | ValidationErrorLogMessage {
return {
type: this.type,
message: this.message,
stack: this.stack,
data: {
fieldName: this.fieldName,
},
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { SchoolFeature } from '@shared/domain/types';
import { federalStateFactory, legacySchoolDoFactory, schoolYearFactory } from '@shared/testing';
import { ExternalSchoolDto } from '../../../dto';
import { SchulconnexSchoolProvisioningService } from './schulconnex-school-provisioning.service';
import { SchoolNameRequiredLoggableException } from '../../loggable/school-name-required-loggable-exception';

describe(SchulconnexSchoolProvisioningService.name, () => {
let module: TestingModule;
Expand Down Expand Up @@ -183,7 +184,7 @@ describe(SchulconnexSchoolProvisioningService.name, () => {
const { systemId, externalSchoolDto } = setup();

await expect(service.provisionExternalSchool(externalSchoolDto, systemId)).rejects.toThrowError(
psachmann marked this conversation as resolved.
Show resolved Hide resolved
'External school name is required'
new SchoolNameRequiredLoggableException('ExternalSchool.name')
);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { LegacySchoolDo } from '@shared/domain/domainobject';
import { FederalStateEntity, SchoolYearEntity } from '@shared/domain/entity';
import { EntityId, SchoolFeature } from '@shared/domain/types';
import { ExternalSchoolDto } from '../../../dto';
import { SchoolNameRequiredLoggableException } from '../../loggable/school-name-required-loggable-exception';

@Injectable()
export class SchulconnexSchoolProvisioningService {
Expand Down Expand Up @@ -54,7 +55,7 @@ export class SchulconnexSchoolProvisioningService {

private getSchoolName(externalSchool: ExternalSchoolDto): string {
if (!externalSchool.name) {
throw new Error('External school name is required');
throw new SchoolNameRequiredLoggableException('ExternalSchool.name');
}
const schoolName: string = externalSchool.location
? `${externalSchool.name} (${externalSchool.location})`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,27 @@ export class TspJwtPayload implements JwtPayload {

@IsOptional()
@IsString()
public sid!: string;
public sid!: string | undefined;

@IsOptional()
@IsString()
public ptscListRolle!: string;
public ptscListRolle!: string | undefined;

@IsOptional()
@IsString()
public personVorname!: string;
public personVorname!: string | undefined;

@IsOptional()
@IsString()
public personNachname!: string;
public personNachname!: string | undefined;

@IsOptional()
@IsString()
public ptscSchuleNummer!: string;
public ptscSchuleNummer!: string | undefined;

@IsOptional()
@IsArray()
public ptscListKlasseId!: [];
public ptscListKlasseId!: [] | undefined;

constructor(data: Partial<TspJwtPayload>) {
Object.assign(this, data);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { RoleName } from '@shared/domain/interface';
import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy';
import { userDoFactory } from '@shared/testing';
import { SchoolService } from '@src/modules/school';
import { IdTokenExtractionFailureLoggableException } from '@src/modules/oauth/loggable';
import jwt from 'jsonwebtoken';
import {
ExternalClassDto,
Expand All @@ -31,10 +31,6 @@ describe('TspProvisioningStrategy', () => {
provide: TspProvisioningService,
useValue: createMock<TspProvisioningService>(),
},
{
provide: SchoolService,
useValue: createMock<SchoolService>(),
},
],
}).compile();

Expand Down Expand Up @@ -76,7 +72,7 @@ describe('TspProvisioningStrategy', () => {
return {
sub: 'externalUserId',
sid: 'externalSchoolId',
ptscListRolle: 'teacher',
ptscListRolle: 'schueler,lehrer,admin',
personVorname: 'firstName',
personNachname: 'lastName',
ptscSchuleNummer: 'externalSchoolId',
Expand All @@ -86,7 +82,7 @@ describe('TspProvisioningStrategy', () => {

const user: ExternalUserDto = new ExternalUserDto({
externalId: 'externalUserId',
roles: [RoleName.TEACHER],
roles: [RoleName.STUDENT, RoleName.TEACHER, RoleName.ADMINISTRATOR],
firstName: 'firstName',
lastName: 'lastName',
});
Expand All @@ -106,19 +102,19 @@ describe('TspProvisioningStrategy', () => {
const { input, user, school, externalClasses } = setup();
const result = await sut.getData(input);

expect(result).toEqual({
expect(result).toEqual<OauthDataDto>({
system: input.system,
externalUser: user,
externalSchool: school,
externalGroups: undefined,
externalLicenses: undefined,
externalClasses,
} as OauthDataDto);
});
});
});

describe('When idToken is invalid', () => {
it('should throw', async () => {
const setup = () => {
const input: OauthDataStrategyInputDto = new OauthDataStrategyInputDto({
system: new ProvisioningSystemDto({
systemId: 'externalSchoolId',
Expand All @@ -130,12 +126,18 @@ describe('TspProvisioningStrategy', () => {

jest.spyOn(jwt, 'decode').mockImplementation(() => null);

await expect(sut.getData(input)).rejects.toThrow();
return { input };
};

it('should throw IdTokenExtractionFailure', async () => {
const { input } = setup();

await expect(sut.getData(input)).rejects.toThrow(new IdTokenExtractionFailureLoggableException('sub'));
});
});

describe('When idToken is missing sub', () => {
it('should throw', async () => {
const setup = () => {
const input: OauthDataStrategyInputDto = new OauthDataStrategyInputDto({
system: new ProvisioningSystemDto({
systemId: 'externalSchoolId',
Expand All @@ -149,12 +151,17 @@ describe('TspProvisioningStrategy', () => {
return {};
});

await expect(sut.getData(input)).rejects.toThrow();
return { input };
};
it('should throw IdTokenExtractionFailure', async () => {
const { input } = setup();

await expect(sut.getData(input)).rejects.toThrow(new IdTokenExtractionFailureLoggableException('sub'));
});
});

describe('When payload is invalid', () => {
it('should throw', async () => {
const setup = () => {
const input: OauthDataStrategyInputDto = new OauthDataStrategyInputDto({
system: new ProvisioningSystemDto({
systemId: 'externalSchoolId',
Expand All @@ -176,7 +183,13 @@ describe('TspProvisioningStrategy', () => {
};
});

await expect(sut.getData(input)).rejects.toThrow();
return { input };
};

it('should throw IdTokenExtractionFailure', async () => {
const { input } = setup();

await expect(sut.getData(input)).rejects.toThrow(new IdTokenExtractionFailureLoggableException('sub'));
});
});
});
Expand Down
26 changes: 11 additions & 15 deletions apps/server/src/modules/provisioning/strategy/tsp/tsp.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Injectable } from '@nestjs/common';
import { RoleName } from '@shared/domain/interface';
import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy';
import { IdTokenExtractionFailureLoggableException } from '@src/modules/oauth/loggable';
import { SchoolService } from '@src/modules/school';
import { validate } from 'class-validator';
import jwt, { JwtPayload } from 'jsonwebtoken';
import {
Expand All @@ -12,7 +11,6 @@ import {
OauthDataDto,
OauthDataStrategyInputDto,
ProvisioningDto,
ProvisioningSystemDto,
} from '../../dto';
import { TspProvisioningService } from '../../service/tsp-provisioning.service';
import { ProvisioningStrategy } from '../base.strategy';
Expand All @@ -21,10 +19,13 @@ import { TspJwtPayload } from './tsp.jwt.payload';

@Injectable()
export class TspProvisioningStrategy extends ProvisioningStrategy {
constructor(
private readonly provisioningService: TspProvisioningService,
private readonly schoolService: SchoolService
) {
RoleMapping: Record<string, RoleName> = {
lehrer: RoleName.TEACHER,
schueler: RoleName.STUDENT,
admin: RoleName.ADMINISTRATOR,
};

constructor(private readonly provisioningService: TspProvisioningService) {
super();
}

Expand All @@ -46,28 +47,23 @@ export class TspProvisioningStrategy extends ProvisioningStrategy {
throw new IdTokenExtractionFailureLoggableException(errors.map((error) => error.property).join(', '));
}

const provisioningSystemDto = new ProvisioningSystemDto({
systemId: payload.sid,
provisioningStrategy: SystemProvisioningStrategy.TSP,
});

const externalUserDto = new ExternalUserDto({
externalId: payload.sub,
firstName: payload.personVorname,
lastName: payload.personNachname,
roles: Object.values(RoleName).filter((role) => payload.ptscListRolle.split(',').includes(role)),
roles: (payload.ptscListRolle ?? '').split(',').map((tspRole) => this.RoleMapping[tspRole]),
});

const externalSchoolDto = new ExternalSchoolDto({
externalId: payload.ptscSchuleNummer,
externalId: payload.ptscSchuleNummer || '',
});

const externalClassDtoList = payload.ptscListKlasseId.map(
const externalClassDtoList = (payload.ptscListKlasseId ?? []).map(
(classId: string) => new ExternalClassDto({ externalId: classId })
);

const oauthDataDto = new OauthDataDto({
system: provisioningSystemDto,
system: input.system,
externalUser: externalUserDto,
externalSchool: externalSchoolDto,
externalClasses: externalClassDtoList,
Expand Down
Loading