65 lines
1.7 KiB
TypeScript
65 lines
1.7 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { UserEntity } from '../../../entities/user.entity';
|
|
import { AuthUser, JwtPayload } from '../auth.types';
|
|
|
|
type RequestWithUser = Request & {
|
|
headers: {
|
|
authorization?: string;
|
|
};
|
|
user?: AuthUser;
|
|
};
|
|
|
|
@Injectable()
|
|
export class JwtAuthGuard implements CanActivate {
|
|
constructor(
|
|
private readonly jwt: JwtService,
|
|
@InjectRepository(UserEntity)
|
|
private readonly users: Repository<UserEntity>,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
|
const token = this.extractBearerToken(request.headers.authorization);
|
|
|
|
if (!token) {
|
|
throw new UnauthorizedException('Missing bearer token');
|
|
}
|
|
|
|
try {
|
|
const payload = await this.jwt.verifyAsync<JwtPayload>(token);
|
|
const user = await this.users.findOne({
|
|
where: { id: payload.sub, isActive: true },
|
|
});
|
|
|
|
if (!user) {
|
|
throw new UnauthorizedException('User is inactive or not found');
|
|
}
|
|
|
|
request.user = {
|
|
id: user.id,
|
|
mobile: user.mobile,
|
|
role: user.role,
|
|
};
|
|
return true;
|
|
} catch {
|
|
throw new UnauthorizedException('Invalid bearer token');
|
|
}
|
|
}
|
|
|
|
private extractBearerToken(header?: string): string | null {
|
|
if (!header) {
|
|
return null;
|
|
}
|
|
const [type, token] = header.split(' ');
|
|
return type === 'Bearer' && token ? token : null;
|
|
}
|
|
}
|