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

153 refator refresh token and callback #155

Merged
merged 3 commits into from
Jan 16, 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 .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ module.exports = {
'@typescript-eslint/no-floating-promises': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'nestjs/use-validation-pipe': 'off',
'import/order': [
'warn',
{
Expand Down
11 changes: 1 addition & 10 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common'

import { Environment } from '@config/environment'
import { AppModule } from '@modules/app'
import { AuthenticationType } from '@modules/auth/enums'
import { BEARER } from '@modules/auth/constants'

async function bootstrap() {
Expand All @@ -22,15 +21,7 @@ async function bootstrap() {
scheme: BEARER,
bearerFormat: 'JWT',
},
AuthenticationType.ACCESS_TOKEN
)
.addBearerAuth(
{
type: 'http',
scheme: BEARER,
bearerFormat: 'JWT',
},
AuthenticationType.REFRESH_TOKEN
BEARER
)
.build()

Expand Down
110 changes: 19 additions & 91 deletions src/modules/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,23 @@ import { Test, TestingModule } from '@nestjs/testing'

import { AuthController } from './auth.controller'
import { SecretData } from './dtos'
import { AuthService } from './auth.service'
import { AuthorizeParams } from './types'

import {
accessToken,
accessTokenMock,
profileMock,
refreshToken,
userMock,
} from '@common/mocks'
import { ProfilesService } from '@modules/profiles'
import { UsersRepository } from '@modules/users'
import { SpotifyAuthService } from '@modules/spotify/auth'
import { SpotifyUsersService } from '@modules/spotify/users'

describe('AuthController', () => {
const redirectUrl = 'http://test.com'

let authController: AuthController
let spotifyAuthService: SpotifyAuthService
let spotifyUsersService: SpotifyUsersService
let profilesService: ProfilesService
let usersRepository: UsersRepository
let authService: AuthService

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
Expand All @@ -44,32 +40,17 @@ describe('AuthController', () => {
},
},
{
provide: ProfilesService,
provide: AuthService,
useValue: {
create: vi.fn(),
},
},
{
provide: UsersRepository,
useValue: {
createUser: vi.fn(),
findOneByProfileId: vi.fn(),
},
},
{
provide: SpotifyUsersService,
useValue: {
profile: vi.fn(),
saveUser: vi.fn(),
},
},
],
}).compile()

authController = module.get(AuthController)
spotifyAuthService = module.get(SpotifyAuthService)
profilesService = module.get(ProfilesService)
usersRepository = module.get(UsersRepository)
spotifyUsersService = module.get(SpotifyUsersService)
authService = module.get(AuthService)
})

