Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into feat_Indexroutes
Browse files Browse the repository at this point in the history
  • Loading branch information
BraCR10 committed Dec 22, 2024
2 parents f5dc225 + 5958dd8 commit d3368d4
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 7 deletions.
23 changes: 23 additions & 0 deletions src/entities/Session.ts
Original file line number Diff line number Diff line change
@@ -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
}
41 changes: 41 additions & 0 deletions src/middleware/session.middleware.ts
Original file line number Diff line number Diff line change
@@ -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<void> => {
// 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' });
}
};
17 changes: 10 additions & 7 deletions src/routes/UserRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
34 changes: 34 additions & 0 deletions src/services/SessionService.ts
Original file line number Diff line number Diff line change
@@ -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<Session>;

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<Session> {
// 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<Session | null> {
// 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;
}
}

0 comments on commit d3368d4

Please sign in to comment.