-
Notifications
You must be signed in to change notification settings - Fork 0
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
[Backend] Implement Google OAuth #21
Merged
Merged
Changes from 11 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0171364
feat(api): :package: add passport libs
rasouza 433accc
feat(api): create Auth and User modules
rasouza 508d9cf
chore(api): :truck: rename dotenv files for IDE
rasouza c3a3a8c
chore(api): :truck: move global error handler to a proper folder
rasouza a9b0d6f
chore(api): :truck: rename Subscription serializer to become a proper…
rasouza 4162d7d
feat(api): :sparkles: implement Google OAuth2
rasouza cef400f
refactor(api): :sparkles: add profile picture field for users
rasouza 3238e7e
feat(api): :sparkles: implement JWT for authentication
rasouza 33cb851
test(api): :white_check_mark: add unit tests for auth
rasouza 384281d
test(api): :white_check_mark: add integration test for Google OAuth
rasouza b5d5583
fix(api): :bug: remove profile picture from JWT
rasouza 79d266b
Merge branch 'main' into feature/auth-passport
rasouza 055a2eb
ci(api): :green_heart: fix .env file for testing
rasouza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
DATABASE_URL="postgresql://test:test@localhost:5433/tests" | ||
|
||
OAUTH_GOOGLE_CLIENT_ID="google-client-id" | ||
OAUTH_GOOGLE_CLIENT_SECRET="google-client-secret" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
/* eslint-disable @typescript-eslint/unbound-method */ | ||
import { TestBed } from '@automock/jest' | ||
import { createMock } from '@golevelup/ts-jest' | ||
import { Request, Response } from 'express' | ||
|
||
import { AuthController } from './auth.controller' | ||
import { AuthService } from './auth.service' | ||
|
||
describe('AuthController', () => { | ||
let controller: AuthController | ||
let authService: jest.Mocked<AuthService> | ||
|
||
beforeEach(async () => { | ||
const { unit, unitRef } = TestBed.create(AuthController).compile() | ||
|
||
controller = unit | ||
authService = unitRef.get(AuthService) | ||
}) | ||
|
||
it('should be defined', () => { | ||
expect(controller).toBeDefined() | ||
}) | ||
|
||
it('should set cookies on google login callback', async () => { | ||
const req = createMock<Request>({ | ||
user: { | ||
email: 'test-email', | ||
name: 'test-name', | ||
picture: 'test-picture' | ||
} | ||
}) | ||
|
||
const res = createMock<Response>() | ||
jest.spyOn(authService, 'signIn').mockResolvedValue('token') | ||
|
||
await controller.googleLoginCallback(req, res) | ||
|
||
expect(authService.signIn).toHaveBeenCalledWith({ | ||
email: 'test-email', | ||
name: 'test-name', | ||
picture: 'test-picture' | ||
}) | ||
|
||
expect(res.cookie).toHaveBeenCalledWith('access_token', 'token') | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { Controller, Req, Get, UseGuards, Res } from '@nestjs/common' | ||
import { Request, Response } from 'express' | ||
|
||
import { GoogleOauthGuard } from './guards/google.guard' | ||
import { AuthService } from './auth.service' | ||
import { Profile } from './interfaces/profile' | ||
|
||
@Controller('auth') | ||
export class AuthController { | ||
constructor (private readonly authService: AuthService) {} | ||
@Get('google') | ||
@UseGuards(GoogleOauthGuard) | ||
async googleLogin () { | ||
} | ||
|
||
@Get('google/callback') | ||
@UseGuards(GoogleOauthGuard) | ||
async googleLoginCallback (@Req() req: Request, @Res({ passthrough: true }) res: Response) { | ||
const token = await this.authService.signIn(req.user as Profile) | ||
|
||
res.cookie('access_token', token) | ||
|
||
return null | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { Module } from '@nestjs/common' | ||
import { PassportModule } from '@nestjs/passport' | ||
import { JwtModule } from '@nestjs/jwt' | ||
import { ConfigService } from '@nestjs/config' | ||
|
||
import { UsersModule } from '../users/users.module' | ||
|
||
import { AuthService } from './auth.service' | ||
import { AuthController } from './auth.controller' | ||
import { GoogleStrategy } from './strategies/google.strategy' | ||
|
||
@Module({ | ||
imports: [ | ||
UsersModule, | ||
PassportModule, | ||
JwtModule.registerAsync({ | ||
useFactory: (config: ConfigService) => ({ | ||
global: true, | ||
secret: config.get<string>('JWT_SECRET'), | ||
signOptions: { expiresIn: config.get<string>('JWT_EXPIRES_IN') } | ||
}), | ||
inject: [ConfigService] | ||
}) | ||
], | ||
providers: [AuthService, GoogleStrategy], | ||
controllers: [AuthController] | ||
}) | ||
export class AuthModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { TestBed } from '@automock/jest' | ||
import { JwtService } from '@nestjs/jwt' | ||
|
||
import { UsersService } from '../users/users.service' | ||
|
||
import { AuthService } from './auth.service' | ||
|
||
describe('AuthService', () => { | ||
let service: AuthService | ||
|
||
beforeEach(async () => { | ||
const { unit } = TestBed.create(AuthService) | ||
.mock(UsersService) | ||
.using({ | ||
findOrCreate: jest.fn().mockResolvedValue({ id: 1, email: '[email protected]' }) | ||
}) | ||
.mock(JwtService) | ||
.using({ | ||
sign: jest.fn().mockReturnValue('jwt') | ||
}) | ||
.compile() | ||
|
||
service = unit | ||
}) | ||
|
||
it('should be defined', () => { | ||
expect(service).toBeDefined() | ||
}) | ||
|
||
it('should return a user and token', async () => { | ||
const user = await service.signIn({ | ||
email: 'test', | ||
name: 'test', | ||
picture: 'test' | ||
}) | ||
expect(user).toEqual('jwt') | ||
}) | ||
|
||
it('should throw an error if no profile is provided', async () => { | ||
try { | ||
// @ts-expect-error: Testing OAuth provider does not return profile | ||
await service.signIn(null) | ||
} catch (e) { | ||
expect(e.message).toEqual('Unauthenticated') | ||
} | ||
}) | ||
|
||
it('should throw an error if no email is provided', async () => { | ||
try { | ||
await service.signIn({ | ||
// @ts-expect-error: Testing when OAuth provider does not return email | ||
email: null, | ||
name: 'test', | ||
picture: 'test' | ||
}) | ||
} catch (e) { | ||
expect(e.message).toEqual('Email not found') | ||
} | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { BadRequestException, Injectable } from '@nestjs/common' | ||
import { JwtService } from '@nestjs/jwt' | ||
|
||
import { UsersService } from '../users/users.service' | ||
|
||
import { Profile } from './interfaces/profile' | ||
|
||
@Injectable() | ||
export class AuthService { | ||
constructor (private readonly usersService: UsersService, private readonly jwtService: JwtService) { | ||
} | ||
|
||
generateJwt (payload: object) { | ||
return this.jwtService.sign(payload) | ||
} | ||
|
||
// TODO: Implement ProfileDTO for improved validation | ||
async signIn (profile: Profile) { | ||
if (!profile) { | ||
throw new BadRequestException('Unauthenticated') | ||
} | ||
|
||
if (!profile.email) { | ||
throw new BadRequestException('Email not found') | ||
} | ||
|
||
const user = await this.usersService.findOrCreate({ | ||
email: profile.email, | ||
name: profile.name, | ||
picture: profile.picture | ||
}) | ||
|
||
return this.generateJwt({ | ||
sub: user.id, | ||
email: user.email | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import { Injectable } from '@nestjs/common' | ||
import { AuthGuard } from '@nestjs/passport' | ||
|
||
@Injectable() | ||
export class GoogleOauthGuard extends AuthGuard('google') {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import { Injectable } from '@nestjs/common' | ||
import { AuthGuard } from '@nestjs/passport' | ||
|
||
@Injectable() | ||
export class JwtAuthGuard extends AuthGuard('jwt') {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export interface JwtPayload { | ||
sub: number | ||
email: string | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
export interface Profile { | ||
name: string | ||
email: string | ||
picture?: string | ||
provider?: string | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I feel like I'm swapping between yarn and npm, but I guess we're using npm now? 😃
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hahaha sorry I should have left a note here.. yarn was failing to capture the terminal session when using the REPL. For some reason, running this command specifically with npm works and I didn't want to put effort to investigate why and fix it.
We're definitely using yarn and you should still run
yarn console
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's keep a proper ticket here :D #23