Compare commits

...

10 Commits

Author SHA1 Message Date
Sven Czarnian
cb9aff155d add endpoints to check if a token is valid 2022-11-04 22:57:30 +01:00
Sven Czarnian
822b39f4fd add functions to login the radar scope 2022-11-04 21:47:34 +01:00
Sven Czarnian
912a8e7509 introduce the RADAR scope token 2022-11-04 21:33:24 +01:00
Sven Czarnian
17f521008c introduce the system module 2022-11-04 13:13:48 +01:00
Sven Czarnian
1d6d0b63e9 fix the return type documentation 2022-11-04 13:13:35 +01:00
Sven Czarnian
e75d872173 introduce the push notification for the airport 2022-11-03 23:33:55 +01:00
Sven Czarnian
1a4fa7e4ab add the new modules 2022-11-03 23:33:29 +01:00
Sven Czarnian
b7f6b079c3 add a system controller with the current timestamp 2022-11-03 23:33:17 +01:00
Sven Czarnian
13f5862654 introduce server sent events services 2022-11-03 23:32:54 +01:00
Sven Czarnian
0b19c4eab1 protect the airport endpoints 2022-11-03 23:32:32 +01:00
15 changed files with 258 additions and 2 deletions

View File

@@ -8,6 +8,8 @@ import {
Query,
HttpException,
HttpStatus,
Sse,
UseGuards,
} from '@nestjs/common';
import { ApiBody, ApiQuery, ApiResponse } from '@nestjs/swagger';
import { AirportService } from './airport.service';
@@ -32,10 +34,16 @@ import { ActiveRunwaysDto } from './dto/activerunways.dto';
import { Runway } from './models/runway.model';
import { RunwayDto } from './dto/runway.dto';
import { AirportOverviewDto } from './dto/airportoverview.dto';
import { Observable } from 'rxjs';
import { EventsService } from '../events/events.service';
import { JwtGuard } from 'src/auth/guards/jwt.guard';
@Controller('airport')
export class AirportController {
constructor(private readonly airportService: AirportService) {}
constructor(
private readonly airportService: AirportService,
private readonly eventService: EventsService,
) {}
private static convertConstraint<T>(
constraint: Constraint | ConstraintDto,
@@ -246,6 +254,12 @@ export class AirportController {
});
}
@Sse('/renew')
renew(): Observable<unknown> {
return this.eventService.subscribeAirportRenew();
}
@UseGuards(JwtGuard)
@Get('/all')
@ApiResponse({
status: 200,
@@ -256,6 +270,7 @@ export class AirportController {
return this.airportService.allAirports();
}
@UseGuards(JwtGuard)
@Get('/get')
@ApiQuery({
name: 'icao',
@@ -280,6 +295,7 @@ export class AirportController {
});
}
@UseGuards(JwtGuard)
@Post('/register')
@ApiBody({
description: 'The airport definition',
@@ -317,6 +333,7 @@ export class AirportController {
});
}
@UseGuards(JwtGuard)
@Delete('/remove')
@ApiQuery({
name: 'icao',
@@ -340,6 +357,7 @@ export class AirportController {
});
}
@UseGuards(JwtGuard)
@Patch('/activateRunways')
@ApiBody({
description: 'The airport definition',

View File

@@ -3,10 +3,12 @@ import { MongooseModule } from '@nestjs/mongoose';
import { AirportSchema } from './models/airport.model';
import { AirportService } from './airport.service';
import { AirportController } from './airport.controller';
import { EventsModule } from 'src/events/events.module';
@Module({
imports: [
MongooseModule.forFeature([{ name: 'airport', schema: AirportSchema }]),
EventsModule,
],
providers: [AirportService],
controllers: [AirportController],

View File

@@ -10,6 +10,8 @@ import { LoggingModule } from './logging/logging.module';
import { InboundModule } from './inbound/inbound.module';
import { WeatherModule } from './weather/weather.module';
import { AuthModule } from './auth/auth.module';
import { EventsModule } from './events/events.module';
import { SystemModule } from './system/system.module';
@Module({
imports: [
@@ -39,6 +41,8 @@ import { AuthModule } from './auth/auth.module';
InboundModule,
WeatherModule,
AuthModule,
EventsModule,
SystemModule,
],
})
export class AppModule {}

View File

@@ -1,17 +1,22 @@
import {
Body,
Controller,
Get,
HttpException,
HttpStatus,
Patch,
Post,
Query,
Redirect,
Req,
UseGuards,
} from '@nestjs/common';
import { ApiQuery } from '@nestjs/swagger';
import { ApiBody, ApiQuery, ApiResponse } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { JwtGuard } from './guards/jwt.guard';
import { RadarScopeDto } from './dto/radarscope.dto';
import { RadarTokenDto } from './dto/radartoken.dto';
import { UserDto } from './dto/user.dto';
import { Request } from 'express';
@@ -56,6 +61,49 @@ export class AuthController {
}
}
@Post('/radarScope')
@ApiBody({
description: 'The airport definition',
type: RadarScopeDto,
})
@ApiResponse({
status: 200,
description: 'The created Bearer token to use endpoints',
type: RadarTokenDto,
})
@ApiResponse({
status: 404,
description: 'The VATSIM ID and key combination is invalid',
})
async radarScope(
@Body('scopeData') scopeData: RadarScopeDto,
): Promise<RadarTokenDto> {
return this.authService
.loginRadarScope(scopeData.vatsimId, scopeData.key)
.then((token) => {
if (token === undefined) {
throw new HttpException(
'Unknown VATSIM ID or invalid key',
HttpStatus.NOT_FOUND,
);
}
return { token };
});
}
@UseGuards(JwtGuard)
@Get('/validate')
@ApiResponse({
status: 200,
description: 'The created Bearer token to use endpoints',
})
@ApiResponse({
status: 401,
description: 'The sent Bearer token is invalid',
})
// eslint-disable-next-line @typescript-eslint/no-empty-function
validate(): void {}
@UseGuards(JwtGuard)
@Get('/user')
async user(@Req() request: Request): Promise<UserDto> {
@@ -68,9 +116,17 @@ export class AuthController {
return {
vatsimId: user.vatsimId,
fullName: user.fullName,
radarScopeKey: user.radarScopeKey,
administrator: user.administrator,
airportConfigurationAccess: user.airportConfigurationAccess,
};
});
}
@UseGuards(JwtGuard)
@Patch('/refreshRadarScopeKey')
async refreshRadarScopeKey(@Req() request: Request): Promise<void> {
const token = request.headers.authorization.replace('Bearer ', '');
return this.authService.resetRadarScopeKey(token);
}
}

View File

@@ -4,6 +4,7 @@ import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { v4 as uuid } from 'uuid';
import { catchError, lastValueFrom, map } from 'rxjs';
import { User, UserDocument } from './models/user.model';
@@ -76,6 +77,7 @@ export class AuthService {
this.userModel.create({
vatsimId: userdata.cid,
fullName,
radarScopeKey: uuid(),
vatsimToken: token,
vatsimRefreshToken: refreshToken,
});
@@ -110,4 +112,24 @@ export class AuthService {
return user;
});
}
async loginRadarScope(vatsimId: string, key: string): Promise<string> {
return this.userModel.findOne({ vatsimId }).then((user) => {
if (!user || user.radarScopeKey !== key) return undefined;
const payload = { vatsimId: vatsimId, sub: key };
return this.jwtService.sign(payload);
});
}
async resetRadarScopeKey(token: string): Promise<void> {
const payload = this.jwtService.verify(token, {
secret: this.config.get<string>('server.jwt-secret'),
});
await this.userModel.findOneAndUpdate(
{ vatsimId: payload.vatsimId },
{ radarScopeKey: uuid() },
);
}
}

View File

@@ -0,0 +1,18 @@
import { IsNotEmpty } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class RadarScopeDto {
@IsNotEmpty()
@ApiProperty({
description: 'The VATSIM ID of the controller',
example: '10000001',
})
vatsimId: string;
@IsNotEmpty()
@ApiProperty({
description: 'The unique key to logon the RADAR scope',
example: 'SECRET',
})
key: string;
}

View File

@@ -0,0 +1,11 @@
import { IsNotEmpty } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class RadarTokenDto {
@IsNotEmpty()
@ApiProperty({
description: 'The usable Bearer token',
example: 'SECRET',
})
token: string;
}

View File

@@ -16,6 +16,13 @@ export class UserDto {
})
fullName: string;
@IsNotEmpty()
@ApiProperty({
description: 'The unique logon code for the radar scope plugins',
example: 'SECRET',
})
radarScopeKey: string;
@IsNotEmpty()
@ApiProperty({
description: 'Indicates if the user has administrator access',

View File

@@ -17,6 +17,11 @@ export class User {
})
fullName: string;
@Prop({
type: String,
})
radarScopeKey: string;
@Prop({
required: true,
type: String,

View File

@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { EventsService } from './events.service';
@Module({
providers: [EventsService],
exports: [EventsService],
})
export class EventsModule {}

View File

@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { EventsService } from './events.service';
describe('EventsService', () => {
let service: EventsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [EventsService],
}).compile();
service = module.get<EventsService>(EventsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@@ -0,0 +1,44 @@
import { Injectable } from '@nestjs/common';
import { EventEmitter } from 'events';
import { fromEvent, Observable } from 'rxjs';
@Injectable()
export class EventsService {
private readonly emitter: EventEmitter;
constructor() {
this.emitter = new EventEmitter();
}
private subscribe(event: string): Observable<unknown> {
return fromEvent(this.emitter, event);
}
private emit(event: string, data: any): void {
this.emitter.emit(event, data);
}
subscribeUserPrivilegeUpdate(vatsimId: string): Observable<unknown> {
return this.subscribe(`/users/${vatsimId}`);
}
emitUserPrivilegeUpdate(vatsimId: string): void {
this.emit(`/users/${vatsimId}`, {});
}
subscribeAirportRenew(): Observable<unknown> {
return this.subscribe('/airports/renew');
}
emitAirportRenew(): void {
this.emit('/airports/renew', {});
}
subscribeArrivalSequenceUpdate(icao: string): Observable<unknown> {
return this.subscribe(`/airports/arrival/${icao}`);
}
emitArrivalSequenceUpdate(icao: string): void {
this.emit(`/airports/arrival/${icao}`, {});
}
}

View File

@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SystemController } from './system.controller';
describe('SystemController', () => {
let controller: SystemController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [SystemController],
}).compile();
controller = module.get<SystemController>(SystemController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@@ -0,0 +1,16 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiResponse } from '@nestjs/swagger';
import { JwtGuard } from 'src/auth/guards/jwt.guard';
@Controller('system')
export class SystemController {
@UseGuards(JwtGuard)
@Get('/timestamp')
@ApiResponse({
description: 'The current ZULU timestamp of the system',
type: Number,
})
async timestamp(): Promise<number> {
return new Date().getTime();
}
}

View File

@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { EventsModule } from 'src/events/events.module';
import { SystemController } from './system.controller';
@Module({
imports: [EventsModule],
controllers: [SystemController],
})
export class SystemModule {}