Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: check user exists methods #113

Merged
merged 2 commits into from
Mar 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.5.5",
"socket.io": "^4.4.1"
"socket.io": "^4.4.1",
"@faker-js/faker": "^6.0.0"
},
"devDependencies": {
"@nestjs/cli": "^8.2.3",
Expand Down
7 changes: 7 additions & 0 deletions backend/src/libs/dto/param/email.param.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { IsEmail, IsString } from 'class-validator';

export class EmailParam {
@IsEmail()
@IsString()
email!: string;
}
11 changes: 7 additions & 4 deletions backend/src/libs/test-utils/mocks/user.mock.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { faker } from '@faker-js/faker';

const mockedUser = {
_id: '1',
email: 'user1@email.com',
name: 'John',
password: 'hash',
_id: faker.datatype.uuid(),
email: faker.internet.email(),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
password: faker.internet.password(),
};

export default mockedUser;
23 changes: 21 additions & 2 deletions backend/src/modules/auth/controller/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
Inject,
NotFoundException,
BadRequestException,
Param,
} from '@nestjs/common';
import LocalAuthGuard from '../../../libs/guards/localAuth.guard';
import RequestWithUser from '../../../libs/interfaces/requestWithUser.interface';
Expand All @@ -23,6 +24,9 @@ import {
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')
export default class AuthController {
Expand All @@ -31,13 +35,21 @@ export default class AuthController {
private registerAuthApp: RegisterAuthApplication,
@Inject(TYPES.applications.GetTokenAuthApplication)
private getTokenAuthApp: GetTokenAuthApplication,
@Inject(User.TYPES.applications.GetUserApplication)
private getUserApp: GetUserApplication,
) {}

@Post('register')
async register(@Body() registrationData: CreateUserDto) {
try {
const user = await this.registerAuthApp.register(registrationData);
return { _id: user._id, name: user.name, email: user.email };
const { _id, firstName, lastName, email } =
await this.registerAuthApp.register(registrationData);
return {
_id,
firstName,
lastName,
email,
};
} catch (error) {
if (error.code === uniqueViolation) {
throw new BadRequestException(EMAIL_EXISTS);
Expand Down Expand Up @@ -65,4 +77,11 @@ export default class AuthController {
} = request;
return this.getTokenAuthApp.getAccessToken(id);
}

@Get('checkUserEmail/:email')
async checkEmail(@Param() emailParam: EmailParam) {
const { email } = emailParam;
const found = await this.getUserApp.getByEmail(email);
return !!found;
nunocaseiro marked this conversation as resolved.
Show resolved Hide resolved
}
}
10 changes: 6 additions & 4 deletions backend/src/modules/auth/shared/login.auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ export const signIn = async (
getTokenService: GetTokenAuthService | GetTokenAuthApplication,
strategy: string,
) => {
const jwt = await getTokenService.getTokens(user._id);
const { email, firstName, lastName, _id } = user;
const jwt = await getTokenService.getTokens(_id);
if (!jwt) return null;
return {
...jwt,
email: user.email,
name: user.name,
email,
firstName,
lastName,
strategy,
id: user._id,
id: _id,
};
};
20 changes: 15 additions & 5 deletions backend/src/modules/azure/controller/azure.controller.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
import { Body, Controller, Get, Inject, Post, Req } from '@nestjs/common';
import { Body, Controller, Get, Inject, Param, Post } from '@nestjs/common';
import { EmailParam } from '../../../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';
import * as User from '../../users/interfaces/types';
import { GetUserApplication } from '../../users/interfaces/applications/get.user.application.interface';

@Controller('auth')
export default class AzureController {
constructor(
@Inject(TYPES.applications.AuthAzureApplication)
private authAzureApp: AuthAzureApplication,
@Inject(User.TYPES.applications.GetUserApplication)
private getUserApp: GetUserApplication,
) {}

@Post('signAzure')
loginOrRegisterAzureToken(@Body() azureToken: AzureToken) {
return this.authAzureApp.registerOrLogin(azureToken.token);
}

@Get('checkUserExists/:email')
checkUserExists(@Req() request) {
const { email } = request.params;
return this.authAzureApp.checkUserExistsInActiveDirectory(email);
@Get('checkUserEmailAD/:email')
async checkEmail(@Param() emailParam: EmailParam) {
const { 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;
}
}
2 changes: 1 addition & 1 deletion backend/src/modules/azure/interfaces/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ export const TYPES = {
CronAzureService: 'CronAzureService',
},
applications: {
AuthAzureApplication: 'AuthAuthApplication',
AuthAzureApplication: 'AuthAzureApplication',
},
};
3 changes: 2 additions & 1 deletion backend/src/modules/azure/services/auth.azure.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ export default class AuthAzureServiceImpl implements AuthAzureService {

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

Expand Down
16 changes: 16 additions & 0 deletions backend/src/modules/users/applications/get.user.application.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Injectable, Inject } from '@nestjs/common';
import { GetUserApplication } from '../interfaces/applications/get.user.application.interface';
import { GetUserService } from '../interfaces/services/get.user.service.interface';
import { TYPES } from '../interfaces/types';

@Injectable()
export class GetUserApplicationImpl implements GetUserApplication {
constructor(
@Inject(TYPES.services.GetUserService)
private getUserService: GetUserService,
) {}

getByEmail(email: string) {
return this.getUserService.getByEmail(email);
}
}
6 changes: 5 additions & 1 deletion backend/src/modules/users/dto/create.user.azure.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { IsNotEmpty, IsString } from 'class-validator';
export default class CreateUserAzureDto {
@IsNotEmpty()
@IsString()
name!: string;
firstName!: string;

@IsNotEmpty()
@IsString()
lastName!: string;

@IsNotEmpty()
@IsString()
Expand Down
8 changes: 7 additions & 1 deletion backend/src/modules/users/dto/create.user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ export default class CreateUserDto {
@IsNotEmpty()
@MinLength(3)
@Transform(({ value }: TransformFnParams) => value.trim())
name!: string;
firstName!: string;

@IsString()
@IsNotEmpty()
@MinLength(3)
@Transform(({ value }: TransformFnParams) => value.trim())
lastName!: string;

@IsString()
@IsNotEmpty()
Expand Down
6 changes: 5 additions & 1 deletion backend/src/modules/users/dto/logged.user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ export default class LoggedUserDto {

@IsNotEmpty()
@IsString()
name!: string;
firstName!: string;

@IsNotEmpty()
@IsString()
lastName!: string;

@IsNotEmpty()
@IsString()
Expand Down
6 changes: 5 additions & 1 deletion backend/src/modules/users/dto/user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ export default class UserDto {

@IsNotEmpty()
@IsString()
name!: string;
firstName!: string;

@IsNotEmpty()
@IsString()
lastName!: string;

@IsNotEmpty()
@IsString()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { LeanDocument } from 'mongoose';
import { UserDocument } from '../../schemas/user.schema';

export interface GetUserApplication {
getByEmail(email: string): Promise<LeanDocument<UserDocument> | null>;
}
3 changes: 3 additions & 0 deletions backend/src/modules/users/interfaces/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ export const TYPES = {
GetUserService: 'GetUserService',
UpdateUserService: 'UpdateUserService',
},
applications: {
GetUserApplication: 'GetUserApplication',
},
};
5 changes: 4 additions & 1 deletion backend/src/modules/users/schemas/user.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ export type UserDocument = User & mongoose.Document;
@Schema()
export default class User {
@Prop({ nullable: false })
name!: string;
firstName!: string;

@Prop({ nullable: false })
lastName!: string;

@Prop({ nullable: false })
password!: string;
Expand Down
15 changes: 13 additions & 2 deletions backend/src/modules/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,22 @@ import {
createUserService,
getUserService,
updateUserService,
getUserApplication,
} from './users.providers';

@Module({
imports: [mongooseUserModule],
providers: [createUserService, getUserService, updateUserService],
exports: [createUserService, getUserService, updateUserService],
providers: [
createUserService,
getUserService,
updateUserService,
getUserApplication,
],
exports: [
createUserService,
getUserService,
updateUserService,
getUserApplication,
],
})
export default class UsersModule {}
5 changes: 5 additions & 0 deletions backend/src/modules/users/users.providers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { GetUserApplicationImpl } from './applications/get.user.application';
import { TYPES } from './interfaces/types';
import CreateUserServiceImpl from './services/create.user.service';
import GetUserServiceImpl from './services/get.user.service';
Expand All @@ -15,3 +16,7 @@ export const updateUserService = {
provide: TYPES.services.UpdateUserService,
useClass: UpdateUserServiceImpl,
};
export const getUserApplication = {
provide: TYPES.applications.GetUserApplication,
useClass: GetUserApplicationImpl,
};
16 changes: 12 additions & 4 deletions backend/test/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
} from '../../src/modules/auth/auth.providers';
import {
createUserService,
getUserApplication,
getUserService,
updateUserService,
} from '../../src/modules/users/users.providers';

Expand All @@ -37,6 +39,8 @@ describe('AuthController', () => {
registerAuthService,
updateUserService,
createUserService,
getUserApplication,
getUserService,
ConfigService,
{
provide: ConfigService,
Expand Down Expand Up @@ -65,7 +69,8 @@ describe('AuthController', () => {
.post('/auth/register')
.send({
email: mockedUser.email,
name: mockedUser.name,
firstName: mockedUser.firstName,
lastName: mockedUser.lastName,
password: '1!Aab2CD',
})
.expect(201);
Expand All @@ -81,22 +86,25 @@ describe('AuthController', () => {
request(app.getHttpServer())
.post('/auth/register')
.send({
name: mockedUser.name,
firstName: mockedUser.firstName,
lastName: mockedUser.lastName,
})
.expect(400));
it('should throw an error because full data wasnt submitted', async () =>
request(app.getHttpServer())
.post('/auth/register')
.send({
name: mockedUser.name,
firstName: mockedUser.firstName,
lastName: mockedUser.lastName,
password: mockedUser.password,
})
.expect(400));
it('should throw an error because password is short', async () => {
const res = await request(app.getHttpServer())
.post('/auth/register')
.send({
name: mockedUser.name,
firstName: mockedUser.firstName,
lastName: mockedUser.lastName,
password: '1234',
email: mockedUser.email,
});
Expand Down
Loading