Skip to content

Commit

Permalink
fix(auth): compile-time errors (#124)
Browse files Browse the repository at this point in the history
  • Loading branch information
derevnjuk authored Sep 29, 2021
1 parent 7e61100 commit 7297d30
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 37 deletions.
17 changes: 7 additions & 10 deletions src/keycloak/keycloak.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export interface RegisterUserData {
}

export interface ExistingUserData {
email: string,
email: string;
}

export interface GenerateTokenData {
Expand Down Expand Up @@ -142,22 +142,20 @@ export class KeyCloakService implements OnModuleInit {
});
}

public async isUserExists({
email,
}: ExistingUserData): Promise<Boolean> {
this.log.debug(`Called isUserExist`);
public async isUserExists({ email }: ExistingUserData): Promise<boolean> {
this.log.debug(`Called isUserExist`);

const { access_token, token_type } = await this.generateToken();

const [existingUser] = await this.httpClient.get(
const [existingUser]: unknown[] = await this.httpClient.get(
`${this.server_uri}/admin/realms/${this.realm}/users?email=${email}`,
{
headers: {
'Content-Type': 'application/json',
Authorization: `${token_type} ${access_token}`,
},
responseType: 'json',
}
},
);
return !!existingUser;
}
Expand All @@ -172,7 +170,7 @@ export class KeyCloakService implements OnModuleInit {

const { access_token, token_type } = await this.generateToken();

const user: User = await this.httpClient.post(
return this.httpClient.post(
`${this.server_uri}/admin/realms/${this.realm}/users`,
{
firstName,
Expand All @@ -195,8 +193,7 @@ export class KeyCloakService implements OnModuleInit {
},
responseType: 'json',
},
)
return user;
);
}

public async generateToken(tokenData?: GenerateTokenData): Promise<Token> {
Expand Down
13 changes: 6 additions & 7 deletions src/users/api/UserDto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { ApiProperty } from '@nestjs/swagger';
import { User } from '../../model/user.entity';

export class UserDto {
@ApiProperty()
Expand All @@ -11,11 +10,11 @@ export class UserDto {
@ApiProperty()
lastName: string;

public static convertToApi(user: User): UserDto {
return {
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
};
constructor(
params: {
[P in keyof UserDto]: UserDto[P];
},
) {
Object.assign(this, params);
}
}
43 changes: 23 additions & 20 deletions src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class UsersController {
async getUser(@Param('email') email: string): Promise<UserDto> {
try {
this.logger.debug(`Find a user by email: ${email}`);
return UserDto.convertToApi(await this.usersService.findByEmail(email));
return new UserDto(await this.usersService.findByEmail(email));
} catch (err) {
throw new InternalServerErrorException({
error: err.message,
Expand Down Expand Up @@ -151,7 +151,7 @@ export class UsersController {
throw new NotFoundException('User not found in ldap');
}

return users.map<UserDto>(UserDto.convertToApi);
return users.map((user: User) => new UserDto(user));
}

@Post('/basic')
Expand All @@ -165,24 +165,26 @@ export class UsersController {
async createUser(@Body() user: CreateUserRequest): Promise<UserDto> {
try {
this.logger.debug(`Create a basic user: ${user}`);

const userExists = await this.usersService.findByEmail(user.email);

if (userExists) {
throw new HttpException(
'User already exists',
409
)
throw new HttpException('User already exists', 409);
}
const newUser = UserDto.convertToApi(

return new UserDto(
await this.usersService.createUser(
user.email,
user.firstName,
user.lastName,
user.password,
),
);
return newUser;
} catch (err) {
throw new HttpException(err.message ?? 'Something went wrong', err.status ?? 500)
throw new HttpException(
err.message ?? 'Something went wrong',
err.status ?? 500,
);
}
}

Expand All @@ -194,30 +196,31 @@ export class UsersController {
type: UserDto,
status: 200,
})
async createOIDCUser(@Body() user: CreateUserRequest): Promise<object | string> {
async createOIDCUser(@Body() user: CreateUserRequest): Promise<UserDto> {
try {
this.logger.debug(`Create a OIDC user: ${user}`);

const userExists = await this.keyCloakService.isUserExists({
email: user.email,
});

if (userExists) {
throw new HttpException(
'User already exists',
409
)
throw new HttpException('User already exists', 409);
}
const newUser = UserDto.convertToApi(

return new UserDto(
await this.keyCloakService.registerUser({
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
password: user.password,
}));
return newUser;

} catch ({ response = 'Something went wrong', status = 500 }) {
throw new HttpException(response, status)
}),
);
} catch (err) {
throw new HttpException(
err.message ?? 'Something went wrong',
err.status ?? 500,
);
}
}

Expand Down

0 comments on commit 7297d30

Please sign in to comment.