diff --git a/src/user/auth.middleware.ts b/src/user/auth.middleware.ts index 560fbde5..597c40b3 100644 --- a/src/user/auth.middleware.ts +++ b/src/user/auth.middleware.ts @@ -8,14 +8,14 @@ import { UserService } from './user.service'; @Injectable() export class AuthMiddleware implements NestMiddleware { - constructor(private readonly userService: UserService) {} + constructor(private readonly userService: UserService) { } async use(req: Request, res: Response, next: NextFunction) { - const authHeaders = req.headers.authorization; - if (authHeaders && (authHeaders as string).split(' ')[1]) { - const token = (authHeaders as string).split(' ')[1]; - const decoded: any = jwt.verify(token, SECRET); - const user = await this.userService.findById(decoded.id); + const authHeaders: string = req.headers.authorization; + if (authHeaders?.split(' ')[1]) { + const token = authHeaders.split(' ')[1]; + const { id: any } = jwt.verify(token, SECRET); + const user = await this.userService.findById(id); if (!user) { throw new HttpException('User not found.', HttpStatus.UNAUTHORIZED); diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts index 55e7121d..b329f4a6 100644 --- a/src/user/user.controller.ts +++ b/src/user/user.controller.ts @@ -49,7 +49,6 @@ export class UserController { const token = await this.userService.generateJWT(_user); const {email, username, bio, image} = _user; - const user = {email, token, username, bio, image}; - return {user} + return {email, token, username, bio, image}; } } diff --git a/src/user/user.decorator.ts b/src/user/user.decorator.ts index ade23d86..78a99346 100644 --- a/src/user/user.decorator.ts +++ b/src/user/user.decorator.ts @@ -10,8 +10,8 @@ export const User = createParamDecorator((data: any, ctx: ExecutionContext) => { } // in case a route is not protected, we still want to get the optional auth user from jwt - const token = req.headers.authorization ? (req.headers.authorization as string).split(' ') : null; - if (token && token[1]) { + const token = (req.headers.authorization as string)?.split(' ') || null; + if (token?.[1]) { const decoded: any = jwt.verify(token[1], SECRET); return !!data ? decoded[data] : decoded.user; }