test('should be defined', () => {
Expand All @@ -85,83 +66,28 @@ describe('AuthController', () => {

describe('callback', () => {
const code = 'code'
const authorizeParams: AuthorizeParams = {
accessToken,
refreshToken,
id: userMock.id,
}

test('callback should return valid redirect path', async () => {
const tokenSpy = vi
.spyOn(spotifyAuthService, 'token')
.mockResolvedValue(accessTokenMock)
const profileSpy = vi
.spyOn(spotifyUsersService, 'profile')
.mockResolvedValue(profileMock)
const findOneByProfileIdSpy = vi
.spyOn(usersRepository, 'findOneByProfileId')
.mockResolvedValue(userMock)
const saveUserSpy = vi
.spyOn(authService, 'saveUser')
.mockResolvedValue(authorizeParams)

expect(await authController.callback(code)).toEqual({
url: `${redirectUrl}/api/authorize?${new URLSearchParams({
accessToken,
refreshToken,
id: userMock.id,
...authorizeParams,
}).toString()}`,
statusCode: HttpStatus.PERMANENT_REDIRECT,
})
expect(tokenSpy).toHaveBeenCalledWith({ code })
expect(profileSpy).toHaveBeenCalledWith(accessTokenMock)
expect(findOneByProfileIdSpy).toHaveBeenCalledWith(profileMock.id)
})

test('should find profile by id', async () => {
vi.spyOn(spotifyAuthService, 'token').mockResolvedValue(accessTokenMock)
vi.spyOn(spotifyUsersService, 'profile').mockResolvedValue(profileMock)

const findUserByProfileId = vi
.spyOn(usersRepository, 'findOneByProfileId')
.mockResolvedValue(userMock)
const createSpy = vi.spyOn(profilesService, 'create')
const createUserSpy = vi.spyOn(usersRepository, 'createUser')

expect(await authController.callback(code)).toEqual({
url: `${redirectUrl}/api/authorize?${new URLSearchParams({
accessToken,
refreshToken,
id: userMock.id,
}).toString()}`,
statusCode: HttpStatus.PERMANENT_REDIRECT,
})
expect(findUserByProfileId).toHaveBeenCalledWith(profileMock.id)
expect(createSpy).not.toHaveBeenCalled()
expect(createUserSpy).not.toHaveBeenCalled()
})

test('should create profile and user', async () => {
vi.spyOn(spotifyAuthService, 'token').mockResolvedValue(accessTokenMock)
vi.spyOn(spotifyUsersService, 'profile').mockResolvedValue(profileMock)

const findUserByProfileId = vi.spyOn(
usersRepository,
'findOneByProfileId'
)
const createSpy = vi
.spyOn(profilesService, 'create')
.mockResolvedValue(profileMock)
const createUserSpy = vi
.spyOn(usersRepository, 'createUser')
.mockResolvedValue(userMock)

expect(await authController.callback(code)).toEqual({
url: `${redirectUrl}/api/authorize?${new URLSearchParams({
accessToken,
refreshToken,
id: userMock.id,
}).toString()}`,
statusCode: HttpStatus.PERMANENT_REDIRECT,
})
expect(findUserByProfileId).toHaveBeenCalledWith(profileMock.id)
expect(createSpy).toHaveBeenCalledWith(profileMock)
expect(createUserSpy).toHaveBeenCalledWith({
profile: profileMock,
refreshToken,
})
expect(saveUserSpy).toHaveBeenCalledWith(accessTokenMock)
})
})

Expand All @@ -174,6 +100,8 @@ describe('AuthController', () => {

vi.spyOn(spotifyAuthService, 'token').mockResolvedValue(accessTokenMock)

expect(await authController.refresh(refreshToken)).toEqual(secretDataMock)
expect(await authController.refresh({ refreshToken })).toEqual(
secretDataMock
)
})
})
68 changes: 19 additions & 49 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import {
Body,
Controller,
Get,
HttpStatus,
Inject,
Post,
Query,
Redirect,
forwardRef,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import {
ApiBody,
ApiExcludeEndpoint,
ApiOkResponse,
ApiOperation,
Expand All @@ -17,15 +18,11 @@ import {

import { spotifyAuthorizationScopes } from './config'
import { RedirectResponse } from './types'
import { Token, ApiAuth } from './decorators'
import { SecretData } from './dtos'
import { RefreshToken, SecretData } from './dtos'
import { AuthService } from './auth.service'

import { SpotifyAuthService } from '@modules/spotify/auth'
import { Environment } from '@config/environment'
import { AuthenticationType } from '@modules/auth/enums'
import { UsersRepository } from '@modules/users'
import { ProfilesService } from '@modules/profiles'
import { SpotifyUsersService } from '@modules/spotify/users'
import { adaptSecretData } from '@common/adapters'

const {
Expand All @@ -40,11 +37,8 @@ const {
export class AuthController {
constructor(
private readonly configService: ConfigService,
@Inject(forwardRef(() => ProfilesService))
private readonly profilesService: ProfilesService,
private readonly usersRepository: UsersRepository,
private readonly spotifyAuthService: SpotifyAuthService,
private readonly spotifyUsersService: SpotifyUsersService
private readonly authService: AuthService,
private readonly spotifyAuthService: SpotifyAuthService
) {}

@Get('login')
Expand Down Expand Up @@ -75,53 +69,29 @@ export class AuthController {
const token = await this.spotifyAuthService.token({
code,
})
const spotifyProfile = await this.spotifyUsersService.profile(token)

const foundUser = await this.usersRepository.findOneByProfileId(
spotifyProfile.id
)

const { access_token: accessToken, refresh_token: refreshToken } = token

if (refreshToken) {
let id: string

if (foundUser) {
id = foundUser.id
} else {
const profile = await this.profilesService.create(spotifyProfile)

const { id: createdUserId } = await this.usersRepository.createUser({
profile,
refreshToken,
})

id = createdUserId
}

return {
url: `${this.configService.get(
CLIENT_CALLBACK_URL
)}/api/authorize?${new URLSearchParams({
accessToken,
refreshToken,
id,
}).toString()}`,
statusCode: HttpStatus.PERMANENT_REDIRECT,
}
return {
url: `${this.configService.get(
CLIENT_CALLBACK_URL
)}/api/authorize?${new URLSearchParams({
...(await this.authService.saveUser(token)),
}).toString()}`,
statusCode: HttpStatus.PERMANENT_REDIRECT,
}
}

@Get('refresh')
@Post('refresh')
@ApiOperation({
summary: 'Refreshing access token.',
})
@ApiAuth(AuthenticationType.REFRESH_TOKEN)
@ApiOkResponse({
description: 'Access token has been succesfully refreshed',
type: SecretData,
})
refresh(@Token() refreshToken: string) {
@ApiBody({
type: RefreshToken,
})
refresh(@Body() { refreshToken }: RefreshToken) {
return this.spotifyAuthService.token({ refreshToken }).then(adaptSecretData)
}
}
Loading
Loading