Skip to content

Commit

Permalink
feat: validate token
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiobrasileiroo committed Oct 13, 2024
1 parent bad5786 commit abc3282
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
1 change: 0 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
Expand Down
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import productRoutes from './routes/productRoutes.js'
import createUserRouter from './routes/createUserRoutes.js'
import createUnitRouter from './routes/createUnitRoutes.js'
import proposalRoutes from './routes/proposalRoutes.js'
import validateToken from './routes/validateToken.js'

const app = express()

Expand All @@ -27,5 +28,6 @@ app.use('/auth', authRoutes) // Adicione '/api' como prefixo para as rotas de au
app.use('/api', createUserRouter) // Adicione '/api' como prefixo para as rotas de autenticação
app.use('/api', createUnitRouter) // Adicione '/api' como prefixo para as rotas de autenticação
app.use('/proposal', proposalRoutes) // Adicione '/api' como prefixo para as rotas de autenticação
app.use('/auth', validateToken) // Adicione '/api' como prefixo para as rotas de autenticação

export default app
31 changes: 31 additions & 0 deletions src/routes/validateToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import express from 'express';
import jwt from 'jsonwebtoken';
import type { Request, Response } from 'express';
import { PrismaClient, UserRole } from '@prisma/client'; // Optional: for user-related info (if needed)

const validateToken = express.Router();
const prisma = new PrismaClient();

// Route for validating JWT tokens
validateToken.post('/validate-token', (req: Request, res: Response) => {
const token = req.body.token;

if (!token) {
return res.status(400).json({ valid: false, message: 'Token is missing' });
}

// Verify the token using the JWT secret
jwt.verify(token, process.env.JWT_SECRET as string, (err: any, decoded: any) => {
if (err) {
return res.status(401).json({ valid: false, message: 'Invalid token' });
}

// Optionally, you could retrieve user information from the database using `decoded.id`
// Example: const user = await prisma.user.findUnique({ where: { id: decoded.id } });

// If token is valid, send back valid: true
res.status(200).json({ valid: true, decoded });
});
});

export default validateToken;

0 comments on commit abc3282

Please sign in to comment.