Skip to content

Commit

Permalink
refactor(modules/auth): move save user login to authService
Browse files Browse the repository at this point in the history
  • Loading branch information
Mnigos committed Jan 16, 2024
1 parent a9d5fe7 commit e69cde8
Show file tree
Hide file tree
Showing 6 changed files with 132 additions and 315 deletions.
106 changes: 16 additions & 90 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 Down
53 changes: 10 additions & 43 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import {
Controller,
Get,
HttpStatus,
Inject,
Post,
Query,
Redirect,
forwardRef,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import {
Expand All @@ -21,12 +19,10 @@ import {
import { spotifyAuthorizationScopes } from './config'
import { RedirectResponse } from './types'
import { RefreshToken, SecretData } from './dtos'
import { AuthService } from './auth.service'

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

const {
Expand All @@ -41,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 @@ -76,40 +69,14 @@ 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,
}
}

Expand Down
Loading

0 comments on commit e69cde8

Please sign in to comment.