/
index.js
81 lines (67 loc) · 2.28 KB
/
index.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const express = require('express');
const passport = require('passport');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = process.env.PORT || 3000;
// Dummy database for storing users
const users = [];
// Middleware
app.use(express.json());
app.use(passport.initialize());
// User model
class User {
constructor(id, username, password) {
this.id = id;
this.username = username;
this.password = password;
}
}
// Local strategy for username/password authentication
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
(username, password, done) => {
const user = users.find(u => u.username === username);
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
bcrypt.compare(password, user.password, (err, res) => {
if (res) {
return done(null, user);
} else {
return done(null, false, { message: 'Incorrect password.' });
}
});
}
));
// JWT strategy for token-based authentication
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'rohit13807!@fafaf5n3535n325nm' // Change this to a secure secret
};
passport.use(new JwtStrategy(jwtOptions, (payload, done) => {
const user = users.find(u => u.id === payload.sub);
if (user) {
return done(null, user);
} else {
return done(null, false);
}
}));
// Routes.. save the user detail in array.
app.post('/register', (req, res) => {
const { username, password } = req.body;
const hashedPassword = bcrypt.hashSync(password, 10);
const newUser = new User(users.length + 1, username, hashedPassword);
users.push(newUser);
res.status(201).json({ message: 'User registered successfully' });
});
app.post('/login', passport.authenticate('local', { session: false }), (req, res) => {
const token = jwt.sign({ sub: req.user.id }, jwtOptions.secretOrKey);
res.json({ token });
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});