homemanager-be/src/shared/guards/login.guard.ts

46 lines
1.2 KiB
TypeScript

import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { UserService } from 'src/objects/user/user.service';
import { AuthService } from '../auth/auth.service';
@Injectable()
export class LoginGuard implements CanActivate {
constructor(
private readonly authService: AuthService,
private readonly userService: UserService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const http = context.switchToHttp();
const request = http.getRequest();
const response = http.getResponse();
const authHeader = request.header('authorization');
if (!authHeader) return false;
const [method, token] = authHeader.split(' ');
if (!token || method !== 'Basic') return false;
const [email, password] = Buffer.from(token, 'base64')
.toString()
.split(':');
const user = await this.userService.getUserByEmail(email);
if (!user) {
throw new UnauthorizedException('Invalid username or password');
}
if (!(await this.authService.comparePassword(user, password))) {
throw new UnauthorizedException('Invalid username or password');
}
response.locals.user = user;
return true;
}
}