-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.js
More file actions
34 lines (26 loc) · 854 Bytes
/
jwt.js
File metadata and controls
34 lines (26 loc) · 854 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import dotenv from 'dotenv';
dotenv.config();
const secretKey = process.env.SECRET
const saltRounds = parseInt(process.env.SALT_ROUNDS)
export function generateToken(id) {
const payload = { id};
const options = { expiresIn: '6h' }; // Token expiration time
return jwt.sign(payload, secretKey, options);
}
export function verifyToken(token) {
try {
return jwt.verify(token, secretKey);
} catch (err) {
throw "Unauthorized user"; // Token is invalid or expired
}
}
export async function hashPassword(password) {
const salt = await bcrypt.genSalt(saltRounds)
return bcrypt.hash(password, salt);
}
export async function validateUser(password, hash) {
return bcrypt.compare(password, hash)
}
export default {generateToken, verifyToken, hashPassword, validateUser};