This repository has been archived by the owner on Apr 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
23 changed files
with
215 additions
and
15 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
POSTGRES_USER=postgres | ||
POSTGRES_PASSWORD=12345678 | ||
POSTGRES_DB=diary-db | ||
JWT_SECRET=itssecret | ||
|
||
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}?schema=public |
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 |
---|---|---|
|
@@ -44,5 +44,4 @@ describe('userService', () => { | |
expect(user).not.toBeNull() | ||
expect(user?.name).toBe('Test User') | ||
}) | ||
|
||
}) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import { ApiResponse, ContextWith } from '../types' | ||
import { authenticateUser } from '@services' | ||
|
||
interface Body { | ||
password: string | ||
login: string | ||
id: number | ||
} | ||
|
||
export const postAuth = async ({ | ||
body, | ||
jwt, | ||
setCookie, | ||
cookie | ||
}: ContextWith<never, Body>): Promise<ApiResponse<string>> => { | ||
if (typeof body === 'undefined') { | ||
return { | ||
success: false, | ||
data: 'Body is required' | ||
} | ||
} | ||
|
||
const { login, password, id } = body | ||
|
||
const { success } = await authenticateUser(id, login, password) | ||
|
||
setCookie('auth', await jwt.sign(body), { | ||
httpOnly: true, | ||
maxAge: 7 * 86400, | ||
secure: true | ||
}) | ||
|
||
const verify = await jwt.verify(cookie.auth) | ||
|
||
console.debug('verify', verify) | ||
console.debug('cookie.auth', cookie.auth) | ||
console.debug('success', success) | ||
|
||
return { | ||
success, | ||
} | ||
} |
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 |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from './userHandler' | ||
export * from './authHandler' |
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
Empty file.
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,19 @@ | ||
import { postAuth } from '@handlers' | ||
import Elysia, { t } from 'elysia' | ||
import { authBody } from './authSchema' | ||
import { getUserById } from '@services' | ||
|
||
const app = new Elysia().post('/auth', postAuth, { | ||
body: t.Object(authBody), | ||
// TODO: move to custom plugin (middleware) | ||
beforeHandle: async (context) => { | ||
const user = await getUserById(context.body.id) | ||
|
||
if (!user || user.id !== context.body.id || user.login !== context.body.login) { | ||
context.set.status = 400 | ||
return 'Bad request' | ||
} | ||
} | ||
}) | ||
|
||
export default app |
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,7 @@ | ||
import { t } from 'elysia' | ||
|
||
export const authBody = { | ||
id: t.Number(), | ||
password: t.String(), | ||
login: t.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,39 @@ | ||
import { comparePassword } from '@utils' | ||
import { ApiResponse } from '../types' | ||
import { PrismaClient } from '@prisma/client' | ||
|
||
const prisma = new PrismaClient() | ||
|
||
export const authenticateUser = async ( | ||
id: number, | ||
login: string, | ||
password: string, | ||
): Promise<ApiResponse<string>> => { | ||
console.log(id) | ||
console.log(password) | ||
Check failure Code scanning / CodeQL Clear-text logging of sensitive information High
This logs sensitive data returned by
an access to password Error loading related location Loading This logs sensitive data returned by an access to password Error loading related location Loading |
||
console.log(login) | ||
const user = await prisma.user.findUnique({ | ||
where: { | ||
email: login, | ||
id | ||
}, | ||
}) | ||
|
||
const isValidPassword = await comparePassword( | ||
password, | ||
user!.salt, | ||
user!.password, | ||
) | ||
|
||
if (!isValidPassword) { | ||
return { | ||
success: false, | ||
data: 'Invalid password', | ||
} | ||
} | ||
|
||
return { | ||
success: true, | ||
data: 'Password', | ||
} | ||
} |
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 |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from './userService' | ||
export * from './authService' |
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,17 @@ | ||
import { pbkdf2Hash } from './pbkdf2Hash' | ||
|
||
/** | ||
* Сравнивает пароль с хешем и солью для проверки соответствия. | ||
* @param password - Пароль, который нужно сравнить. | ||
* @param salt - Соль, использованная при хешировании. | ||
* @param hash - Хеш, с которым сравнивается пароль. | ||
* @returns Промис, который разрешается булевым значением, указывающим соответствие пароля хешу. | ||
*/ | ||
export const comparePassword = async ( | ||
password: string, | ||
salt: string, | ||
hash: string | ||
): Promise<boolean> => { | ||
const derivedKey = await pbkdf2Hash(password, salt) | ||
return hash === derivedKey | ||
} |
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 |
---|---|---|
@@ -1,7 +1,7 @@ | ||
export const getRandomID = () => { | ||
let array = new Uint32Array(1) | ||
const array = new Uint32Array(1) | ||
crypto.getRandomValues(array) | ||
|
||
const maxIntValue = 2147483647 | ||
return array[0] % maxIntValue | ||
} |
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,15 @@ | ||
import { randomBytes } from 'crypto' | ||
import { pbkdf2Hash } from './pbkdf2Hash' | ||
|
||
/** | ||
* Хеширует пароль с использованием PBKDF2 и случайно сгенерированной соли. | ||
* @param password - Пароль, который нужно захешировать. | ||
* @returns Промис, который разрешается объектом с хешем и солью. | ||
*/ | ||
export const hashPassword = async ( | ||
password: string | ||
): Promise<{ hash: string; salt: string }> => { | ||
const salt = randomBytes(16).toString('hex') | ||
const hash = await pbkdf2Hash(password, salt) | ||
return { hash, salt } | ||
} |
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 |
---|---|---|
@@ -1,2 +1,6 @@ | ||
export * from './handleErrors' | ||
export * from './getRandomNumber' | ||
export * from './pbkdf2Hash' | ||
export * from './md5hash' | ||
export * from './hashPassword' | ||
export * from './comparePassword' |
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,11 @@ | ||
import { createHash } from 'crypto' | ||
|
||
/** | ||
* Генерирует MD5-хеш для заданного текста. | ||
* @param text - Текст, который нужно захешировать. | ||
* @returns MD5-хеш введенного текста. | ||
*/ | ||
function md5hash(text: string) { | ||
// Создаем объект хеша MD5, обновляем его текстом и получаем результат в шестнадцатеричном формате. | ||
return createHash('md5').update(text).digest('hex') | ||
} |
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,22 @@ | ||
import { pbkdf2 } from 'crypto' | ||
|
||
/** | ||
* Хеширует данные с использованием PBKDF2. | ||
* @param password - Данные для хеширования (например, пароль). | ||
* @param salt - Соль для хеширования. | ||
* @returns Промис, который разрешается строкой с хешем. | ||
*/ | ||
export const pbkdf2Hash = async ( | ||
password: string, | ||
salt: string | ||
): Promise<string> => { | ||
return new Promise((resolve, reject) => { | ||
pbkdf2(password, salt, 1000, 64, 'sha512', (error, derivedKey) => { | ||
if (error) { | ||
return reject(error) | ||
} | ||
|
||
return resolve(derivedKey.toString('hex')) | ||
}) | ||
}) | ||
} |
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 |
---|---|---|
@@ -1,5 +1,7 @@ | ||
export interface User { | ||
id: number | ||
email: string | ||
name?: string | null | ||
password: string | ||
salt: string | ||
name?: 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