Compare commits

..

No commits in common. "61e232d9b0427fa66eb568cc76144cc809e38433" and "46f69e1c53dcd4d64394f9088fb9f0bb3221e0c9" have entirely different histories.

4 changed files with 73 additions and 66 deletions

View File

@ -3,7 +3,6 @@ import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { CorsMiddleware } from './middleware/cors-middleware/cors.middlware';
import { CspMiddleware } from './middleware/csp-middleware/csp.middleware'; import { CspMiddleware } from './middleware/csp-middleware/csp.middleware';
import { HttpsRedirectMiddleware } from './middleware/https-middlware/https-redirect.middleware'; import { HttpsRedirectMiddleware } from './middleware/https-middlware/https-redirect.middleware';
import { SecurityHeadersMiddleware } from './middleware/security-middleware/security.middleware'; import { SecurityHeadersMiddleware } from './middleware/security-middleware/security.middleware';
@ -35,8 +34,8 @@ export class AppModule {
.apply( .apply(
CspMiddleware, CspMiddleware,
SecurityHeadersMiddleware, SecurityHeadersMiddleware,
HttpsRedirectMiddleware, HttpsRedirectMiddleware
CorsMiddleware //CorsMiddleware
) )
.forRoutes({ path: '*', method: RequestMethod.ALL }); .forRoutes({ path: '*', method: RequestMethod.ALL });
} }

View File

