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 { AppService } from './app.service';
import { CorsMiddleware } from './middleware/cors-middleware/cors.middlware';
import { CspMiddleware } from './middleware/csp-middleware/csp.middleware';
import { HttpsRedirectMiddleware } from './middleware/https-middlware/https-redirect.middleware';
import { SecurityHeadersMiddleware } from './middleware/security-middleware/security.middleware';
@ -35,8 +34,8 @@ export class AppModule {
.apply(
CspMiddleware,
SecurityHeadersMiddleware,
HttpsRedirectMiddleware,
CorsMiddleware
HttpsRedirectMiddleware
//CorsMiddleware
)
.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 {
if (this.configService.get<string>('NODE_ENV') === 'development') {
const allowedOrigins = this.configService
.get<string>('CORS_ALLOW_ORIGIN')
.split(',');
const requestOrigin = req.headers.origin;
const allowedOrigin = this.configService.get<string>('CORS_ALLOW_ORIGIN');
if (!requestOrigin || allowedOrigins.includes(requestOrigin)) {
res.header('Access-Control-Allow-Origin', requestOrigin || '*');
if (req.headers.origin === allowedOrigin) {
res.header('Access-Control-Allow-Origin', allowedOrigin);
res.header(
'Access-Control-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 { Response } from 'express';
import { Session } from 'src/entities';
import { DeleteResult, Repository } from 'typeorm';
import { LessThan } from 'typeorm';
import { LessThan, Repository } from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
@Injectable()
export class SessionRepository {
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 expirationDate = new Date();
expirationDate.setHours(expirationDate.getHours() + 1);
const session = this.sessionRepository.create({
userCredentials: userId,
sessionId,
@ -25,12 +27,13 @@ export class SessionRepository {
userAgent,
});
return this.sessionRepository.save(session);
await this.sessionRepository.save(session);
return session;
}
public findSessionBySessionId(sessionId: string): Promise<Session> {
return this.sessionRepository.findOne({
where: { sessionId },
public async findSessionBySessionId(sessionId: string): Promise<Session> {
return await this.sessionRepository.findOne({
where: { sessionId: sessionId },
relations: ['userCredentials'],
});
}
@ -43,54 +46,56 @@ export class SessionRepository {
});
}
public validateSessionUserAgent(
public async validateSessionUserAgent(
sessionId: string,
currentUserAgent: string
): Promise<boolean> {
return this.sessionRepository
.findOne({
where: { sessionId },
select: ['userAgent'],
})
.then((session) =>
session ? session.userAgent === currentUserAgent : false
);
const session = await this.sessionRepository.findOne({
where: { sessionId: sessionId },
select: ['userAgent'],
});
if (!session) {
return false;
}
return session.userAgent === currentUserAgent;
}
public checkSessionLimit(userId: string): Promise<DeleteResult> {
return this.sessionRepository
public async checkSessionLimit(userId: string): Promise<void> {
const userSessions = await this.sessionRepository
.createQueryBuilder('session')
.leftJoinAndSelect('session.userCredentials', 'userCredentials')
.where('userCredentials.id = :userId', { userId })
.orderBy('session.expiresAt', 'ASC')
.getMany()
.then((userSessions) => {
if (userSessions.length >= 5) {
return this.sessionRepository.delete(userSessions[0].id);
}
});
.getMany();
if (userSessions.length >= 5) {
await this.sessionRepository.delete(userSessions[0].id);
}
}
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> {
return this.sessionRepository.delete({ userCredentials: userId });
public async invalidateAllSessionsForUser(userId: string): Promise<void> {
await this.sessionRepository.delete({ userCredentials: userId });
}
public extendSessionExpiration(sessionId: string): Promise<Session> {
return this.sessionRepository
.findOne({ where: { sessionId } })
.then((session) => {
if (session) {
session.expiresAt = new Date(
session.expiresAt.setMinutes(session.expiresAt.getMinutes() + 30)
);
return this.sessionRepository.save(session);
}
});
public async extendSessionExpiration(sessionId: string): Promise<void> {
const session = await this.sessionRepository.findOne({
where: { sessionId },
});
if (session) {
session.expiresAt = new Date(
session.expiresAt.setMinutes(session.expiresAt.getMinutes() + 30)
);
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();
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 { InjectRepository } from '@nestjs/typeorm';
import { Response } from 'express';
import { Session } from 'src/entities';
import { DeleteResult } from 'typeorm';
import { SessionRepository } from '../repositories/session.repository';
@Injectable()
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> {
return this.sessionRepository.createSession(userId, userAgent);
public async createSession(
userId: string,
userAgent: string
): Promise<Session> {
return await this.sessionRepository.createSession(userId, userAgent);
}
public validateSessionUserAgent(
public async validateSessionUserAgent(
sessionId: string,
currentUserAgent: string
): Promise<boolean> {
return this.sessionRepository.validateSessionUserAgent(
return await this.sessionRepository.validateSessionUserAgent(
sessionId,
currentUserAgent
);
}
public checkSessionLimit(userId: string): Promise<DeleteResult> {
return this.sessionRepository.checkSessionLimit(userId);
public async checkSessionLimit(userId: string): Promise<void> {
await this.sessionRepository.checkSessionLimit(userId);
}
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> {
return this.sessionRepository.invalidateAllSessionsForUser(userId);
public async invalidateAllSessionsForUser(userId: string): Promise<void> {
await this.sessionRepository.invalidateAllSessionsForUser(userId);
}
public clearExpiredSessions(): Promise<DeleteResult> {
return this.sessionRepository.clearExpiredSessions();
public async clearExpiredSessions(): Promise<void> {
await this.sessionRepository.clearExpiredSessions();
}
public extendSessionExpiration(sessionId: string): Promise<Session> {
return this.sessionRepository.extendSessionExpiration(sessionId);
public async extendSessionExpiration(sessionId: string): Promise<void> {
await this.sessionRepository.extendSessionExpiration(sessionId);
}
public findSessionBySessionId(sessionId: string): Promise<Session> {
return this.sessionRepository.findSessionBySessionId(sessionId);
public async findSessionBySessionId(sessionId: string): Promise<Session> {
return await this.sessionRepository.findSessionBySessionId(sessionId);
}
public attachSessionToResponse(response: Response, sessionId: string): void {