forked from Shared/esg
initial commit
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { JWT_ACCESS_STRATEGY } from '../constants/auth.constants';
|
||||
import { JwtPayload } from '../interfaces/jwt-payload.interface';
|
||||
import { AuthenticatedUser } from '../interfaces/authenticated-user.interface';
|
||||
import { UsersService } from '../../users/users.service';
|
||||
|
||||
/**
|
||||
* Validates access JWT and attaches a slim user object to the request.
|
||||
*/
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, JWT_ACCESS_STRATEGY) {
|
||||
constructor(
|
||||
configService: ConfigService,
|
||||
private readonly usersService: UsersService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: configService.getOrThrow<string>('auth.jwtSecret'),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: JwtPayload): Promise<AuthenticatedUser> {
|
||||
const user = await this.usersService.findById(payload.sub);
|
||||
|
||||
if (!user.isActive) {
|
||||
throw new UnauthorizedException('Account is inactive');
|
||||
}
|
||||
if (user.isBlocked) {
|
||||
throw new UnauthorizedException('Account is blocked');
|
||||
}
|
||||
|
||||
return {
|
||||
id: user._id.toString(),
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
clientType: user.clientType,
|
||||
appName: user.appName,
|
||||
allowedInquiries: user.allowedInquiries,
|
||||
requestLimitPerMinute: user.requestLimitPerMinute,
|
||||
requestLimitPerDay: user.requestLimitPerDay,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user