Token Refresh
This commit is contained in:
parent
8d2469ddb6
commit
253ca97fe8
|
|
@ -1,6 +1,7 @@
|
|||
import 'dotenv/config';
|
||||
import express from 'express';
|
||||
import express, { Request, Response, NextFunction } from 'express';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import path from 'path';
|
||||
import authRouter from './routes/auth';
|
||||
import adminRouter from './routes/admin';
|
||||
|
|
@ -10,6 +11,31 @@ const app = express();
|
|||
app.set( 'trust proxy', 1 );
|
||||
app.use( express.json() );
|
||||
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( '/api/auth', authRouter );
|
||||
|
|
|
|||
Loading…
Reference in New Issue