Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add session management #23

Merged
merged 4 commits into from
Dec 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}
Loading