Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
chore: lint
Browse files Browse the repository at this point in the history
  • Loading branch information
scffs committed Dec 12, 2023
1 parent 3eab58b commit d1db13e
Show file tree
Hide file tree
Showing 23 changed files with 308 additions and 312 deletions.
2 changes: 1 addition & 1 deletion apps/api/__tests__/i.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from 'bun:test'

test('2 + 2', () => {
expect(2 + 2).toBe(4)
expect(2 + 2).toBe(4)
})
84 changes: 42 additions & 42 deletions apps/api/__tests__/services/auth/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,46 +6,46 @@ import { getTestUser } from '@utils'
const testDb = new PrismaClient()

describe('authenticationService', () => {
afterAll(async () => {
await testDb.$disconnect()
})

beforeEach(async () => {
await testDb.user.deleteMany()
})

it('should fail authentication for a non-existent user', async () => {
const user = await isUserExist(1, 'nonexistent@example.com')

expect(user).toBe(null)
})

it('should fail authentication for an invalid password', async () => {
const id = 1
const testUser = await getTestUser(id)
await testDb.user.create({
data: testUser
})

const result = await authenticateUser(
testUser,
testUser.email,
'wrongpassword'
)
expect(result).toBe(false)
})

it('should authenticate a user with valid credentials', async () => {
const id = 1
const testUser = await getTestUser(id)
await testDb.user.create({
data: testUser
})

/**
* В getTestUser пароль хешируется, но по задумке authenticateUser мы передаем туда пароль в чистом виде.
*/
const result = await authenticateUser(testUser, testUser.email, 'password')
expect(result).toBe(true)
})
afterAll(async () => {
await testDb.$disconnect()
})

beforeEach(async () => {
await testDb.user.deleteMany()
})

it('should fail authentication for a non-existent user', async () => {
const user = await isUserExist(1, 'nonexistent@example.com')

expect(user).toBe(null)
})

it('should fail authentication for an invalid password', async () => {
const id = 1
const testUser = await getTestUser(id)
await testDb.user.create({
data: testUser
})

const result = await authenticateUser(
testUser,
testUser.email,
'wrongpassword'
)
expect(result).toBe(false)
})

it('should authenticate a user with valid credentials', async () => {
const id = 1
const testUser = await getTestUser(id)
await testDb.user.create({
data: testUser
})

/**
* В getTestUser пароль хешируется, но по задумке authenticateUser мы передаем туда пароль в чистом виде.
*/
const result = await authenticateUser(testUser, testUser.email, 'password')
expect(result).toBe(true)
})
})
70 changes: 35 additions & 35 deletions apps/api/__tests__/services/user/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,39 @@ import { getRandomID, getTestUser } from '@utils'
const testDb = new PrismaClient()

describe('userService', () => {
afterAll(async () => {
await testDb.$disconnect()
})

beforeEach(async () => {
await testDb.user.deleteMany()
})

it('getAllUsers should return an array of users', async () => {
const firstID = getRandomID()
const secondID = getRandomID()

await testDb.user.createMany({
data: [await getTestUser(firstID), await getTestUser(secondID)],
skipDuplicates: true
})

const users = await getAllUsers()
expect(users).toHaveLength(2)
expect(users[0].name).toBe(`Test User ${firstID}`)
expect(users[1].name).toBe(`Test User ${secondID}`)
})

it('getUserById should return a user by ID', async () => {
const id = getRandomID()
const data = await getTestUser(id)

await testDb.user.create({
data
})

const user = await getUserById(id)
expect(user).not.toBeNull()
expect(user?.name).toBe(`Test User ${id}`)
})
afterAll(async () => {
await testDb.$disconnect()
})

beforeEach(async () => {
await testDb.user.deleteMany()
})

it('getAllUsers should return an array of users', async () => {
const firstID = getRandomID()
const secondID = getRandomID()

await testDb.user.createMany({
data: [await getTestUser(firstID), await getTestUser(secondID)],
skipDuplicates: true
})

const users = await getAllUsers()
expect(users).toHaveLength(2)
expect(users[0].name).toBe(`Test User ${firstID}`)
expect(users[1].name).toBe(`Test User ${secondID}`)
})

it('getUserById should return a user by ID', async () => {
const id = getRandomID()
const data = await getTestUser(id)

await testDb.user.create({
data
})

const user = await getUserById(id)
expect(user).not.toBeNull()
expect(user?.name).toBe(`Test User ${id}`)
})
})
78 changes: 39 additions & 39 deletions apps/api/__tests__/utils/handleErrors/i.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,43 @@ import { describe, expect, it } from 'bun:test'
import { handleErrors } from '@utils'

describe('handleErrors', () => {
it('should handle VALIDATION error', () => {
const result = handleErrors({
code: 'VALIDATION',
error: new Error('Validation failed')
})

expect(result.message).toBe('Validation error')
expect(result.error).toBeInstanceOf(Error)
})

it('should handle INTERNAL_SERVER_ERROR', () => {
const result = handleErrors({
code: 'INTERNAL_SERVER_ERROR',
error: new Error('Server error')
})

expect(result.message).toBe('Internal Server Error')
expect(result.error).toBeInstanceOf(Error)
})

it('should handle NOT_FOUND error', () => {
const result = handleErrors({
code: 'NOT_FOUND',
error: new Error('Resource not found')
})

expect(result.message).toBe('Not found')
expect(result.error).toBeInstanceOf(Error)
})

it('should handle unknown error', () => {
const result = handleErrors({
code: 'UNKNOWN_ERROR',
error: new Error('Unknown error occurred')
})

expect(result.message).toBe('Unknown error')
expect(result.error).toBeInstanceOf(Error)
})
it('should handle VALIDATION error', () => {
const result = handleErrors({
code: 'VALIDATION',
error: new Error('Validation failed')
})

expect(result.message).toBe('Validation error')
expect(result.error).toBeInstanceOf(Error)
})

it('should handle INTERNAL_SERVER_ERROR', () => {
const result = handleErrors({
code: 'INTERNAL_SERVER_ERROR',
error: new Error('Server error')
})

expect(result.message).toBe('Internal Server Error')
expect(result.error).toBeInstanceOf(Error)
})

it('should handle NOT_FOUND error', () => {
const result = handleErrors({
code: 'NOT_FOUND',
error: new Error('Resource not found')
})

expect(result.message).toBe('Not found')
expect(result.error).toBeInstanceOf(Error)
})

it('should handle unknown error', () => {
const result = handleErrors({
code: 'UNKNOWN_ERROR',
error: new Error('Unknown error occurred')
})

expect(result.message).toBe('Unknown error')
expect(result.error).toBeInstanceOf(Error)
})
})
10 changes: 5 additions & 5 deletions apps/api/__tests__/utils/hashPassword/i.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { describe, expect, it } from 'bun:test'
import { hashPassword, pbkdf2Hash } from '@utils'

describe('hashPassword', () => {
it('should hash password with random salt', async () => {
const result = await hashPassword('password')
const expectedHash = await pbkdf2Hash('password', result.salt)
it('should hash password with random salt', async () => {
const result = await hashPassword('password')
const expectedHash = await pbkdf2Hash('password', result.salt)

expect(result.hash).toMatch(expectedHash)
})
expect(result.hash).toMatch(expectedHash)
})
})
14 changes: 7 additions & 7 deletions apps/api/biome.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"formatter": {
"ignore": ["./dist"]
},
"linter": {
"ignore": ["./dist"]
},
"extends": ["../../biome.json"]
"formatter": {
"ignore": ["./dist"]
},
"linter": {
"ignore": ["./dist"]
},
"extends": ["../../biome.json"]
}
92 changes: 46 additions & 46 deletions apps/api/src/handlers/auth/authHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,54 +2,54 @@ import { authenticateUser, isUserExist } from '@services'
import { ApiResponse, ContextWith } from '@types'

interface Body {
password: string
login: string
id: number
password: string
login: string
id: number
}

export const postAuth = async ({
body,
jwt,
set
body,
jwt,
set
}: ContextWith<never, Body>): Promise<ApiResponse<string>> => {
const { login, password, id } = body

const user = await isUserExist(id, login)

if (!user) {
set.status = 'Bad Request'

return {
success: false,
data: 'Bad Request'
}
}

const isAuth = await authenticateUser(user, login, password)

if (!isAuth || !jwt) {
set.status = 'Bad Request'

return {
success: false
}
}

/**
* jwt.sign() будет возвращать одну и ту же куку в течении даты ее жизни
*
* Если хочется генерировать новую на каждую авторизацию (например), то можно использовать такой код
*
* setCookie('auth', await jwt.sign(body), {
* httpOnly: true,
* maxAge: 7 * 86400,
* })
*
* @see https://elysiajs.com/plugins/jwt.html#jwt-plugin
*/
await jwt.sign(body)

return {
success: true
}
const { login, password, id } = body

const user = await isUserExist(id, login)

if (!user) {
set.status = 'Bad Request'

return {
success: false,
data: 'Bad Request'
}
}

const isAuth = await authenticateUser(user, login, password)

if (!isAuth || !jwt) {
set.status = 'Bad Request'

return {
success: false
}
}

/**
* jwt.sign() будет возвращать одну и ту же куку в течении даты ее жизни
*
* Если хочется генерировать новую на каждую авторизацию (например), то можно использовать такой код
*
* setCookie('auth', await jwt.sign(body), {
* httpOnly: true,
* maxAge: 7 * 86400,
* })
*
* @see https://elysiajs.com/plugins/jwt.html#jwt-plugin
*/
await jwt.sign(body)

return {
success: true
}
}
Loading

0 comments on commit d1db13e

Please sign in to comment.