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 10 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
@@ -1,7 +1,7 @@
export class ExternalClassDto {
public readonly externalId: string;

public readonly name: string;
public readonly name?: string;

constructor(props: Readonly<ExternalClassDto>) {
this.externalId = props.externalId;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export class ExternalSchoolDto {
externalId: string;

name: string;
name?: string;

officialSchoolNumber?: string;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ export class TspProvisioningService {
if (currentClass) {
// Case: Class exists -> update class
currentClass.schoolId = school.id;
currentClass.name = clazz.name;
if (clazz.name) {
currentClass.name = clazz.name;
}
currentClass.year = school.currentYear?.id;
currentClass.source = this.ENTITY_SOURCE;
currentClass.sourceOptions = new ClassSourceOptions({ tspUid: clazz.externalId });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,48 @@ describe(SchulconnexSchoolProvisioningService.name, () => {
});
});

describe('when the external system does not provide a Name for the school', () => {
const setup = () => {
const systemId = new ObjectId().toHexString();
const externalSchoolDto: ExternalSchoolDto = new ExternalSchoolDto({
externalId: 'externalId',
officialSchoolNumber: 'officialSchoolNumber',
});

const schoolYear = schoolYearFactory.build();
const federalState = federalStateFactory.build();
const savedSchoolDO = new LegacySchoolDo({
id: 'schoolId',
externalId: 'externalId',
name: 'name',
officialSchoolNumber: 'officialSchoolNumber',
systems: [systemId],
features: [SchoolFeature.OAUTH_PROVISIONING_ENABLED],
schoolYear,
federalState,
});

schoolService.save.mockResolvedValue(savedSchoolDO);
schoolService.getSchoolByExternalId.mockResolvedValue(null);
schoolYearService.getCurrentSchoolYear.mockResolvedValue(schoolYear);
federalStateService.findFederalStateByName.mockResolvedValue(federalState);

return {
systemId,
externalSchoolDto,
savedSchoolDO,
};
};

it('should throw an error', async () => {
const { systemId, externalSchoolDto } = setup();

await expect(service.provisionExternalSchool(externalSchoolDto, systemId)).rejects.toThrowError(
'External school name is required'
);
});
});

describe('when the external system does not provide a location for the school', () => {
const setup = () => {
const systemId = new ObjectId().toHexString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ export class SchulconnexSchoolProvisioningService {
}

private getSchoolName(externalSchool: ExternalSchoolDto): string {
if (!externalSchool.name) {
throw new Error('External school name is required');
}
const schoolName: string = externalSchool.location
? `${externalSchool.name} (${externalSchool.location})`
: externalSchool.name;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { IsString, IsOptional, IsArray } from 'class-validator';
import { JwtPayload } from 'jsonwebtoken';

export class TspJwtPayload implements JwtPayload {
@IsString()
public sub!: string;

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

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

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

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

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

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

constructor(data: Partial<TspJwtPayload>) {
Object.assign(this, data);
}
}
124 changes: 122 additions & 2 deletions apps/server/src/modules/provisioning/strategy/tsp/tsp.strategy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ 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 jwt from 'jsonwebtoken';
import {
ExternalClassDto,
ExternalSchoolDto,
ExternalUserDto,
OauthDataDto,
Expand All @@ -28,6 +31,10 @@ describe('TspProvisioningStrategy', () => {
provide: TspProvisioningService,
useValue: createMock<TspProvisioningService>(),
},
{
provide: SchoolService,
useValue: createMock<SchoolService>(),
},
],
}).compile();

Expand Down Expand Up @@ -55,8 +62,121 @@ describe('TspProvisioningStrategy', () => {

describe('getData', () => {
describe('When called', () => {
it('should throw', () => {
expect(() => sut.getData({} as OauthDataStrategyInputDto)).toThrow();
const setup = () => {
const input: OauthDataStrategyInputDto = new OauthDataStrategyInputDto({
system: new ProvisioningSystemDto({
systemId: 'externalSchoolId',
provisioningStrategy: SystemProvisioningStrategy.TSP,
}),
idToken: 'tspIdToken',
accessToken: 'tspAccessToken',
});

jest.spyOn(jwt, 'decode').mockImplementation(() => {
return {
sub: 'externalUserId',
sid: 'externalSchoolId',
ptscListRolle: 'teacher',
personVorname: 'firstName',
personNachname: 'lastName',
ptscSchuleNummer: 'externalSchoolId',
ptscListKlasseId: ['externalClassId1', 'externalClassId2'],
};
});

const user: ExternalUserDto = new ExternalUserDto({
externalId: 'externalUserId',
roles: [RoleName.TEACHER],
firstName: 'firstName',
lastName: 'lastName',
});

const school: ExternalSchoolDto = new ExternalSchoolDto({
externalId: 'externalSchoolId',
});

const externalClass1 = new ExternalClassDto({ externalId: 'externalClassId1' });
const externalClass2 = new ExternalClassDto({ externalId: 'externalClassId2' });
const externalClasses = [externalClass1, externalClass2];

return { input, user, school, externalClasses };
};

it('should return mapped oauthDataDto if input is valid', async () => {
const { input, user, school, externalClasses } = setup();
const result = await sut.getData(input);

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

describe('When idToken is invalid', () => {
it('should throw', async () => {
const input: OauthDataStrategyInputDto = new OauthDataStrategyInputDto({
system: new ProvisioningSystemDto({
systemId: 'externalSchoolId',
provisioningStrategy: SystemProvisioningStrategy.TSP,
}),
idToken: 'invalidIdToken',
accessToken: 'tspAccessToken',
});

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

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

describe('When idToken is missing sub', () => {
it('should throw', async () => {
const input: OauthDataStrategyInputDto = new OauthDataStrategyInputDto({
system: new ProvisioningSystemDto({
systemId: 'externalSchoolId',
provisioningStrategy: SystemProvisioningStrategy.TSP,
}),
idToken: 'invalidIdToken',
accessToken: 'tspAccessToken',
});

jest.spyOn(jwt, 'decode').mockImplementation(() => {
return {};
});

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

describe('When payload is invalid', () => {
it('should throw', async () => {
const input: OauthDataStrategyInputDto = new OauthDataStrategyInputDto({
system: new ProvisioningSystemDto({
systemId: 'externalSchoolId',
provisioningStrategy: SystemProvisioningStrategy.TSP,
}),
idToken: 'tspIdToken',
accessToken: 'tspAccessToken',
});

jest.spyOn(jwt, 'decode').mockImplementation(() => {
return {
sub: 'externalUserId',
sid: 1000,
ptscListRolle: 'teacher',
personVorname: 'firstName',
personNachname: 'lastName',
ptscSchuleNummer: 'externalSchoolId',
ptscListKlasseId: ['externalClassId1', 'externalClassId2'],
};
});

await expect(sut.getData(input)).rejects.toThrow();
});
});
});
Expand Down
69 changes: 62 additions & 7 deletions apps/server/src/modules/provisioning/strategy/tsp/tsp.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,79 @@
import { Injectable, NotImplementedException } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { RoleName } from '@shared/domain/interface';
import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy';
import { OauthDataDto, OauthDataStrategyInputDto, ProvisioningDto } from '../../dto';
import { IdTokenExtractionFailureLoggableException } from '@src/modules/oauth/loggable';
import { SchoolService } from '@src/modules/school';
import { validate } from 'class-validator';
import jwt, { JwtPayload } from 'jsonwebtoken';
import {
ExternalClassDto,
ExternalSchoolDto,
ExternalUserDto,
OauthDataDto,
OauthDataStrategyInputDto,
ProvisioningDto,
ProvisioningSystemDto,
} from '../../dto';
import { TspProvisioningService } from '../../service/tsp-provisioning.service';
import { ProvisioningStrategy } from '../base.strategy';
import { BadDataLoggableException } from '../loggable';
import { TspJwtPayload } from './tsp.jwt.payload';

@Injectable()
export class TspProvisioningStrategy extends ProvisioningStrategy {
constructor(private readonly provisioningService: TspProvisioningService) {
constructor(
private readonly provisioningService: TspProvisioningService,
private readonly schoolService: SchoolService
) {
super();
}

getType(): SystemProvisioningStrategy {
return SystemProvisioningStrategy.TSP;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
override getData(input: OauthDataStrategyInputDto): Promise<OauthDataDto> {
// TODO EW-1004
throw new NotImplementedException();
override async getData(input: OauthDataStrategyInputDto): Promise<OauthDataDto> {
const decodedAccessToken: JwtPayload | null = jwt.decode(input.accessToken, { json: true });

if (!decodedAccessToken || !decodedAccessToken.sub) {
throw new IdTokenExtractionFailureLoggableException('sub');
}

const payload = new TspJwtPayload(decodedAccessToken);
const errors = await validate(payload);

if (errors.length > 0) {
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)),
});

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

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

const oauthDataDto = new OauthDataDto({
system: provisioningSystemDto,
externalUser: externalUserDto,
externalSchool: externalSchoolDto,
externalClasses: externalClassDtoList,
});

return oauthDataDto;
}

override async apply(data: OauthDataDto): Promise<ProvisioningDto> {
Expand Down
Loading