@ -8,13 +8,10 @@ export class CorsMiddleware implements NestMiddleware {
public use(req: Request, res: Response, next: NextFunction): void { public use(req: Request, res: Response, next: NextFunction): void {
if (this.configService.get<string>('NODE_ENV') === 'development') { if (this.configService.get<string>('NODE_ENV') === 'development') {
const allowedOrigins = this.configService const allowedOrigin = this.configService.get<string>('CORS_ALLOW_ORIGIN');
.get<string>('CORS_ALLOW_ORIGIN')
.split(',');
const requestOrigin = req.headers.origin;
if (!requestOrigin || allowedOrigins.includes(requestOrigin)) { if (req.headers.origin === allowedOrigin) {
res.header('Access-Control-Allow-Origin', requestOrigin || '*'); res.header('Access-Control-Allow-Origin', allowedOrigin);
res.header( res.header(
'Access-Control-Allow-Methods', 'Access-Control-Allow-Methods',
this.configService.get<string>('CORS_ALLOW_METHODS') this.configService.get<string>('CORS_ALLOW_METHODS')

View File

@ -2,22 +2,24 @@ import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Response } from 'express'; import { Response } from 'express';
import { Session } from 'src/entities'; import { Session } from 'src/entities';
import { DeleteResult, Repository } from 'typeorm'; import { LessThan, Repository } from 'typeorm';
import { LessThan } from 'typeorm';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
@Injectable() @Injectable()
export class SessionRepository { export class SessionRepository {
public constructor( public constructor(
@InjectRepository(Session) private sessionRepository: Repository<Session> @InjectRepository(Session)
private sessionRepository: Repository<Session>
) {} ) {}
public createSession(userId: string, userAgent: string): Promise<Session> { public async createSession(
userId: string,
userAgent: string
): Promise<Session> {
const sessionId = uuidv4(); const sessionId = uuidv4();
const expirationDate = new Date(); const expirationDate = new Date();
expirationDate.setHours(expirationDate.getHours() + 1); expirationDate.setHours(expirationDate.getHours() + 1);
const session = this.sessionRepository.create({ const session = this.sessionRepository.create({
userCredentials: userId, userCredentials: userId,
sessionId, sessionId,
@ -25,12 +27,13 @@ export class SessionRepository {
userAgent, userAgent,
}); });
return this.sessionRepository.save(session); await this.sessionRepository.save(session);
return session;
} }
public findSessionBySessionId(sessionId: string): Promise<Session> { public async findSessionBySessionId(sessionId: string): Promise<Session> {
return this.sessionRepository.findOne({ return await this.sessionRepository.findOne({
where: { sessionId }, where: { sessionId: sessionId },
relations: ['userCredentials'], relations: ['userCredentials'],
}); });
} }
@ -43,54 +46,56 @@ export class SessionRepository {
}); });
} }
public validateSessionUserAgent( public async validateSessionUserAgent(
sessionId: string, sessionId: string,
currentUserAgent: string currentUserAgent: string
): Promise<boolean> { ): Promise<boolean> {
return this.sessionRepository const session = await this.sessionRepository.findOne({
.findOne({ where: { sessionId: sessionId },
where: { sessionId }, select: ['userAgent'],
select: ['userAgent'], });
})
.then((session) => if (!session) {
session ? session.userAgent === currentUserAgent : false return false;
); }
return session.userAgent === currentUserAgent;
} }
public checkSessionLimit(userId: string): Promise<DeleteResult> { public async checkSessionLimit(userId: string): Promise<void> {
return this.sessionRepository const userSessions = await this.sessionRepository
.createQueryBuilder('session') .createQueryBuilder('session')
.leftJoinAndSelect('session.userCredentials', 'userCredentials') .leftJoinAndSelect('session.userCredentials', 'userCredentials')
.where('userCredentials.id = :userId', { userId }) .where('userCredentials.id = :userId', { userId })
.orderBy('session.expiresAt', 'ASC') .orderBy('session.expiresAt', 'ASC')
.getMany() .getMany();
.then((userSessions) => {
if (userSessions.length >= 5) { if (userSessions.length >= 5) {
return this.sessionRepository.delete(userSessions[0].id); await this.sessionRepository.delete(userSessions[0].id);
} }
});
} }
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> { public async invalidateAllSessionsForUser(userId: string): Promise<void> {
return this.sessionRepository.delete({ userCredentials: userId }); await this.sessionRepository.delete({ userCredentials: userId });
} }
public extendSessionExpiration(sessionId: string): Promise<Session> { public async extendSessionExpiration(sessionId: string): Promise<void> {
return this.sessionRepository const session = await this.sessionRepository.findOne({
.findOne({ where: { sessionId } }) where: { sessionId },
.then((session) => { });
if (session) {
session.expiresAt = new Date( if (session) {
session.expiresAt.setMinutes(session.expiresAt.getMinutes() + 30) session.expiresAt = new Date(
); session.expiresAt.setMinutes(session.expiresAt.getMinutes() + 30)
return this.sessionRepository.save(session); );
} await this.sessionRepository.save(session);
}); }
} }
public clearExpiredSessions(): Promise<DeleteResult> { // TODO Add cron job to clear expired sessions
public async clearExpiredSessions(): Promise<void> {
const now = new Date(); const now = new Date();
return this.sessionRepository.delete({ expiresAt: LessThan(now) }); await this.sessionRepository.delete({ expiresAt: LessThan(now) });
} }
} }

View File

@ -1,46 +1,52 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Response } from 'express'; import { Response } from 'express';
import { Session } from 'src/entities'; import { Session } from 'src/entities';
import { DeleteResult } from 'typeorm';
import { SessionRepository } from '../repositories/session.repository'; import { SessionRepository } from '../repositories/session.repository';
@Injectable() @Injectable()
export class SessionService { export class SessionService {
public constructor(private readonly sessionRepository: SessionRepository) {} public constructor(
@InjectRepository(Session)
private readonly sessionRepository: SessionRepository
) {}
public createSession(userId: string, userAgent: string): Promise<Session> { public async createSession(
return this.sessionRepository.createSession(userId, userAgent); userId: string,
userAgent: string
): Promise<Session> {
return await this.sessionRepository.createSession(userId, userAgent);
} }
public validateSessionUserAgent( public async validateSessionUserAgent(
sessionId: string, sessionId: string,
currentUserAgent: string currentUserAgent: string
): Promise<boolean> { ): Promise<boolean> {
return this.sessionRepository.validateSessionUserAgent( return await this.sessionRepository.validateSessionUserAgent(
sessionId, sessionId,
currentUserAgent currentUserAgent
); );
} }
public checkSessionLimit(userId: string): Promise<DeleteResult> { public async checkSessionLimit(userId: string): Promise<void> {
return this.sessionRepository.checkSessionLimit(userId); await this.sessionRepository.checkSessionLimit(userId);
} }
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> { public async invalidateAllSessionsForUser(userId: string): Promise<void> {
return this.sessionRepository.invalidateAllSessionsForUser(userId); await this.sessionRepository.invalidateAllSessionsForUser(userId);
} }
public clearExpiredSessions(): Promise<DeleteResult> { public async clearExpiredSessions(): Promise<void> {
return this.sessionRepository.clearExpiredSessions(); await this.sessionRepository.clearExpiredSessions();
} }
public extendSessionExpiration(sessionId: string): Promise<Session> { public async extendSessionExpiration(sessionId: string): Promise<void> {
return this.sessionRepository.extendSessionExpiration(sessionId); await this.sessionRepository.extendSessionExpiration(sessionId);
} }
public findSessionBySessionId(sessionId: string): Promise<Session> { public async findSessionBySessionId(sessionId: string): Promise<Session> {
return this.sessionRepository.findSessionBySessionId(sessionId); return await this.sessionRepository.findSessionBySessionId(sessionId);
} }
public attachSessionToResponse(response: Response, sessionId: string): void { public attachSessionToResponse(response: Response, sessionId: string): void {