44 lines
914 B
TypeScript
44 lines
914 B
TypeScript
import bcrypt from "bcrypt";
|
|
import jwt from "jsonwebtoken";
|
|
import { ENV } from "./env";
|
|
|
|
const SALT_ROUNDS = 10;
|
|
|
|
/**
|
|
* Hashe un mot de passe avec bcrypt
|
|
*/
|
|
export async function hashPassword(password: string): Promise<string> {
|
|
return bcrypt.hash(password, SALT_ROUNDS);
|
|
}
|
|
|
|
/**
|
|
* Vérifie un mot de passe contre son hash
|
|
*/
|
|
export async function verifyPassword(
|
|
password: string,
|
|
hash: string
|
|
): Promise<boolean> {
|
|
return bcrypt.compare(password, hash);
|
|
}
|
|
|
|
/**
|
|
* Génère un token JWT pour un utilisateur
|
|
*/
|
|
export function generateToken(userId: number): string {
|
|
return jwt.sign({ userId }, ENV.jwtSecret, {
|
|
expiresIn: "30d",
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Vérifie et décode un token JWT
|
|
*/
|
|
export function verifyToken(token: string): { userId: number } | null {
|
|
try {
|
|
const decoded = jwt.verify(token, ENV.jwtSecret) as { userId: number };
|
|
return decoded;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|