-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
60 lines (52 loc) · 1.44 KB
/
auth.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const secretKey = 'BM8yoeRub9wB8kkYPLtBwp/CapXFogakbPF+tsCKT7E=';
const generateJwtToken = (user) => {
const payload = {
id: user.id,
username: user.username,
};
return jwt.sign(payload, secretKey, { expiresIn: '1h' });
};
passport.use(
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: secretKey,
},
(payload, done) => {
// TODO: Implement user lookup and validation
done(null, false);
}
)
);
const authenticateJwt = (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user) => {
if (err) {
console.error('Error authenticating JWT:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else if (!user) {
res.status(401).json({ error: 'Unauthorized' });
} else {
req.user = user;
next();
}
})(req, res, next);
};
const encryptPassword = async (password) => {
const saltRounds = 10;
const salt = await bcrypt.genSalt(saltRounds);
const hash = await bcrypt.hash(password, salt);
return hash;
};
const comparePassword = async (password, hash) => {
return await bcrypt.compare(password, hash);
};
module.exports = {
generateJwtToken,
authenticateJwt,
encryptPassword,
comparePassword,
};