Files
parcer/server/src/utils/auth.ts

45 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-09-23 23:44:21 +05:30
import bcrypt from "bcrypt";
2024-10-05 15:42:06 +05:30
import crypto from 'crypto';
import { getEnvVariable } from './env';
2024-09-23 23:44:21 +05:30
2024-09-25 18:43:43 +05:30
export const hashPassword = (password: string): Promise<string> => {
2024-09-23 23:44:21 +05:30
return new Promise((resolve, reject) => {
bcrypt.genSalt(12, (err, salt) => {
if (err) {
reject(err)
}
bcrypt.hash(password, salt, (err, hash) => {
if (err) {
reject(err)
}
resolve(hash)
})
})
})
}
// password from frontend and hash from database
2024-09-25 19:19:06 +05:30
export const comparePassword = (password: string, hash: string): Promise<boolean> => {
2024-09-23 23:44:21 +05:30
return bcrypt.compare(password, hash)
2024-10-05 15:42:06 +05:30
}
2024-10-05 15:58:32 +05:30
export const encrypt = (text: string): string => {
const ivLength = parseInt(getEnvVariable('IV_LENGTH'), 10);
const iv = crypto.randomBytes(ivLength);
const algorithm = getEnvVariable('ALGORITHM');
const key = Buffer.from(getEnvVariable('ENCRYPTION_KEY'), 'hex');
const cipher = crypto.createCipheriv(algorithm, key, iv);
2024-10-05 15:42:06 +05:30
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return `${iv.toString('hex')}:${encrypted}`;
2024-10-05 15:42:32 +05:30
};
2024-10-05 15:58:32 +05:30
export const decrypt = (encryptedText: string): string => {
2024-10-05 15:42:32 +05:30
const [iv, encrypted] = encryptedText.split(':');
const algorithm = getEnvVariable('ALGORITHM');
const key = Buffer.from(getEnvVariable('ENCRYPTION_KEY'), 'hex');
const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(iv, 'hex'));
2024-10-05 15:42:32 +05:30
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
2024-10-05 15:42:06 +05:30
};