first commit
This commit is contained in:
37
src/utils/crypto.js
Normal file
37
src/utils/crypto.js
Normal file
@@ -0,0 +1,37 @@
|
||||
import bcrypt from 'bcrypt';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { env } from '../config/env.js';
|
||||
|
||||
const TIME_MULTIPLIERS = {
|
||||
ms: 1,
|
||||
s: 1000,
|
||||
m: 60 * 1000,
|
||||
h: 60 * 60 * 1000,
|
||||
d: 24 * 60 * 60 * 1000
|
||||
};
|
||||
|
||||
export const hashPassword = async (password) => bcrypt.hash(password, 10);
|
||||
|
||||
export const comparePassword = async (password, hash) => bcrypt.compare(password, hash);
|
||||
|
||||
export const signToken = (payload, options = {}) =>
|
||||
jwt.sign(payload, env.jwtSecret, {
|
||||
expiresIn: env.jwtExpiresIn,
|
||||
...options
|
||||
});
|
||||
|
||||
export const verifyToken = (token) => jwt.verify(token, env.jwtSecret);
|
||||
|
||||
export const expiresInToMs = (value) => {
|
||||
if (!value) return 0;
|
||||
if (typeof value === 'number') return value * 1000;
|
||||
const trimmed = String(value).trim();
|
||||
const directNumber = Number(trimmed);
|
||||
if (!Number.isNaN(directNumber)) return directNumber * 1000;
|
||||
|
||||
const match = trimmed.match(/^(\d+)(ms|s|m|h|d)$/i);
|
||||
if (!match) return 0;
|
||||
const amount = Number(match[1]);
|
||||
const unit = match[2].toLowerCase();
|
||||
return amount * (TIME_MULTIPLIERS[unit] || 0);
|
||||
};
|
||||
Reference in New Issue
Block a user