From 0b36f3f1069943a2d087f3474baa1ad8837ad65e Mon Sep 17 00:00:00 2001 From: JosephPDF Date: Tue, 17 Dec 2024 14:28:12 -0600 Subject: [PATCH 1/4] Add file Session.ts --- src/entities/Session.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/entities/Session.ts diff --git a/src/entities/Session.ts b/src/entities/Session.ts new file mode 100644 index 0000000..52b1d7d --- /dev/null +++ b/src/entities/Session.ts @@ -0,0 +1,23 @@ +import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, CreateDateColumn, UpdateDateColumn } from 'typeorm'; +import { User } from './User'; + +@Entity('sessions') +export class Session { + @PrimaryGeneratedColumn() + id: number; // Unique identifier for the session + + @ManyToOne(() => User) + user: User; // Reference to the user associated with the session + + @Column({ unique: true }) + token: string; // Unique token for the session + + @Column() + expiresAt: Date; // Expiration date of the session + + @CreateDateColumn() + createdAt: Date; // Timestamp when the session was created + + @UpdateDateColumn() + updatedAt: Date; // Timestamp when the session was last updated +} From 8c9a51ba540f99d3bdb0a9765262299e625980d3 Mon Sep 17 00:00:00 2001 From: JosephPDF Date: Tue, 17 Dec 2024 14:37:27 -0600 Subject: [PATCH 2/4] Add file SessionService.ts --- src/services/SessionService.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/services/SessionService.ts diff --git a/src/services/SessionService.ts b/src/services/SessionService.ts new file mode 100644 index 0000000..1608f80 --- /dev/null +++ b/src/services/SessionService.ts @@ -0,0 +1,34 @@ +import { Repository } from "typeorm"; +import { Session } from "../entities/Session"; +import { User } from "../entities/User"; +import { DataSource } from "typeorm"; + +export class SessionService { + // Repository for managing session entities + private sessionRepository: Repository; + + constructor(dataSource: DataSource) { + // Initialize the session repository with the provided data source + this.sessionRepository = dataSource.getRepository(Session); + } + + // Create a new session for a user + async createSession(user: User, token: string, expiresAt: Date): Promise { + // Create a session object + const session = this.sessionRepository.create({ user, token, expiresAt }); + // Save the session to the database + return await this.sessionRepository.save(session); + } + + // Validate an existing session using the token + async validateSession(token: string): Promise { + // Find the session by token + const session = await this.sessionRepository.findOne({ where: { token } }); + // Check if the session is valid (not expired) + if (session && session.expiresAt > new Date()) { + return session; + } + // Return null if the session is invalid or not found + return null; + } +} \ No newline at end of file From c23b161918033d58fb5971aadc0ca09a4e162708 Mon Sep 17 00:00:00 2001 From: JosephPDF Date: Tue, 17 Dec 2024 14:38:16 -0600 Subject: [PATCH 3/4] Add file session.middleware.ts --- src/middleware/session.middleware.ts | 41 ++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/middleware/session.middleware.ts diff --git a/src/middleware/session.middleware.ts b/src/middleware/session.middleware.ts new file mode 100644 index 0000000..d505206 --- /dev/null +++ b/src/middleware/session.middleware.ts @@ -0,0 +1,41 @@ +import { Request, Response, NextFunction } from 'express'; +import { SessionService } from '../services/SessionService'; +import AppDataSource from '../config/ormconfig'; + +interface AuthenticatedRequest extends Request { + user?: { id: number; role: string }; +} + +// Middleware function to handle session validation +export const sessionMiddleware = async ( + req: AuthenticatedRequest, + res: Response, + next: NextFunction +): Promise => { + // Extracting the token from the authorization header + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + // Responding with an error if the token is missing + res.status(401).json({ message: 'Authentication token is missing' }); + return; + } + + try { + // Creating an instance of SessionService to validate the session + const sessionService = new SessionService(AppDataSource); + const session = await sessionService.validateSession(token); + + if (!session) { + // Responding with an error if the session is invalid or expired + res.status(401).json({ message: 'Session expired or invalid' }); + return; + } + + // Attaching user information to the request object + req.user = { id: session.user.id, role: session.user.role }; + next(); // Proceeding to the next middleware + } catch (error) { + // Handling any internal server errors + res.status(500).json({ message: 'Internal server error' }); + } +}; \ No newline at end of file From 5bf92e41cbc0aa5a11d95c665d7e4f322737d53d Mon Sep 17 00:00:00 2001 From: JosephPDF Date: Tue, 17 Dec 2024 14:39:04 -0600 Subject: [PATCH 4/4] Update file UserRoutes.ts --- src/routes/UserRoutes.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/routes/UserRoutes.ts b/src/routes/UserRoutes.ts index c890001..d8f249e 100644 --- a/src/routes/UserRoutes.ts +++ b/src/routes/UserRoutes.ts @@ -2,16 +2,19 @@ import { Router } from 'express'; import { createUser, deleteUser, getAllUsers, getUser, updateUser } from '../controllers/UserController'; import { validationMiddleware } from '../middleware/userValidation.middleware'; import { CreateUserDto, UpdateUserDto } from '../dtos/UserDTO'; - - +import { sessionMiddleware } from '../middleware/session.middleware'; const router = Router(); -router.get('/', getAllUsers); +// Route to get all users +router.get('/', sessionMiddleware, getAllUsers); +// Route to create a new user with validation router.post('/create', validationMiddleware(CreateUserDto), createUser); -router.get('/show/:id', getUser); -router.put('/update/:id',validationMiddleware(UpdateUserDto), updateUser); -router.delete('/delete/:id', deleteUser); - +// Route to get a specific user by ID +router.get('/show/:id', sessionMiddleware, getUser); +// Route to update a user by ID with validation +router.put('/update/:id', sessionMiddleware, validationMiddleware(UpdateUserDto), updateUser); +// Route to delete a user by ID +router.delete('/delete/:id', sessionMiddleware, deleteUser); export default router;