-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathauth-jwt.ts
More file actions
34 lines (29 loc) · 1.09 KB
/
auth-jwt.ts
File metadata and controls
34 lines (29 loc) · 1.09 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
import type { UserRepository } from '@/features/user/repositories/user-repository';
import { InvalidTokenException } from '@/shared/errors/invalid-token-exception';
import { type JWTHelper } from '@/shared/infra/jwt/jwt';
import type { AsyncRequestHandler } from '@/shared/protocols/handlers';
export class AuthenticationJWT {
jwtAuth: AsyncRequestHandler = async (req, res, next) => {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Token missing' });
}
const { userId } = this.jwtHelper.parseToken(token);
const user = await this.userRepository.findById(userId);
if (!user) {
return res.status(401).json({ error: 'Invalid user' });
}
next();
} catch (error) {
if (error instanceof InvalidTokenException) {
return res.status(401).json({ error: 'Invalid token' });
}
return res.status(500).json({ error: 'Internal Server Error' });
}
};
constructor(
private jwtHelper: JWTHelper,
private userRepository: UserRepository
) {}
}