forked from Shared/esg
50 lines
1.6 KiB
TypeScript
50 lines
1.6 KiB
TypeScript
import { Injectable } 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';
|
|
import { AppException } from '../../common/exceptions/app-exception';
|
|
|
|
/**
|
|
* 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 AppException('ACCOUNT_INACTIVE');
|
|
}
|
|
if (user.isBlocked) {
|
|
throw new AppException('ACCOUNT_BLOCKED');
|
|
}
|
|
|
|
return {
|
|
id: user.id,
|
|
username: user.username,
|
|
email: user.email,
|
|
role: user.role,
|
|
clientType: user.clientType,
|
|
appName: user.appName,
|
|
allowedInquiries: user.allowedInquiries,
|
|
requestLimitPerMinute: user.requestLimitPerMinute,
|
|
requestLimitPerDay: user.requestLimitPerDay,
|
|
};
|
|
}
|
|
}
|