Skip to content

Commit

Permalink
refactor(back): always use getOrThrow over get in ConfigService
Browse files Browse the repository at this point in the history
  • Loading branch information
tsa96 committed Nov 30, 2023
1 parent 73824f7 commit a26dcfd
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 50 deletions.
28 changes: 15 additions & 13 deletions apps/backend-e2e/src/auth.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ describe('Auth', () => {
);
steamIsLimitedSpy.mockResolvedValue(false);

jest.spyOn(configService, 'get').mockImplementation((key) => {
jest.spyOn(configService, 'getOrThrow').mockImplementation((key) => {
switch (key) {
case 'steam.preventLimited':
return true;
Expand Down Expand Up @@ -250,16 +250,18 @@ describe('Auth', () => {

it('should create an account if the user is a limited account and preventLimited is false', async () => {
steamIsLimitedSpy.mockResolvedValueOnce(true);
jest.spyOn(configService, 'get').mockImplementationOnce((key) => {
switch (key) {
case 'steam.preventLimited':
return false;
case 'jwt.expTime':
return '1m';
case 'jwt.refreshExpTime':
return '5m';
}
});
jest
.spyOn(configService, 'getOrThrow')
.mockImplementationOnce((key) => {
switch (key) {
case 'steam.preventLimited':
return false;
case 'jwt.expTime':
return '1m';
case 'jwt.refreshExpTime':
return '5m';
}
});

steamIsLimitedSpy.mockResolvedValueOnce(true);

Expand Down Expand Up @@ -287,7 +289,7 @@ describe('Auth', () => {

describe('Online API', () => {
beforeEach(() =>
jest.spyOn(configService, 'get').mockImplementation((key) => {
jest.spyOn(configService, 'getOrThrow').mockImplementation((key) => {
switch (key) {
case 'steam.useSteamTicketLibrary':
return false;
Expand Down Expand Up @@ -486,7 +488,7 @@ describe('Auth', () => {

describe('Local Library', () => {
beforeEach(() =>
jest.spyOn(configService, 'get').mockImplementation((key) => {
jest.spyOn(configService, 'getOrThrow').mockImplementation((key) => {
switch (key) {
case 'steam.useSteamTicketLibrary':
return true;
Expand Down
6 changes: 3 additions & 3 deletions apps/backend-e2e/src/maps.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,9 +557,9 @@ describe('Maps', () => {
};
});

afterAll(() => {
db.cleanup('user', 'mMap');
fileStore.deleteDirectory('submissions');
afterAll(async () => {
await db.cleanup('user', 'mMap');
await fileStore.deleteDirectory('submissions');
});

describe('should submit a map', () => {
Expand Down
4 changes: 2 additions & 2 deletions apps/backend/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ import { XpSystemsModule } from './modules/xp-systems/xp-systems.module';
}),
SentryModule.forRootAsync({
useFactory: async (config: ConfigService) => ({
environment: config.get('env'),
environment: config.getOrThrow('env'),
sentryOpts: {
dsn: config.get('sentry.dsn'),
dsn: config.getOrThrow('sentry.dsn'),
debug: false,
tracesSampleRate: 1
}
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/app/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class AuthController {
private readonly steamOpenID: SteamOpenIDService
) {
this.cookieOptions = {
domain: this.configService.get('domain'),
domain: this.configService.getOrThrow('domain'),
// The value on the cookies gets transferred to local storage immediately,
// so just use a short lifetime of 10s.
maxAge: 10000,
Expand Down
4 changes: 2 additions & 2 deletions apps/backend/src/app/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import { SteamOpenIDService } from './steam/steam-openid.service';
imports: [
JwtModule.registerAsync({
useFactory: async (config: ConfigService) => ({
secret: config.get('jwt.secret'),
signOptions: { issuer: config.get('domain') }
secret: config.getOrThrow('jwt.secret'),
signOptions: { issuer: config.getOrThrow('domain') }
}),
inject: [ConfigService]
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe('JwtAuthService', () => {
.useMocker((token) => {
if (token === ConfigService)
return {
get: jest.fn((key) => {
getOrThrow: jest.fn((key) => {
switch (key) {
case 'jwt.expTime':
return jwtConfig.expTime;
Expand Down
10 changes: 5 additions & 5 deletions apps/backend/src/app/modules/auth/jwt/jwt-auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,20 +94,20 @@ export class JwtAuthService {
return DtoFactory(JWTResponseWebDto, {
accessToken: accessToken,
refreshToken: refreshToken,
expiresIn: this.config.get('jwt.expTime')
expiresIn: this.config.getOrThrow('jwt.expTime')
});
}

private generateAccessToken(payload: UserJwtAccessPayload): Promise<string> {
return this.jwtService.signAsync(payload, {
expiresIn: payload.gameAuth
? this.config.get('jwt.gameExpTime')
: this.config.get('jwt.expTime')
expiresIn: this.config.getOrThrow(
payload.gameAuth ? 'jwt.gameExpTime' : 'jwt.expTime'
)
});
}

private async generateRefreshToken(payload: UserJwtPayload): Promise<string> {
const options = { expiresIn: this.config.get('jwt.refreshExpTime') };
const options = { expiresIn: this.config.getOrThrow('jwt.refreshExpTime') };
const refreshToken = await this.jwtService.signAsync(payload, options);

await this.db.userAuth.upsert({
Expand Down
4 changes: 2 additions & 2 deletions apps/backend/src/app/modules/auth/steam/steam-game.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class SteamGameGuard implements CanActivate {
'Missing user ticket. Should be a raw octet-stream buffer.'
);

this.configService.get('steam.useSteamTicketLibrary')
this.configService.getOrThrow('steam.useSteamTicketLibrary')
? this.verifyUserTicketLocalLibrary(userTicket, steamID)
: await this.verifyUserTicketOnlineAPI(
userTicket.toString('hex'),
Expand Down Expand Up @@ -91,7 +91,7 @@ export class SteamGameGuard implements CanActivate {
this.steamService.tryAuthenticateUserTicketLocal(userTicketRaw);

if (
!this.configService.get('appIDs').includes(appID) ||
!this.configService.getOrThrow('appIDs').includes(appID) ||
steamID !== steamIDToVerify
)
throw new UnauthorizedException('Invalid user ticket');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('SteamOpenIDService', () => {
.useMocker((token) => {
if (token === ConfigService)
return {
get: jest.fn((key) => {
getOrThrow: jest.fn((key) => {
switch (key) {
case 'url.auth':
return 'ratemyowl.com';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export class SteamOpenIDService {
private readonly config: ConfigService,
private readonly steam: SteamService
) {
const authUrl = `${this.config.get('url')}/auth`;
const apiKey = this.config.get('steam.webAPIKey');
const authUrl = `${this.config.getOrThrow('url')}/auth`;
const apiKey = this.config.getOrThrow('steam.webAPIKey');

this.relyingParty = new openid.RelyingParty(
`${authUrl}/web/return`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@ import { Test, TestingModule } from '@nestjs/testing';
import { FileStoreS3Service } from './file-store-s3.service';
import { ConfigService } from '@nestjs/config';
import { createHash } from 'node:crypto';
import { mockDeep } from 'jest-mock-extended';

describe('FileStoreS3Service', () => {
let service: FileStoreS3Service;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [FileStoreS3Service, ConfigService]
}).compile();
providers: [FileStoreS3Service]
})
.useMocker((token) => {
return token === ConfigService
? // Just mocking every S3 config value to a random string is fine here
{ getOrThrow: jest.fn(() => 'sausage') }
: mockDeep(token);
})
.compile();

service = module.get<FileStoreS3Service>(FileStoreS3Service);
});
Expand Down
10 changes: 5 additions & 5 deletions apps/backend/src/app/modules/filestore/file-store-s3.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ export class FileStoreS3Service extends FileStoreService {
super();

this.s3Client = new S3Client({
region: this.config.get('storage.region'),
endpoint: this.config.get('storage.endpointUrl'),
region: this.config.getOrThrow('storage.region'),
endpoint: this.config.getOrThrow('storage.endpointUrl'),
credentials: {
accessKeyId: this.config.get('storage.accessKeyID'),
secretAccessKey: this.config.get('storage.secretAccessKey')
accessKeyId: this.config.getOrThrow('storage.accessKeyID'),
secretAccessKey: this.config.getOrThrow('storage.secretAccessKey')
},
forcePathStyle: true
});

this.bucket = this.config.get('storage.bucketName');
this.bucket = this.config.getOrThrow('storage.bucketName');
}

async storeFile(fileBuffer: Buffer, fileKey: string): Promise<FileStoreFile> {
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/app/modules/maps/map-image.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class MapImageService {
const images = await this.db.mapImage.findMany({ where: { mapID } });
let imageCount = images.length;
if (map.thumbnailID) imageCount--; // Don't count the thumbnail towards this limit
if (imageCount >= this.config.get('limits.mapImageUploads'))
if (imageCount >= this.config.getOrThrow('limits.mapImageUploads'))
throw new ConflictException('Map image file limit reached');

// It may seem strange to create an entry with nothing but a key into Map,
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/app/modules/reports/reports.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class ReportsService {
}
});

if (recentReports >= this.config.get('limits.dailyReports'))
if (recentReports >= this.config.getOrThrow('limits.dailyReports'))
throw new ConflictException(
'You have reached the limit of daily reports'
);
Expand Down
10 changes: 6 additions & 4 deletions apps/backend/src/app/modules/steam/steam.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ export class SteamService {
private readonly http: HttpService,
private readonly config: ConfigService
) {
this.steamApiKey = this.config.get('steam.webAPIKey');
this.steamTicketsSecretKey = this.config.get('steam.ticketsSecretKey');
this.steamApiKey = this.config.getOrThrow('steam.webAPIKey');
this.steamTicketsSecretKey = this.config.getOrThrow(
'steam.ticketsSecretKey'
);
}

private readonly steamApiKey: string;
Expand All @@ -33,7 +35,7 @@ export class SteamService {
this.http
.get('https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/', {
params: {
key: this.config.get('steam.webAPIKey'),
key: this.config.getOrThrow('steam.webAPIKey'),
steamids: steamID.toString()
}
})
Expand Down Expand Up @@ -99,7 +101,7 @@ export class SteamService {
'https://api.steampowered.com/ISteamUserAuth/AuthenticateUserTicket/v1/',
{
params: {
key: this.config.get('steam.webAPIKey'),
key: this.config.getOrThrow('steam.webAPIKey'),
appid: appID,
ticket: ticket
}
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/app/modules/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export class UsersService {
});
} else {
if (
this.config.get('steam.preventLimited') &&
this.config.getOrThrow('steam.preventLimited') &&
(await this.steamService.isAccountLimited(userData.steamID))
)
throw new ForbiddenException(
Expand Down
10 changes: 6 additions & 4 deletions apps/backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ async function bootstrap() {
);

const configService = app.get(ConfigService);
const env: Environment = configService.get('env');
const env: Environment = configService.getOrThrow('env');

// Steam game auth and replay submission from game send raw octet-streams.
// Steam auth we could limit to 2kb, but replays can be massive. Limiting
Expand Down Expand Up @@ -90,7 +90,7 @@ async function bootstrap() {
await app.register(cors, {
origin:
env === Environment.PRODUCTION
? this.config.get('url')
? this.config.getOrThrow('url')
: 'http://localhost:4200',
allowedHeaders: [
'Origin',
Expand All @@ -105,7 +105,9 @@ async function bootstrap() {
});

// Cookies for transferring JWTs back to client after OpenID auth
await app.register(cookie, { secret: configService.get('sessionSecret') });
await app.register(cookie, {
secret: configService.getOrThrow('sessionSecret')
});

await app.enableShutdownHooks();

Expand All @@ -128,7 +130,7 @@ async function bootstrap() {
});

// Here we fucking go!!!
await app.listen(configService.get('port'));
await app.listen(configService.getOrThrow('port'));
}

bootstrap().then();

0 comments on commit a26dcfd

Please sign in to comment.