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 Login API #186

Merged
merged 1 commit into from
Feb 6, 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
23 changes: 19 additions & 4 deletions apps/api/src/app/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ import {
UseInterceptors,
} from '@nestjs/common';
import { IJwtPayload } from '@impler/shared';
import { RegisterUserDto, LoginUserDto } from './dtos';
import { IStrategyResponse } from '@shared/types/auth.types';
import { CONSTANTS, COOKIE_CONFIG } from '@shared/constants';
import { UserSession } from '@shared/framework/user.decorator';
import { ApiException } from '@shared/exceptions/api.exception';
import { StrategyUser } from './decorators/strategy-user.decorator';
import { CONSTANTS, COOKIE_CONFIG } from '@shared/constants';
import { RegisterUserDto } from './dtos/register-user.dto';
import { RegisterUser, RegisterUserCommand } from './usecases';
import { LoginUser, LoginUserCommand, RegisterUser, RegisterUserCommand } from './usecases';

@ApiTags('Auth')
@Controller('/auth')
@ApiExcludeController()
@UseInterceptors(ClassSerializerInterceptor)
export class AuthController {
constructor(private registerUser: RegisterUser) {}
constructor(private registerUser: RegisterUser, private loginUser: LoginUser) {}

@Post('/register')
async registerUserAPI(@Body() registerData: RegisterUserDto, @Res({ passthrough: true }) response: Response) {
Expand All @@ -39,6 +39,21 @@ export class AuthController {
);

response.cookie(CONSTANTS.AUTH_COOKIE_NAME, registerationResponse.token, COOKIE_CONFIG);

return { showAddProject: registerationResponse.showAddProject };
}

@Post('/login')
async login(@Body() loginData: LoginUserDto, @Res({ passthrough: true }) response: Response) {
const loginResponse = await this.loginUser.execute(
LoginUserCommand.create({
email: loginData.email,
password: loginData.password,
})
);
response.cookie(CONSTANTS.AUTH_COOKIE_NAME, loginResponse.token, COOKIE_CONFIG);

return { showAddProject: loginResponse.showAddProject };
}

@Get('/github')
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/app/auth/dtos/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { LoginUserDto } from './login-user.dto';
export { RegisterUserDto } from './register-user.dto';
11 changes: 11 additions & 0 deletions apps/api/src/app/auth/dtos/login-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { IsDefined, IsString, IsEmail } from 'class-validator';

export class LoginUserDto {
@IsEmail()
@IsDefined()
email: string;

@IsString()
@IsDefined()
password: string;
}
32 changes: 30 additions & 2 deletions apps/api/src/app/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserEntity, UserRepository, MemberRepository, MemberEntity } from '@impler/dal';
import { IJwtPayload, MemberStatusEnum } from '@impler/shared';
import { UserNotFoundException } from '@shared/exceptions/user-not-found.exception';
import { IAuthenticationData, IStrategyResponse } from '@shared/types/auth.types';
import { UniqueEmailException } from '@shared/exceptions/unique-email.exception';
import { IncorrectLoginCredentials } from '@shared/exceptions/incorrect-login-credentials.exception';

@Injectable()
export class AuthService {
Expand Down Expand Up @@ -48,7 +50,7 @@ export class AuthService {
if (!member) {
// invitationId is not valid
showAddProject = true;
} else if (userCreated && member?._id) {
} else if (userCreated && member?._id && !member?._userId) {
// accept invitation or add user to project only first time
await this.memberRepository.findOneAndUpdate(
{ _id: member._id },
Expand All @@ -64,7 +66,33 @@ export class AuthService {
user,
userCreated,
showAddProject,
token: await this.getSignedToken(user, member._projectId, member.role),
token: await this.getSignedToken(user, member?._projectId, member?.role),
};
}

async login(email: string, password: string) {
const user = await this.userRepository.findOne({ email });
if (!user) {
throw new IncorrectLoginCredentials();
}

const doesPasswordMatch = bcrypt.compareSync(password, user.password);
if (!doesPasswordMatch) {
throw new IncorrectLoginCredentials();
}

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

return {
user,
showAddProject,
token: await this.getSignedToken(user, member?._projectId, member?.role),
};
}

Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/app/auth/usecases/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { RegisterUserCommand } from './register-user/register-user.command';
import { RegisterUser } from './register-user/register-user.usecase';
import { LoginUser } from './login-user/login-user.usecase';
import { LoginUserCommand } from './login-user/login-user.command';

export const USE_CASES = [
RegisterUser,
LoginUser,
//
];

export { RegisterUser, RegisterUserCommand };
export { RegisterUser, RegisterUserCommand, LoginUserCommand, LoginUser };
12 changes: 12 additions & 0 deletions apps/api/src/app/auth/usecases/login-user/login-user.command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { IsDefined, IsString, IsEmail } from 'class-validator';
import { BaseCommand } from '@shared/commands/base.command';

export class LoginUserCommand extends BaseCommand {
@IsEmail()
@IsDefined()
email: string;

@IsString()
@IsDefined()
password: string;
}
11 changes: 11 additions & 0 deletions apps/api/src/app/auth/usecases/login-user/login-user.usecase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Injectable } from '@nestjs/common';
import { AuthService } from '../../services/auth.service';
import { LoginUserCommand } from './login-user.command';

@Injectable()
export class LoginUser {
constructor(private authService: AuthService) {}
execute(command: LoginUserCommand) {
return this.authService.login(command.email, command.password);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class RegisterUser {
avatar_url: CONSTANTS.DEFAULT_USER_AVATAR,
password: bcrypt.hashSync(command.password, CONSTANTS.PASSWORD_SALT),
},
validateUniqueEmail: false,
validateUniqueEmail: true,
});
}
}
1 change: 1 addition & 0 deletions apps/api/src/app/shared/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const APIMessages = {
PROJECT_NOT_ASSIGNED: 'Project is not assigned to you',
USER_NOT_FOUND: 'User is not found',
UNIQUE_EMAIL: 'Email address already in use',
INCORRECT_LOGIN_CREDENTIALS: 'Incorrect email or password provided',
};

export const CONSTANTS = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { BadRequestException } from '@nestjs/common';
import { APIMessages } from '../constants';

export class IncorrectLoginCredentials extends BadRequestException {
constructor() {
super(APIMessages.INCORRECT_LOGIN_CREDENTIALS);
}
}
2 changes: 1 addition & 1 deletion libs/dal/src/repositories/member/member.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ interface IMemberDocument extends MemberEntity, Document {
}

// eslint-disable-next-line @typescript-eslint/naming-convention
export const Member = (models.Upload as Model<IMemberDocument>) || model<IMemberDocument>('Member', memberSchema);
export const Member = (models.Member as Model<IMemberDocument>) || model<IMemberDocument>('Member', memberSchema);