Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code in the user file has been revised to improve readability #98

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
12 changes: 6 additions & 6 deletions src/user/auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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};
}
}
4 changes: 2 additions & 2 deletions src/user/user.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down