Token Refresh

This commit is contained in:
Rokojori 2026-07-16 19:07:24 +02:00
parent 8d2469ddb6
commit 253ca97fe8
1 changed files with 27 additions and 1 deletions

View File

@ -1,6 +1,7 @@
import 'dotenv/config'; import 'dotenv/config';
import express from 'express'; import express, { Request, Response, NextFunction } from 'express';
import cookieParser from 'cookie-parser'; import cookieParser from 'cookie-parser';
import jwt from 'jsonwebtoken';
import path from 'path'; import path from 'path';
import authRouter from './routes/auth'; import authRouter from './routes/auth';
import adminRouter from './routes/admin'; import adminRouter from './routes/admin';
@ -10,6 +11,31 @@ const app = express();
app.set( 'trust proxy', 1 ); app.set( 'trust proxy', 1 );
app.use( express.json() ); app.use( express.json() );
app.use( cookieParser() ); app.use( cookieParser() );
app.use( ( req: Request, res: Response, next: NextFunction ) =>
{
if ( req.path.startsWith( '/api/' ) ) { next(); return; }
const token = req.cookies?.accessToken as string | undefined;
if ( !token ) { next(); return; }
try
{
jwt.verify( token, process.env.JWT_SECRET ?? '' );
next();
}
catch ( err )
{
if ( err instanceof jwt.TokenExpiredError )
{
const redirect = encodeURIComponent( req.protocol + '://' + req.get( 'host' ) + req.originalUrl );
res.redirect( `/api/auth/refresh-session?redirect=${redirect}` );
}
else
{
next();
}
}
} );
app.use( express.static( path.join( __dirname, '..', '..', 'build', 'app' ) ) ); app.use( express.static( path.join( __dirname, '..', '..', 'build', 'app' ) ) );
app.use( '/api/auth', authRouter ); app.use( '/api/auth', authRouter );