36 lines
842 B
TypeScript
36 lines
842 B
TypeScript
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
|
|
export interface JwtPayload {
|
|
sub: string;
|
|
email?: string;
|
|
phone?: string;
|
|
name?: string;
|
|
tenantId: string;
|
|
roles: string[];
|
|
}
|
|
|
|
@Injectable()
|
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
constructor() {
|
|
super({
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
ignoreExpiration: false,
|
|
secretOrKey: process.env.JWT_SECRET || 'dev-secret',
|
|
});
|
|
}
|
|
|
|
async validate(payload: JwtPayload) {
|
|
if (!payload.sub) {
|
|
throw new UnauthorizedException();
|
|
}
|
|
return {
|
|
userId: payload.sub,
|
|
email: payload.email,
|
|
tenantId: payload.tenantId,
|
|
roles: payload.roles,
|
|
};
|
|
}
|
|
}
|