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

feat auth changes #205

Merged
merged 6 commits into from
Apr 18, 2023
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
2 changes: 2 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"dotenv": "^16.0.2",
"envalid": "^7.3.1",
"fast-csv": "^4.3.6",
"hat": "^0.0.3",
"jsonwebtoken": "^9.0.0",
"passport": "^0.6.0",
"passport-github2": "^0.1.12",
Expand All @@ -60,6 +61,7 @@
"@types/chai": "^4.3.4",
"@types/cookie-parser": "^1.4.3",
"@types/express": "^4.17.14",
"@types/hat": "^0.0.1",
"@types/mocha": "^10.0.0",
"@types/multer": "^1.4.7",
"@types/node": "^18.7.18",
Expand Down
4 changes: 2 additions & 2 deletions apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { ReviewModule } from './app/review/review.module';
import { CommonModule } from './app/common/common.module';
import { HealthModule } from 'app/health/health.module';
import { AuthModule } from './app/auth/auth.module';
import { FlowModule } from './app/flow/flow.module';
import { EnvironmentModule } from './app/environment/environment.module';

const modules: Array<Type | DynamicModule | Promise<DynamicModule> | ForwardReference> = [
ProjectModule,
Expand All @@ -24,7 +24,7 @@ const modules: Array<Type | DynamicModule | Promise<DynamicModule> | ForwardRefe
CommonModule,
HealthModule,
AuthModule,
FlowModule,
EnvironmentModule,
];

const providers = [];
Expand Down
35 changes: 28 additions & 7 deletions apps/api/src/app/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { IJwtPayload } from '@impler/shared';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserEntity, UserRepository, MemberRepository, MemberEntity } from '@impler/dal';
import { UserEntity, UserRepository, EnvironmentRepository, ProjectRepository, ProjectEntity } from '@impler/dal';
import { UserNotFoundException } from '@shared/exceptions/user-not-found.exception';
import { IAuthenticationData, IStrategyResponse } from '@shared/types/auth.types';
import { IncorrectLoginCredentials } from '@shared/exceptions/incorrect-login-credentials.exception';
Expand All @@ -12,7 +12,8 @@ export class AuthService {
constructor(
private jwtService: JwtService,
private userRepository: UserRepository,
private memberRepository: MemberRepository
private projectRepository: ProjectRepository,
private environmentRepository: EnvironmentRepository
) {}

async authenticate({ profile, provider }: IAuthenticationData): Promise<IStrategyResponse> {
Expand Down Expand Up @@ -58,10 +59,10 @@ export class AuthService {
}

let showAddProject = true;
const member: MemberEntity = await this.memberRepository.findOne({
$or: [{ _userId: user._id }],
const project: ProjectEntity = await this.projectRepository.findOne({
_userId: user._id,
});
if (member) {
if (project) {
showAddProject = false;
}

Expand All @@ -70,8 +71,7 @@ export class AuthService {
showAddProject,
token: await this.getSignedToken(
{ _id: user._id, email: user.email, firstName: user.firstName, lastName: user.lastName },
member?._projectId,
member?.role
project?._id
),
};
}
Expand Down Expand Up @@ -131,4 +131,25 @@ export class AuthService {
private async getUser({ _id }: { _id: string }) {
return await this.userRepository.findById(_id);
}

async apiKeyAuthenticate(apiKey: string) {
const environment = await this.environmentRepository.findByApiKey(apiKey);
if (!environment) throw new UnauthorizedException('API Key not found');

const key = environment.apiKeys.find((i) => i.key === apiKey);
if (!key) throw new UnauthorizedException('API Key not found');

const user = await this.getUser({ _id: key._userId });
if (!user) throw new UnauthorizedException('User not found');

return await this.getSignedToken(
{
_id: user._id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
},
environment._projectId
);
}
}
5 changes: 5 additions & 0 deletions apps/api/src/app/environment/environment.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
@Controller('/environment')
@ApiTags('Environment')
export class EnvironmentController {}
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { USE_CASES } from './usecases';
import { EnvironmentController } from './environment.controller';
import { SharedModule } from '@shared/shared.module';
import { FlowController } from './flow.controller';

@Module({
imports: [SharedModule],
providers: [...USE_CASES],
controllers: [FlowController],
exports: [...USE_CASES],
controllers: [EnvironmentController],
})
export class FlowModule {}
export class EnvironmentModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ProjectCommand } from '../../../shared/commands/project.command';

export class CreateEnvironmentCommand extends ProjectCommand {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Injectable } from '@nestjs/common';
import { EnvironmentRepository } from '@impler/dal';

import { CreateEnvironmentCommand } from './create-environment.command';
import { GenerateUniqueApiKey } from '../generate-api-key/generate-api-key.usecase';

@Injectable()
export class CreateEnvironment {
constructor(
private environmentRepository: EnvironmentRepository,
private generateUniqueApiKey: GenerateUniqueApiKey
) {}

async execute(command: CreateEnvironmentCommand) {
const key = await this.generateUniqueApiKey.execute();

const environment = await this.environmentRepository.create({
_projectId: command.projectId,
apiKeys: [
{
key,
_userId: command._userId,
},
],
});

return environment;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { EnvironmentRepository } from '@impler/dal';
import * as hat from 'hat';
import { VARIABLES } from '@shared/constants';

const API_KEY_GENERATION_MAX_RETRIES = 3;

@Injectable()
export class GenerateUniqueApiKey {
constructor(private environmentRepository: EnvironmentRepository) {}

async execute(): Promise<string> {
let apiKey = '';
let count = 0;
let isApiKeyUsed = true;
while (isApiKeyUsed) {
apiKey = this.generateApiKey();
const environment = await this.environmentRepository.findByApiKey(apiKey);
isApiKeyUsed = environment ? true : false;
count += VARIABLES.ONE;

if (count === API_KEY_GENERATION_MAX_RETRIES) {
const errorMessage = 'Clashing of the API key generation';
throw new InternalServerErrorException(new Error(errorMessage), errorMessage);
}
}

return apiKey as string;
}

/**
* Extracting the generation functionality so it can be stubbed for functional testing
*
* @requires hat
* @todo Dependency is no longer accessible to source code due of removal from GitHub. Consider look for an alternative.
*/
private generateApiKey(): string {
return hat();
}
}
4 changes: 4 additions & 0 deletions apps/api/src/app/environment/usecases/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { CreateEnvironment } from './create-environment/create-environment.usecase';
import { GenerateUniqueApiKey } from './generate-api-key/generate-api-key.usecase';

export const USE_CASES = [CreateEnvironment, GenerateUniqueApiKey];
13 changes: 0 additions & 13 deletions apps/api/src/app/flow/dtos/update-flow.dto.ts

This file was deleted.

77 changes: 0 additions & 77 deletions apps/api/src/app/flow/flow.controller.ts

This file was deleted.

This file was deleted.

16 changes: 0 additions & 16 deletions apps/api/src/app/flow/usecases/create-flow/create-flow.usecase.ts

This file was deleted.

This file was deleted.

22 changes: 0 additions & 22 deletions apps/api/src/app/flow/usecases/delete-flow/delete-flow.usecase.ts

This file was deleted.

12 changes: 0 additions & 12 deletions apps/api/src/app/flow/usecases/get-flows/get-flows.command.ts

This file was deleted.

21 changes: 0 additions & 21 deletions apps/api/src/app/flow/usecases/get-flows/get-flows.usecase.ts

This file was deleted.

Loading