Skip to content

Commit

Permalink
chore: improve some code (#127)
Browse files Browse the repository at this point in the history
* chore: improved some code in auth, boards and azure domains

* chore: improved code on cards domain

* chore: improved code on comments domain

* chore: improved code on users and votes domains

* chore: revert parameters change

Co-authored-by: Rui Silva <rui.s@tamanna.com>
  • Loading branch information
rpvsilva and Rui Silva authored Apr 11, 2022
1 parent 252e213 commit bdc35f2
Show file tree
Hide file tree
Showing 32 changed files with 248 additions and 226 deletions.
4 changes: 3 additions & 1 deletion backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,6 @@ lerna-debug.log*
.env.production.local
.env
.env.dev
.env.staging
.env.staging

.vscode
30 changes: 12 additions & 18 deletions backend/src/modules/auth/controller/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
BadRequestException,
Param,
} from '@nestjs/common';
import { EmailParam } from '../../../libs/dto/param/email.param';
import LocalAuthGuard from '../../../libs/guards/localAuth.guard';
import RequestWithUser from '../../../libs/interfaces/requestWithUser.interface';
import JwtRefreshGuard from '../../../libs/guards/jwtRefreshAuth.guard';
Expand All @@ -25,7 +26,6 @@ import CreateUserDto from '../../users/dto/create.user.dto';
import { uniqueViolation } from '../../../infrastructure/database/errors/unique.user';
import { signIn } from '../shared/login.auth';
import * as User from '../../users/interfaces/types';
import { EmailParam } from '../../../libs/dto/param/email.param';
import { GetUserApplication } from '../../users/interfaces/applications/get.user.application.interface';

@Controller('auth')
Expand All @@ -44,12 +44,8 @@ export default class AuthController {
try {
const { _id, firstName, lastName, email } =
await this.registerAuthApp.register(registrationData);
return {
_id,
firstName,
lastName,
email,
};

return { _id, firstName, lastName, email };
} catch (error) {
if (error.code === uniqueViolation) {
throw new BadRequestException(EMAIL_EXISTS);
Expand All @@ -62,26 +58,24 @@ export default class AuthController {
@UseGuards(LocalAuthGuard)
@Post('login')
async login(@Req() request: RequestWithUser) {
const { user } = request;

const loggedUser = await signIn(user, this.getTokenAuthApp, 'local');
const loggedUser = await signIn(
request.user,
this.getTokenAuthApp,
'local',
);
if (!loggedUser) throw new NotFoundException(USER_NOT_FOUND);

return loggedUser;
}

@UseGuards(JwtRefreshGuard)
@Get('refresh')
refresh(@Req() request: RequestWithUser) {
const {
user: { _id: id },
} = request;
return this.getTokenAuthApp.getAccessToken(id);
return this.getTokenAuthApp.getAccessToken(request.user._id);
}

@Get('checkUserEmail/:email')
async checkEmail(@Param() emailParam: EmailParam) {
const { email } = emailParam;
const found = await this.getUserApp.getByEmail(email);
return !!found;
checkEmail(@Param() { email }: EmailParam): Promise<boolean> {
return this.getUserApp.getByEmail(email).then((user) => !!user);
}
}
11 changes: 3 additions & 8 deletions backend/src/modules/auth/shared/login.auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,8 @@ export const signIn = async (
) => {
const { email, firstName, lastName, _id } = user;
const jwt = await getTokenService.getTokens(_id);

if (!jwt) return null;
return {
...jwt,
email,
firstName,
lastName,
strategy,
id: _id,
};

return { ...jwt, email, firstName, lastName, strategy, id: _id };
};
2 changes: 2 additions & 0 deletions backend/src/modules/auth/strategy/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ export default class JwtStrategy extends PassportStrategy(Strategy) {
const user = await this.validateUserAuthService.validateUserById(
payload.userId,
);

if (!user) throw new UnauthorizedException(INVALID_CREDENTIALS);

return user;
}
}
2 changes: 2 additions & 0 deletions backend/src/modules/auth/strategy/local.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ export default class LocalStrategy extends PassportStrategy(Strategy) {
email,
password,
);

if (!user) throw new UnauthorizedException(INVALID_CREDENTIALS);

return user;
}
}
2 changes: 2 additions & 0 deletions backend/src/modules/auth/strategy/refresh.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ export default class JwtRefreshTokenStrategy extends PassportStrategy(
authorization!,
payload.userId,
);

if (!user) throw new UnauthorizedException(INVALID_CREDENTIALS);

return user;
}
}
7 changes: 4 additions & 3 deletions backend/src/modules/azure/controller/azure.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Body, Controller, Get, Inject, Param, Post } from '@nestjs/common';
import { EmailParam } from '../../../libs/dto/param/email.param';
import { EmailParam } from 'src/libs/dto/param/email.param';
import { AuthAzureApplication } from '../interfaces/applications/auth.azure.application.interface';
import { AzureToken } from '../interfaces/token.azure.dto';
import { TYPES } from '../interfaces/types';
Expand All @@ -21,13 +21,14 @@ export default class AzureController {
}

