fix cors for postman + small tidy up
This commit is contained in:
parent
46f69e1c53
commit
d2d3b69baa
|
@ -3,6 +3,7 @@ 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';
|
||||
|
@ -34,8 +35,8 @@ export class AppModule {
|
|||
.apply(
|
||||
CspMiddleware,
|
||||
SecurityHeadersMiddleware,
|
||||
HttpsRedirectMiddleware
|
||||
//CorsMiddleware
|
||||
HttpsRedirectMiddleware,
|
||||
CorsMiddleware
|
||||
)
|
||||
.forRoutes({ path: '*', method: RequestMethod.ALL });
|
||||
}
|
||||
|
|
|
@ -8,10 +8,13 @@ export class CorsMiddleware implements NestMiddleware {
|
|||
|
||||
public use(req: Request, res: Response, next: NextFunction): void {
|
||||
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) {
|
||||
res.header('Access-Control-Allow-Origin', allowedOrigin);
|
||||
if (!requestOrigin || allowedOrigins.includes(requestOrigin)) {
|
||||
res.header('Access-Control-Allow-Origin', requestOrigin || '*');
|
||||
res.header(
|
||||
'Access-Control-Allow-Methods',
|
||||
this.configService.get<string>('CORS_ALLOW_METHODS')
|
||||
|
|
|
@ -2,24 +2,22 @@ import { Injectable } from '@nestjs/common';
|
|||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Response } from 'express';
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class SessionRepository {
|
||||
public constructor(
|
||||
@InjectRepository(Session)
|
||||
private sessionRepository: Repository<Session>
|
||||
@InjectRepository(Session) private sessionRepository: Repository<Session>
|
||||
) {}
|
||||
|
||||
public async createSession(
|
||||
userId: string,
|
||||
userAgent: string
|
||||
): Promise<Session> {
|
||||
public 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,
|
||||
|
@ -27,13 +25,12 @@ export class SessionRepository {
|
|||
userAgent,
|
||||
});
|
||||
|
||||
await this.sessionRepository.save(session);
|
||||
return session;
|
||||
return this.sessionRepository.save(session);
|
||||
}
|
||||
|
||||
public async findSessionBySessionId(sessionId: string): Promise<Session> {
|
||||
return await this.sessionRepository.findOne({
|
||||
where: { sessionId: sessionId },
|
||||
public findSessionBySessionId(sessionId: string): Promise<Session> {
|
||||
return this.sessionRepository.findOne({
|
||||
where: { sessionId },
|
||||
relations: ['userCredentials'],
|
||||
});
|
||||
}
|
||||
|
@ -46,56 +43,54 @@ export class SessionRepository {
|
|||
});
|
||||
}
|
||||
|
||||
public async validateSessionUserAgent(
|
||||
public validateSessionUserAgent(
|
||||
sessionId: string,
|
||||
currentUserAgent: string
|
||||
): Promise<boolean> {
|
||||
const session = await this.sessionRepository.findOne({
|
||||
where: { sessionId: sessionId },
|
||||
return this.sessionRepository
|
||||
.findOne({
|
||||
where: { sessionId },
|
||||
select: ['userAgent'],
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
return false;
|
||||
})
|
||||
.then((session) =>
|
||||
session ? session.userAgent === currentUserAgent : false
|
||||
);
|
||||
}
|
||||
|
||||
return session.userAgent === currentUserAgent;
|
||||
}
|
||||
|
||||
public async checkSessionLimit(userId: string): Promise<void> {
|
||||
const userSessions = await this.sessionRepository
|
||||
public checkSessionLimit(userId: string): Promise<DeleteResult> {
|
||||
return this.sessionRepository
|
||||
.createQueryBuilder('session')
|
||||
.leftJoinAndSelect('session.userCredentials', 'userCredentials')
|
||||
.where('userCredentials.id = :userId', { userId })
|
||||
.orderBy('session.expiresAt', 'ASC')
|
||||
.getMany();
|
||||
|
||||
.getMany()
|
||||
.then((userSessions) => {
|
||||
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> {
|
||||
await this.sessionRepository.delete({ userCredentials: userId });
|
||||
}
|
||||
|
||||
public async extendSessionExpiration(sessionId: string): Promise<void> {
|
||||
const session = await this.sessionRepository.findOne({
|
||||
where: { sessionId },
|
||||
});
|
||||
}
|
||||
|
||||
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> {
|
||||
return 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)
|
||||
);
|
||||
await this.sessionRepository.save(session);
|
||||
return this.sessionRepository.save(session);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// TODO Add cron job to clear expired sessions
|
||||
public async clearExpiredSessions(): Promise<void> {
|
||||
public clearExpiredSessions(): Promise<DeleteResult> {
|
||||
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 { 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(
|
||||
@InjectRepository(Session)
|
||||
private readonly sessionRepository: SessionRepository
|
||||
) {}
|
||||
public constructor(private readonly sessionRepository: SessionRepository) {}
|
||||
|
||||
public async createSession(
|
||||
userId: string,
|
||||
userAgent: string
|
||||
): Promise<Session> {
|
||||
return await this.sessionRepository.createSession(userId, userAgent);
|
||||
public createSession(userId: string, userAgent: string): Promise<Session> {
|
||||
return this.sessionRepository.createSession(userId, userAgent);
|
||||
}
|
||||
|
||||
public async validateSessionUserAgent(
|
||||
public validateSessionUserAgent(
|
||||
sessionId: string,
|
||||
currentUserAgent: string
|
||||
): Promise<boolean> {
|
||||
return await this.sessionRepository.validateSessionUserAgent(
|
||||
return this.sessionRepository.validateSessionUserAgent(
|
||||
sessionId,
|
||||
currentUserAgent
|
||||
);
|
||||
}
|
||||
|
||||
public async checkSessionLimit(userId: string): Promise<void> {
|
||||
await this.sessionRepository.checkSessionLimit(userId);
|
||||
public checkSessionLimit(userId: string): Promise<DeleteResult> {
|
||||
return this.sessionRepository.checkSessionLimit(userId);
|
||||
}
|
||||
|
||||
public async invalidateAllSessionsForUser(userId: string): Promise<void> {
|
||||
await this.sessionRepository.invalidateAllSessionsForUser(userId);
|
||||
public invalidateAllSessionsForUser(userId: string): Promise<DeleteResult> {
|
||||
return this.sessionRepository.invalidateAllSessionsForUser(userId);
|
||||
}
|
||||
|
||||
public async clearExpiredSessions(): Promise<void> {
|
||||
await this.sessionRepository.clearExpiredSessions();
|
||||
public clearExpiredSessions(): Promise<DeleteResult> {
|
||||
return this.sessionRepository.clearExpiredSessions();
|
||||
}
|
||||
|
||||
public async extendSessionExpiration(sessionId: string): Promise<void> {
|
||||
await this.sessionRepository.extendSessionExpiration(sessionId);
|
||||
public extendSessionExpiration(sessionId: string): Promise<Session> {
|
||||
return this.sessionRepository.extendSessionExpiration(sessionId);
|
||||
}
|
||||
|
||||
public async findSessionBySessionId(sessionId: string): Promise<Session> {
|
||||
return await this.sessionRepository.findSessionBySessionId(sessionId);
|
||||
public findSessionBySessionId(sessionId: string): Promise<Session> {
|
||||
return this.sessionRepository.findSessionBySessionId(sessionId);
|
||||
}
|
||||
|
||||
public attachSessionToResponse(response: Response, sessionId: string): void {
|
||||
|
|
Loading…
Reference in New Issue