Skip to content

Commit

Permalink
feat: redirect to requested path after login
Browse files Browse the repository at this point in the history
  • Loading branch information
FreekBes committed Jun 7, 2024
1 parent 78d45b8 commit 3245ac2
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/handlers/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import express from 'express';
import { Request, Response, NextFunction } from "express";
import { IntraUser } from "../intra/oauth";
import { CustomSessionData } from "./session";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();


const checkIfAuthenticated = function(req: Request, res: Response, next: NextFunction) {
if (req.path.startsWith('/login') || req.path.startsWith('/logout') || res.statusCode === 503) {
return next();
}
if (req.isAuthenticated()) {
return next();
}
// Store the path the user was trying to access
(req.session as CustomSessionData).returnTo = req.originalUrl;
return res.redirect('/login');
};

Expand Down
5 changes: 5 additions & 0 deletions src/handlers/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { SessionData } from "express-session";

export interface CustomSessionData extends SessionData {
returnTo?: string;
}
7 changes: 7 additions & 0 deletions src/routes/login.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Express } from 'express';
import passport from 'passport';
import { IntraUser } from '../intra/oauth';
import { CustomSessionData } from '../handlers/session';

export const setupLoginRoutes = function(app: Express): void {
app.get('/login', (req, res) => {
Expand All @@ -23,6 +24,12 @@ export const setupLoginRoutes = function(app: Express): void {
if (err) {
console.error('Failed to save session:', err);
}
// Check if there was a path the user was trying to access
const returnTo = (req.session as CustomSessionData).returnTo;
if (returnTo) {
delete (req.session as CustomSessionData).returnTo;
return res.redirect(returnTo);
}
res.redirect('/');
});
});
Expand Down

0 comments on commit 3245ac2

Please sign in to comment.