@Get('checkUserEmailAD/:email')
async checkEmail(@Param() emailParam: EmailParam) {
const { email } = emailParam;
async checkEmail(@Param() { email }: EmailParam) {
const existUserInAzure =
await this.authAzureApp.checkUserExistsInActiveDirectory(email);
if (existUserInAzure) return 'az';

const existUserInDB = await this.getUserApp.getByEmail(email);
if (existUserInDB) return 'local';

return false;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export interface CronAzureService {
getAzureAccessToken: () => Promise<void>;
getAzureAccessToken: () => Promise<string>;
getToken: () => string | undefined;
handleCron(): Promise<void>;
}
25 changes: 14 additions & 11 deletions backend/src/modules/azure/services/auth.azure.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ import { TYPES } from '../interfaces/types';
import { CronAzureService } from '../interfaces/services/cron.azure.service.interface';
import isEmpty from '../../../libs/utils/isEmpty';

interface AzureUserFound {
mail: string | undefined;
displayName: string | undefined;
userPrincipalName: string | undefined;
}
type AzureUserFound = {
mail?: string;
displayName?: string;
userPrincipalName?: string;
};

interface AzureDecodedUser {
type AzureDecodedUser = {
unique_name: string;
email: string;
given_name: string;
family_name: string;
}
};

@Injectable()
export default class AuthAzureServiceImpl implements AuthAzureService {
Expand All @@ -42,17 +42,20 @@ export default class AuthAzureServiceImpl implements AuthAzureService {
const { unique_name, email, given_name, family_name } = <AzureDecodedUser>(
jwt_decode(azureToken)
);
const user = await this.getUserService.getByEmail(email ?? unique_name);

const emailOrUniqueName = email ?? unique_name;
const user = await this.getUserService.getByEmail(emailOrUniqueName);
if (user) return signIn(user, this.getTokenService, 'azure');

const createdUser = await this.createUserService.create({
email: email ?? unique_name,
email: emailOrUniqueName,
firstName: given_name,
lastName: family_name,
});
if (createdUser) return signIn(createdUser, this.getTokenService, 'azure');

return null;
if (!createdUser) return null;

return signIn(createdUser, this.getTokenService, 'azure');
}

getGraphQueryUrl(email: string) {
Expand Down
15 changes: 8 additions & 7 deletions backend/src/modules/azure/services/cron.azure.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ import { CronAzureService } from '../interfaces/services/cron.azure.service.inte

@Injectable()
export default class CronAzureServiceImpl implements CronAzureService {
private azureAccessToken: string | undefined = undefined;

constructor(private readonly configService: ConfigService) {
this.getAzureAccessToken();
this.getAzureAccessToken().then((token) => {
this.azureAccessToken = token;
});
}

private azureAccessToken: string | undefined = undefined;

@Cron('0 45 * * * *')
async handleCron() {
await this.getAzureAccessToken();
Expand All @@ -30,7 +32,7 @@ export default class CronAzureServiceImpl implements CronAzureService {
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
}

async getAzureAccessToken() {
async getAzureAccessToken(): Promise<string> {
const params = new URLSearchParams();
params.append('grant_type', 'client_credentials');
params.append('client_id', this.configService.get(AZURE_CLIENT_ID)!);
Expand All @@ -48,8 +50,7 @@ export default class CronAzureServiceImpl implements CronAzureService {

const authUrl = this.getOAuthUrl(this.configService.get(AZURE_TENANT_ID)!);

const { data: tokenData } = await axios.post(authUrl, params, config);
const { access_token: accessToken } = tokenData;
this.azureAccessToken = accessToken;
const { data } = await axios.post(authUrl, params, config);
return data.access_token;
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Inject, Injectable } from '@nestjs/common';
import BoardDto from '../dto/board.dto';
import { CreateBoardApplication } from '../interfaces/applications/create.board.application.interface';
import { CreateBoardApplicationInterface } from '../interfaces/applications/create.board.application.interface';
import { CreateBoardService } from '../interfaces/services/create.board.service.interface';
import { TYPES } from '../interfaces/types';
import { BoardDocument } from '../schemas/board.schema';

@Injectable()
export class CreateBoardApplicationImpl implements CreateBoardApplication {
export class CreateBoardApplication implements CreateBoardApplicationInterface {
constructor(
@Inject(TYPES.services.CreateBoardService)
private createBoardService: CreateBoardService,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Inject, Injectable } from '@nestjs/common';
import { DeleteBoardApplication } from '../interfaces/applications/delete.board.application.interface';
import { DeleteBoardApplicationInterface } from '../interfaces/applications/delete.board.application.interface';
import { DeleteBoardService } from '../interfaces/services/delete.board.service.interface';
import { TYPES } from '../interfaces/types';

@Injectable()
export class DeleteBoardApplicationImpl implements DeleteBoardApplication {
export class DeleteBoardApplication implements DeleteBoardApplicationInterface {
constructor(
@Inject(TYPES.services.DeleteBoardService)
private deleteBoardService: DeleteBoardService,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Inject, Injectable } from '@nestjs/common';
import { GetBoardApplication } from '../interfaces/applications/get.board.application.interface';
import { GetBoardApplicationInterface } from '../interfaces/applications/get.board.application.interface';
import { GetBoardService } from '../interfaces/services/get.board.service.interface';
import { TYPES } from '../interfaces/types';

@Injectable()
export class GetBoardApplicationImpl implements GetBoardApplication {
export class GetBoardApplication implements GetBoardApplicationInterface {
constructor(
@Inject(TYPES.services.GetBoardService)
private getBoardService: GetBoardService,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Inject, Injectable } from '@nestjs/common';
import boardDto from '../dto/board.dto';
import { UpdateBoardApplication } from '../interfaces/applications/update.board.application.interface';
import { UpdateBoardApplicationInterface } from '../interfaces/applications/update.board.application.interface';
import { UpdateBoardService } from '../interfaces/services/update.board.service.interface';
import { TYPES } from '../interfaces/types';

@Injectable()
export class UpdateBoardApplicationImpl implements UpdateBoardApplication {
export class UpdateBoardApplication implements UpdateBoardApplicationInterface {
constructor(
@Inject(TYPES.services.UpdateBoardService)
private updateBoardService: UpdateBoardService,
Expand Down
16 changes: 8 additions & 8 deletions backend/src/modules/boards/boards.providers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { CreateBoardApplicationImpl } from './applications/create.board.application';
import { DeleteBoardApplicationImpl } from './applications/delete.board.application';
import { GetBoardApplicationImpl } from './applications/get.board.application';
import { UpdateBoardApplicationImpl } from './applications/update.board.application';
import { CreateBoardApplication } from './applications/create.board.application';
import { DeleteBoardApplication } from './applications/delete.board.application';
import { GetBoardApplication } from './applications/get.board.application';
import { UpdateBoardApplication } from './applications/update.board.application';
import { TYPES } from './interfaces/types';
import CreateBoardServiceImpl from './services/create.board.service';
import DeleteBoardServiceImpl from './services/delete.board.service';
Expand Down Expand Up @@ -30,20 +30,20 @@ export const deleteBoardService = {

export const createBoardApplication = {
provide: TYPES.applications.CreateBoardApplication,
useClass: CreateBoardApplicationImpl,
useClass: CreateBoardApplication,
};

export const getBoardApplication = {
provide: TYPES.applications.GetBoardApplication,
useClass: GetBoardApplicationImpl,
useClass: GetBoardApplication,
};

export const updateBoardApplication = {
provide: TYPES.applications.UpdateBoardApplication,
useClass: UpdateBoardApplicationImpl,
useClass: UpdateBoardApplication,
};

export const deleteBoardApplication = {
provide: TYPES.applications.DeleteBoardApplication,
useClass: DeleteBoardApplicationImpl,
useClass: DeleteBoardApplication,
};
Loading

0 comments on commit bdc35f2

Please sign in to comment.