51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
import 'dotenv/config';
|
|
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';
|
|
|
|
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 );
|
|
app.use( '/api/admin', adminRouter );
|
|
|
|
app.get( '/', ( _req, res ) =>
|
|
{
|
|
res.redirect( '/login.html' );
|
|
} );
|
|
|
|
const PORT = process.env.PORT ? Number( process.env.PORT ) : 3001;
|
|
app.listen( PORT, () => console.log( `rokojori-auth running on http://localhost:${PORT}` ) );
|