-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge remote-tracking branch 'origin/main' into feat_Indexroutes
- Loading branch information
Showing
4 changed files
with
108 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' }); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |