-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.guard.spec.ts
More file actions
166 lines (140 loc) · 5.2 KB
/
Copy pathauth.guard.spec.ts
File metadata and controls
166 lines (140 loc) · 5.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import {
ExecutionContext,
ForbiddenException,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { JsonWebTokenError, JwtService } from '@nestjs/jwt'
import { Test, TestingModule } from '@nestjs/testing'
import { Request } from 'express'
import authConfig from 'src/auth/config/auth.config'
import { IS_PUBLIC_KEY } from 'src/auth/decorator'
import { PrismaService } from 'src/infra/prisma/prisma.service'
import { AuthGuard, REQUEST_USER_KEY } from './auth.guard'
describe('AuthGuard', () => {
let guard: AuthGuard
const mockReflector = {
getAllAndOverride: jest.fn(),
}
const mockJwtService = {
verifyAsync: jest.fn(),
}
const mockPrisma = {
user: {
findUnique: jest.fn(),
},
}
const mockAuthConfig = { secret: 'test-secret' }
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthGuard,
{ provide: Reflector, useValue: mockReflector },
{ provide: JwtService, useValue: mockJwtService },
{ provide: PrismaService, useValue: mockPrisma },
{ provide: authConfig.KEY, useValue: mockAuthConfig },
],
}).compile()
guard = module.get<AuthGuard>(AuthGuard)
})
afterEach(() => {
jest.clearAllMocks()
})
const mockContext = (headers: Record<string, string> = {}) => {
const request = { headers } as unknown as Request
return {
getHandler: jest.fn(),
getClass: jest.fn(),
switchToHttp: jest.fn().mockReturnValue({
getRequest: () => request,
}),
} as unknown as ExecutionContext
}
it('should be defined', () => {
expect(guard).toBeDefined()
})
it('should return true if route is public', async () => {
mockReflector.getAllAndOverride.mockReturnValue(true)
const context = mockContext()
expect(await guard.canActivate(context)).toBe(true)
expect(mockReflector.getAllAndOverride).toHaveBeenCalledWith(
IS_PUBLIC_KEY,
expect.anything(),
)
})
it('should throw UnauthorizedException if token is missing', async () => {
mockReflector.getAllAndOverride.mockReturnValue(false)
const context = mockContext({}) // no authorization header
await expect(guard.canActivate(context)).rejects.toThrow(
new UnauthorizedException('Token missing'),
)
})
it('should throw UnauthorizedException if token verification fails with JsonWebTokenError', async () => {
mockReflector.getAllAndOverride.mockReturnValue(false)
const context = mockContext({ authorization: 'Bearer invalid_token' })
mockJwtService.verifyAsync.mockRejectedValue(
new JsonWebTokenError('invalid signature'),
)
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
)
})
it('should throw NotFoundException if user is not found', async () => {
mockReflector.getAllAndOverride.mockReturnValue(false)
const context = mockContext({ authorization: 'Bearer valid_token' })
mockJwtService.verifyAsync.mockResolvedValue({ sub: 1, version: 1 })
mockPrisma.user.findUnique.mockResolvedValue(null)
await expect(guard.canActivate(context)).rejects.toThrow(
new NotFoundException('Your account not exists'),
)
})
it('should throw ForbiddenException if user is inactive (deleted)', async () => {
mockReflector.getAllAndOverride.mockReturnValue(false)
const context = mockContext({ authorization: 'Bearer valid_token' })
mockJwtService.verifyAsync.mockResolvedValue({ sub: 1, version: 1 })
mockPrisma.user.findUnique.mockResolvedValue({ deleted: true })
await expect(guard.canActivate(context)).rejects.toThrow(
new ForbiddenException('Your account is inactive'),
)
})
it('should throw UnauthorizedException if token version does not match user tokenVersion', async () => {
mockReflector.getAllAndOverride.mockReturnValue(false)
const context = mockContext({ authorization: 'Bearer valid_token' })
mockJwtService.verifyAsync.mockResolvedValue({ sub: 1, version: 1 }) // payload version 1
mockPrisma.user.findUnique.mockResolvedValue({
deleted: false,
tokenVersion: 2,
}) // user version 2
await expect(guard.canActivate(context)).rejects.toThrow(
new UnauthorizedException('Access token revoked'),
)
})
it('should attach user payload to request and return true on valid token', async () => {
mockReflector.getAllAndOverride.mockReturnValue(false)
const request = {
headers: { authorization: 'Bearer valid_token' },
} as unknown as Request
const context = {
getHandler: jest.fn(),
getClass: jest.fn(),
switchToHttp: jest.fn().mockReturnValue({ getRequest: () => request }),
} as unknown as ExecutionContext
mockJwtService.verifyAsync.mockResolvedValue({ sub: 1, version: 1 })
mockPrisma.user.findUnique.mockResolvedValue({
email: 'test@test.com',
role: 'USER',
tokenVersion: 1,
deleted: false,
})
const result = await guard.canActivate(context)
expect(result).toBe(true)
expect(
(request as unknown as Record<string, unknown>)[REQUEST_USER_KEY],
).toEqual({
sub: 1,
email: 'test@test.com',
role: 'USER',
})
})
})