generated from OPCODE-Open-Spring-Fest/template
-
Notifications
You must be signed in to change notification settings - Fork 16
feat: session expiry feature implemented #51
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
Merged
04shubham7
merged 6 commits into
OPCODE-Open-Spring-Fest:main
from
anandshukla15:feature/session-expiry
Oct 29, 2025
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
22a5a87
feat: session expiry feature implemented
anandshukla15 7ebdd16
Merge branch 'main' into feature/session-expiry
anandshukla15 af96509
Update backend/src/middleware/authMiddleware.ts
anandshukla15 1bb1873
Update backend/src/models/sessionModel.ts
anandshukla15 140bb1a
clear conflict
anandshukla15 feaedf3
Merge branch 'main' into feature/session-expiry
anandshukla15 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,21 +1,49 @@ | ||
| import type { Request, Response, NextFunction } from "express"; | ||
| import jwt from "jsonwebtoken"; | ||
| import { Session } from "../models/sessionModel.js"; | ||
|
|
||
| interface AuthRequest extends Request { | ||
| userId?: string; | ||
| userId?: string; | ||
| } | ||
|
|
||
| export const protect = (req: AuthRequest, res: Response, next: NextFunction) => { | ||
| let token = req.headers.authorization?.split(" ")[1]; | ||
|
|
||
| if (!token) | ||
| return res.status(401).json({ success: false, message: "Not authorized, token missing" }); | ||
| export const protect = async (req: AuthRequest, res: Response, next: NextFunction) => { | ||
| try { | ||
| const token = req.headers.authorization?.split(" ")[1]; | ||
| if (!token) { | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: "Not authorized — token missing", | ||
| }); | ||
| } | ||
|
|
||
|
|
||
| const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { id: string; exp: number }; | ||
anandshukla15 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| try { | ||
| const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { id: string }; | ||
| req.userId = decoded.id; | ||
| next(); | ||
| } catch { | ||
| res.status(401).json({ success: false, message: "Invalid token" }); | ||
|
|
||
| const activeSession = await Session.findOne({ token }); | ||
| if (!activeSession) { | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: "Session expired or invalid", | ||
| }); | ||
| } | ||
|
|
||
|
|
||
| if (activeSession.expiresAt < new Date()) { | ||
| await Session.deleteOne({ token }); | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: "Session expired", | ||
| }); | ||
| } | ||
|
|
||
| req.userId = decoded.id; | ||
| next(); | ||
| } catch (error) { | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: "Invalid or expired token", | ||
| }); | ||
| } | ||
| }; | ||
This file contains hidden or 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,13 @@ | ||
| import mongoose from "mongoose"; | ||
|
|
||
| const sessionSchema = new mongoose.Schema({ | ||
| userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }, | ||
| token: { type: String, required: true }, | ||
| expiresAt: { type: Date, required: true }, | ||
| createdAt: { type: Date, default: Date.now }, | ||
| }); | ||
|
|
||
|
|
||
| sessionSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); | ||
|
|
||
anandshukla15 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| export const Session = mongoose.model("Session", sessionSchema); | ||
This file contains hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,5 +1,9 @@ | ||
| import jwt from "jsonwebtoken"; | ||
|
|
||
| export const generateToken = (id: string) => { | ||
| return jwt.sign({ id }, process.env.JWT_SECRET as string, { expiresIn: "7d" }); | ||
| export const generateToken = (userId: string) => { | ||
| const expiresIn = "7d"; | ||
| const token = jwt.sign({ id: userId }, process.env.JWT_SECRET as string, { | ||
| expiresIn, | ||
| }); | ||
| return token; | ||
| }; |
This file contains hidden or 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 |
|---|---|---|
| @@ -1 +1 @@ | ||
| {"root":["./src/app.ts","./src/server.ts","./src/controllers/authcontroller.ts","./src/controllers/healthcontroller.ts","./src/controllers/roomcontroller.ts","./src/middleware/authmiddleware.ts","./src/middleware/errorhandler.ts","./src/models/chatmessagemodel.ts","./src/models/roommodel.ts","./src/models/usermodel.ts","./src/routes/authroutes.ts","./src/routes/healthroutes.ts","./src/routes/roomroutes.ts","./src/utils/generatetoken.ts","./src/utils/passport.ts","./src/utils/validateinputs.ts"],"version":"5.9.3"} | ||
| {"root":["./src/app.ts","./src/server.ts","./src/controllers/authcontroller.ts","./src/controllers/healthcontroller.ts","./src/controllers/roomcontroller.ts","./src/middleware/authmiddleware.ts","./src/middleware/errorhandler.ts","./src/models/chatmessagemodel.ts","./src/models/roommodel.ts","./src/models/sessionmodel.ts","./src/models/usermodel.ts","./src/routes/authroutes.ts","./src/routes/healthroutes.ts","./src/routes/roomroutes.ts","./src/utils/generatetoken.ts","./src/utils/passport.ts","./src/utils/validateinputs.ts"],"version":"5.9.3"} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.