fix cors for postman + small tidy up #10
|
@ -3,6 +3,7 @@ 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';
|
||||||
|
@ -34,8 +35,8 @@ export class AppModule {
|
||||||
.apply(
|
.apply(
|
||||||
CspMiddleware,
|
CspMiddleware,
|
||||||
SecurityHeadersMiddleware,
|
SecurityHeadersMiddleware,
|
||||||
HttpsRedirectMiddleware
|
HttpsRedirectMiddleware,
|
||||||
//CorsMiddleware
|
CorsMiddleware
|
||||||
)
|
)
|
||||||
.forRoutes({ path: '*', method: RequestMethod.ALL });
|
.forRoutes({ path: '*', method: RequestMethod.ALL });
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,10 +8,13 @@ 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 allowedOrigin = this.configService.get<string>('CORS_ALLOW_ORIGIN');
|
const allowedOrigins = this.configService
|
||||||
|
.get<string>('CORS_ALLOW_ORIGIN')
|
||||||
|
.split(',');
|
||||||
|
const requestOrigin = req.headers.origin;
|
||||||
|
|
||||||
if (req.headers.origin === allowedOrigin) {
|
if (!requestOrigin || allowedOrigins.includes(requestOrigin)) {
|
||||||
res.header('Access-Control-Allow-Origin', allowedOrigin);
|
res.header('Access-Control-Allow-Origin', requestOrigin || '*');
|
||||||
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')
|
||||||
|
|
|
@ -2,24 +2,22 @@ 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 { LessThan, Repository } from 'typeorm';
|
import { DeleteResult, 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)
|
@InjectRepository(Session) private sessionRepository: Repository<Session>
|
||||||
private sessionRepository: Repository<Session>
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async createSession(
|
public createSession(userId: string, userAgent: string): Promise<Session> {
|
||||||
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,
|
||||||
|
@ -27,13 +25,12 @@ export class SessionRepository {
|
||||||
userAgent,
|
userAgent,
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.sessionRepository.save(session);
|
return this.sessionRepository.save(session);
|
||||||
return session;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async findSessionBySessionId(sessionId: string): Promise<Session> {
|
public findSessionBySessionId(sessionId: string): Promise<Session> {
|
||||||
return await this.sessionRepository.findOne({
|
return this.sessionRepository.findOne({
|
||||||
where: { sessionId: sessionId },
|
where: { sessionId },
|
||||||
relations: ['userCredentials'],
|
relations: ['userCredentials'],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -46,56 +43,54 @@ export class SessionRepository {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async validateSessionUserAgent(
|
public validateSessionUserAgent(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
currentUserAgent: string
|
currentUserAgent: string
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const session = await this.sessionRepository.findOne({
|
return this.sessionRepository
|
||||||
where: { sessionId: sessionId },
|
.findOne({
|
||||||
select: ['userAgent'],
|
where: { sessionId },
|
||||||
});
|
select: ['userAgent'],
|
||||||
|
})
|
||||||
if (!session) {
|
.then((session) =>
|
||||||
return false;
|
session ? session.userAgent === currentUserAgent : false
|
||||||
}
|
);
|
||||||
|
|
||||||
return session.userAgent === currentUserAgent;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async checkSessionLimit(userId: string): Promise<void> {
|
public checkSessionLimit(userId: string): Promise<DeleteResult> {
|
||||||
const userSessions = await this.sessionRepository
|
return 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) {
|
||||||
await this.sessionRepository.delete(userSessions[0].id);
|
return this.sessionRepository.delete(userSessions[0].id);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async invalidateAllSessionsForUser(userId: string): Promise<void> {
|
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> {
|
||||||
await this.sessionRepository.delete({ userCredentials: userId });
|
return this.sessionRepository.delete({ userCredentials: userId });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async extendSessionExpiration(sessionId: string): Promise<void> {
|
public extendSessionExpiration(sessionId: string): Promise<Session> {
|
||||||
const session = await this.sessionRepository.findOne({
|
return this.sessionRepository
|
||||||
where: { sessionId },
|
.findOne({ where: { sessionId } })
|
||||||
});
|
.then((session) => {
|
||||||
|
if (session) {
|
||||||
if (session) {
|
session.expiresAt = new Date(
|
||||||
session.expiresAt = new Date(
|
session.expiresAt.setMinutes(session.expiresAt.getMinutes() + 30)
|
||||||
session.expiresAt.setMinutes(session.expiresAt.getMinutes() + 30)
|
);
|
||||||
);
|
return this.sessionRepository.save(session);
|
||||||
await this.sessionRepository.save(session);
|
}
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO Add cron job to clear expired sessions
|
public clearExpiredSessions(): Promise<DeleteResult> {
|
||||||
public async clearExpiredSessions(): Promise<void> {
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
|
||||||
await this.sessionRepository.delete({ expiresAt: LessThan(now) });
|
return this.sessionRepository.delete({ expiresAt: LessThan(now) });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,52 +1,46 @@
|
||||||
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(
|
public constructor(private readonly sessionRepository: SessionRepository) {}
|
||||||
@InjectRepository(Session)
|
|
||||||
private readonly sessionRepository: SessionRepository
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public async createSession(
|
public createSession(userId: string, userAgent: string): Promise<Session> {
|
||||||
userId: string,
|
return this.sessionRepository.createSession(userId, userAgent);
|
||||||
userAgent: string
|
|
||||||
): Promise<Session> {
|
|
||||||
return await this.sessionRepository.createSession(userId, userAgent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async validateSessionUserAgent(
|
public validateSessionUserAgent(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
currentUserAgent: string
|
currentUserAgent: string
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
return await this.sessionRepository.validateSessionUserAgent(
|
return this.sessionRepository.validateSessionUserAgent(
|
||||||
sessionId,
|
sessionId,
|
||||||
currentUserAgent
|
currentUserAgent
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async checkSessionLimit(userId: string): Promise<void> {
|
public checkSessionLimit(userId: string): Promise<DeleteResult> {
|
||||||
await this.sessionRepository.checkSessionLimit(userId);
|
return this.sessionRepository.checkSessionLimit(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async invalidateAllSessionsForUser(userId: string): Promise<void> {
|
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> {
|
||||||
await this.sessionRepository.invalidateAllSessionsForUser(userId);
|
return this.sessionRepository.invalidateAllSessionsForUser(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async clearExpiredSessions(): Promise<void> {
|
public clearExpiredSessions(): Promise<DeleteResult> {
|
||||||
await this.sessionRepository.clearExpiredSessions();
|
return this.sessionRepository.clearExpiredSessions();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async extendSessionExpiration(sessionId: string): Promise<void> {
|
public extendSessionExpiration(sessionId: string): Promise<Session> {
|
||||||
await this.sessionRepository.extendSessionExpiration(sessionId);
|
return this.sessionRepository.extendSessionExpiration(sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async findSessionBySessionId(sessionId: string): Promise<Session> {
|
public findSessionBySessionId(sessionId: string): Promise<Session> {
|
||||||
return await this.sessionRepository.findSessionBySessionId(sessionId);
|
return this.sessionRepository.findSessionBySessionId(sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public attachSessionToResponse(response: Response, sessionId: string): void {
|
public attachSessionToResponse(response: Response, sessionId: string): void {
|
||||||
|
|
Loading…
Reference in New Issue