28 lines
906 B
TypeScript
28 lines
906 B
TypeScript
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { UsersService } from '../../users/users.service';
|
|
|
|
@Injectable()
|
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
constructor(
|
|
private readonly configService: ConfigService,
|
|
private readonly usersService: UsersService,
|
|
) {
|
|
super({
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
ignoreExpiration: false,
|
|
secretOrKey: configService.get('JWT_SECRET', 'your-secret-key'),
|
|
});
|
|
}
|
|
|
|
async validate(payload: { sub: string }) {
|
|
const user = await this.usersService.findById(payload.sub);
|
|
if (!user || !user.isActive) {
|
|
throw new UnauthorizedException('Usuario no autorizado');
|
|
}
|
|
return user;
|
|
}
|
|
}
|