Skip to content

Commit 02895a0

Browse files
committed
refactor: implement auth middleware
1 parent bc03a0c commit 02895a0

File tree

10 files changed

+90
-15
lines changed

10 files changed

+90
-15
lines changed

src/common/middlewares/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './is-authenticated.middleware'
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { NextFunction, Request, Response } from 'express'
2+
import jwt from 'jsonwebtoken'
3+
4+
export interface AuthRequest extends Request {
5+
user?: object
6+
token?: string
7+
}
8+
9+
export function isAuthenticated(
10+
req: AuthRequest,
11+
res: Response,
12+
next: NextFunction,
13+
) {
14+
const authHeader = req.headers['authorization']
15+
16+
if (!authHeader) {
17+
return res.status(401).json({
18+
success: false,
19+
error: {
20+
message: 'Auth headers not provided in the request.',
21+
},
22+
})
23+
}
24+
25+
if (!authHeader.startsWith('Bearer')) {
26+
return res.status(401).json({
27+
success: false,
28+
error: {
29+
message: 'Invalid auth mechanism.',
30+
},
31+
})
32+
}
33+
34+
const token = authHeader.split(' ')[1]
35+
36+
if (!token) {
37+
return res.status(401).json({
38+
success: false,
39+
error: {
40+
message: 'Bearer token missing in the authorization headers.',
41+
},
42+
})
43+
}
44+
45+
return jwt.verify(token, process.env['JWT_SECRET']!, (err, user: any) => {
46+
if (err) {
47+
return res.status(403).json({
48+
success: false,
49+
error: 'Invalid access token provided, please login again.',
50+
})
51+
}
52+
53+
req.user = user
54+
return next()
55+
})
56+
}

src/modules/auth/application/controllers/auth.controller.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ import jwt from 'jsonwebtoken'
44
import { Request, Response } from 'express'
55

66
import { UserDataProvider } from '@/modules/users/adapters/dataproviders/user.dataprovider'
7-
import { User } from '@/modules/users/core'
7+
import { UserParams } from '@/modules/users/core'
88

99
export class AuthController {
1010
constructor(private _userDataProvider: UserDataProvider) {}
1111

12-
register = async (req: Request<User>, res: Response) => {
12+
register = async (req: Request<UserParams>, res: Response) => {
1313
const { password, ...user } = req.body
1414
const encryptedPassword = this._encryptPassword(password)
1515

@@ -40,7 +40,7 @@ export class AuthController {
4040
})
4141
}
4242

43-
sign = async (req: Request<User>, res: Response) => {
43+
sign = async (req: Request<UserParams>, res: Response) => {
4444
const { password, email } = req.body
4545
const encryptedPassword = this._encryptPassword(password)
4646
const defaultErrorMessage = 'Provided email or password might be incorrect.'
Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
import express from 'express'
22

3+
import { isAuthenticated } from '@/common/middlewares'
34
import { genAIController } from '@/di'
45

56
const router = express.Router()
67

7-
router.post('/translate', genAIController.translateText)
8-
router.post('/search-in-document', genAIController.searchInDocument)
8+
router.post('/translate', isAuthenticated, genAIController.translateText)
9+
10+
router.post(
11+
'/search-in-document',
12+
isAuthenticated,
13+
genAIController.searchInDocument,
14+
)
915

1016
export default router

src/modules/status/routes.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import express from 'express'
2+
3+
import { isAuthenticated } from '@/common/middlewares'
4+
25
const router = express.Router()
36

4-
export default router.get('/', (_, res) => {
7+
export default router.get('/', isAuthenticated, (_, res) => {
58
res.status(200).send({ message: 'Systems up and running!' })
69
})

src/modules/users/adapters/dataproviders/user.dataprovider.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { prismaClient } from '@/di'
2-
import { User } from '../../core'
2+
import { UserParams } from '../../core'
33

44
export class UserDataProvider {
5-
async insert({ name, email, password }: User) {
5+
async insert({ name, email, password }: UserParams) {
66
return await prismaClient.users.create({
77
data: {
88
name,
@@ -12,7 +12,7 @@ export class UserDataProvider {
1212
})
1313
}
1414

15-
async update({ id, name, email, password }: User) {
15+
async update({ id, name, email, password }: UserParams) {
1616
return await prismaClient.users.update({
1717
where: {
1818
id,
Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
import express from 'express'
22

3+
import { isAuthenticated } from '@/common/middlewares'
34
import { usersController } from '@/di'
45

56
const router = express.Router()
67

7-
router.get('/', usersController.getUser)
8-
router.patch('/', usersController.updateUser)
8+
router.get('/', isAuthenticated, usersController.getUser)
9+
router.patch('/', isAuthenticated, usersController.updateUser)
910

10-
router.get('/all', usersController.getAllUsers)
11+
router.get('/all', isAuthenticated, usersController.getAllUsers)
1112

12-
router.delete('/:id', usersController.deleteUser)
13-
router.post('/:id', usersController.getUser)
13+
router.delete('/:id', isAuthenticated, usersController.deleteUser)
14+
router.post('/:id', isAuthenticated, usersController.getUser)
1415

15-
router.put('/:id', usersController.updateUser)
16+
router.put('/:id', isAuthenticated, usersController.updateUser)
1617

1718
export default router
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export type User = {
22
id?: string
33
email: string
4+
createdAt: Date
45
password: string
56
name?: string
67
}

src/modules/users/core/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
export * from './entities'
2+
export * from './params'
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export type UserParams = {
2+
id: string
3+
email: string
4+
password: string
5+
name?: string
6+
}

0 commit comments

Comments
 (0)