Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions backend/src/shared/infra/http/middlewares/ensureAuthenticated.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Request, Response, NextFunction } from 'express';
import { verify } from 'jsonwebtoken';
import { UsersRepository } from '@modules/accounts/infra/typeorm/repositories/UsersRepository';
import { AppError } from '@errors/AppError';

interface IPayload {
sub: string;
}

export async function ensureAuthenticated(request: Request, response: Response, next: NextFunction) {
const authHeader = request.headers.authorization;

if (!authHeader) {
throw new AppError('Token missing');
}

const [, token] = authHeader.split(' ');

try {
const { sub: user_id } = verify(token, process.env.APP_JWT_SECRET || '') as IPayload;

const usersRepository = new UsersRepository();

const user = await usersRepository.findByID(user_id);

if (!user) {
throw new AppError('User does not exists');
}

request.user = {
id: user_id
}

next();
} catch {
throw new AppError('Invalid token!');
}
}
11 changes: 11 additions & 0 deletions backend/src/shared/infra/http/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Router } from 'express';
import { usersRoutes } from '@modules/accounts/infra/http/routes/users.routes';
import { authenticateRouter } from '@modules/accounts/infra/http/routes/authenticate.routes';
import { propertiesRoutes } from '@modules/properties/infra/http/routes/properties.routes';
const router = Router();

router.use('/users', usersRoutes);
router.use('/sessions', authenticateRouter);
router.use('/properties', propertiesRoutes);

export { router }