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(auth): Updated authentication logic #122

Merged
merged 7 commits into from
Jun 25, 2024
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: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"cSpell.words": ["onboarded"]
}
31 changes: 5 additions & 26 deletions src/auth/auth.e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,44 +41,24 @@ describe('Auth Controller Tests', () => {
it('should be able to sign up using email', async () => {
const response = await app.inject({
method: 'POST',
url: '/auth/sign-up',
url: '/auth/email',
payload: {
email: '[email protected]',
},
});

expect(response.statusCode).toEqual(201);
expect(response.json().email).toEqual('[email protected]');
});

it('should be able to sign in using email', async () => {
await prisma.user.create({
data: {
email: '[email protected]',
isEmailVerified: true,
authType: AuthType.EMAIL,
},
expect(response.json()).toEqual({
status: 'success',
});

const response = await app.inject({
method: 'POST',
url: '/auth/sign-in',
payload: {
email: '[email protected]',
},
});

expect(response.statusCode).toEqual(201);
expect(response.json().email).toEqual('[email protected]');
});

it('should send verification code to email on sign up', async () => {
await app.inject({
method: 'POST',
url: '/auth/sign-up',
url: '/auth/email',
payload: {
email: '[email protected]',
password: 'Password123',
},
});

Expand Down Expand Up @@ -123,10 +103,9 @@ describe('Auth Controller Tests', () => {
// Sign up
await app.inject({
method: 'POST',
url: '/auth/sign-up',
url: '/auth/email',
payload: {
email: '[email protected]',
password: 'Password123',
},
});

Expand Down
37 changes: 9 additions & 28 deletions src/auth/controller/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,10 @@ import { Public } from '../../decorators/public.decorator';
import { FacebookOAuthStrategyFactory } from '../../oauth/factory/facebook/facebook-strategy.factory';
import { LinkedInOAuthStrategyFactory } from '../../oauth/factory/linkedin/linkedin-strategy.factory';
import { AppleOAuthStrategyFactory } from '../../oauth/factory/apple/apple-strategy.factory';
import { SignupDto } from '../dto/signup.dto';
import { SigninDto } from '../dto/signin.dto';
import { UserDetailsDto } from '../dto/user-details.dto';
import { EmailVerificationDto } from '../dto/email-verification.dto';
import {
ApiBadRequestResponse,
ApiConflictResponse,
ApiCreatedResponse,
ApiNoContentResponse,
ApiNotFoundResponse,
Expand All @@ -37,6 +35,7 @@ import { LowercasePipe } from '../../common/pipes/lowercase.pipe';
import { GithubOAuthStrategyFactory } from '../../oauth/factory/github/github-strategy.factory';
import { CurrentUser } from '../../decorators/current-user.decorator';
import { SocialAccountType, User } from '@prisma/client';
import { BypassOnboardingCheck } from '../../decorators/bypass-onboarding.decorator';

@Controller('auth')
@ApiTags('Auth Controller')
Expand Down Expand Up @@ -313,29 +312,10 @@ export class AuthController {
}

@Public()
@Post('sign-up')
@Post('email')
@ApiOperation({
summary: 'Sign up',
description: 'Sign up with email',
})
@ApiCreatedResponse({
description: 'User signed up successfully',
})
@ApiConflictResponse({
description: 'User with this email already exists',
})
async signUp(@Body() dto: SignupDto) {
return await this.authService.signUp(dto);
}

@Public()
@Post('sign-in')
@ApiOperation({
summary: 'Sign in',
description: 'Sign in with email',
})
@ApiNotFoundResponse({
description: 'User not found',
summary: 'Sign in or sign up with email',
description: 'Sign in or sign up with email',
})
@ApiCreatedResponse({
description: 'User signed in successfully',
Expand All @@ -347,8 +327,8 @@ export class AuthController {
},
},
})
async signIn(@Body() dto: SigninDto) {
return await this.authService.signIn(dto);
async sendVerificationCode(@Body() dto: UserDetailsDto) {
return await this.authService.sendVerificationCode(dto);
}

@Public()
Expand Down Expand Up @@ -396,9 +376,10 @@ export class AuthController {
},
})
async verifyEmail(@Body() dto: EmailVerificationDto) {
return await this.authService.verifyEmail(dto.email, dto.code);
return await this.authService.verifyEmail(dto);
}

@BypassOnboardingCheck()
@Get('/social-accounts')
async getSocialAccounts(@CurrentUser() user: User) {
return this.authService.getSocialAccounts(user.id);
Expand Down
16 changes: 0 additions & 16 deletions src/auth/dto/signup.dto.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsEmail } from 'class-validator';

export class SigninDto {
export class UserDetailsDto {
@IsEmail()
@Transform(({ value }) => value.toLowerCase())
@ApiProperty({
Expand Down
13 changes: 13 additions & 0 deletions src/auth/guard/auth/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import {
ExecutionContext,
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../../../decorators/public.decorator';
import { PrismaService } from '../../../prisma/prisma.service';
import { User } from '@prisma/client';
import { ONBOARDING_BYPASSED } from '../../../decorators/bypass-onboarding.decorator';

const X_E2E_USER_EMAIL = 'x-e2e-user-email';

Expand Down Expand Up @@ -74,6 +76,17 @@ export class AuthGuard implements CanActivate {
}
}

const onboardingBypassed =
this.reflector.getAllAndOverride<boolean>(ONBOARDING_BYPASSED, [
context.getHandler(),
context.getClass(),
]) ?? false;

// If the onboarding is not finished, we throw an UnauthorizedException.
if (!onboardingBypassed && !user.onboarded) {
throw new UnauthorizedException('Onboarding not finished');
}

// We attach the user to the request object.
request['user'] = user;
return true;
Expand Down
Loading
Loading