change jwt data

This commit is contained in:
rubikscraft
2022-03-21 23:23:32 +01:00
parent d11c8f9083
commit 0b65d496c3
4 changed files with 19 additions and 14 deletions

View File

@@ -13,7 +13,10 @@ export class AuthManagerService {
async createToken(user: EUserBackend): Promise<string> { async createToken(user: EUserBackend): Promise<string> {
const jwtData: JwtDataDto = plainToClass(JwtDataDto, { const jwtData: JwtDataDto = plainToClass(JwtDataDto, {
user, user: {
username: user.username,
roles: user.roles,
},
}); });
const errors = await strictValidate(jwtData); const errors = await strictValidate(jwtData);

View File

@@ -1,8 +1,7 @@
import { import {
Inject, Inject,
Injectable, Injectable,
Logger, Logger
UnauthorizedException
} from '@nestjs/common'; } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport'; import { PassportStrategy } from '@nestjs/passport';
import { plainToClass } from 'class-transformer'; import { plainToClass } from 'class-transformer';
@@ -23,14 +22,14 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
}); });
} }
async validate(payload: any): Promise<EUserBackend> { async validate(payload: any): Promise<EUserBackend | false> {
const jwt = plainToClass(JwtDataDto, payload); const jwt = plainToClass(JwtDataDto, payload);
const errors = await strictValidate(jwt); const errors = await strictValidate(jwt);
if (errors.length > 0) { if (errors.length > 0) {
this.logger.warn(errors); this.logger.warn(errors);
throw new UnauthorizedException(); return false;
} }
return jwt.user; return jwt.user;

View File

@@ -1,12 +1,12 @@
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { IsDefined, IsInt, IsOptional, ValidateNested } from 'class-validator'; import { IsDefined, IsInt, IsOptional, ValidateNested } from 'class-validator';
import { EUser } from '../entities/user.entity'; import { RoledUser } from '../entities/user.entity';
export class JwtDataDto { export class JwtDataDto {
@IsDefined() @IsDefined()
@ValidateNested() @ValidateNested()
@Type(() => EUser) @Type(() => RoledUser)
user: EUser; user: RoledUser;
@IsOptional() @IsOptional()
@IsInt() @IsInt()

View File

@@ -29,15 +29,18 @@ export class SimpleUser extends SimpleUsername {
password: string; password: string;
} }
// Actual entity that goes in the db // Add a user object with just the username and roles for jwt
export class EUser extends SimpleUsername { export class RoledUser extends SimpleUsername {
@IsOptional()
@IsInt()
id?: number;
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
roles: Roles; roles: Roles;
}
// Actual entity that goes in the db
export class EUser extends RoledUser {
@IsOptional()
@IsInt()
id?: number;
@IsOptional() @IsOptional()
@Exclude() @Exclude()