-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (66 loc) · 1.83 KB
/
app.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
const express = require("express");
const passport = require("passport");
const bodyParser = require("body-parser");
const dotenv = require("dotenv");
const sequelize = require("./config/database");
const User = require("./models/user");
// Passport setup for JWT authentication
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
dotenv.config();
const app = express();
app.use(bodyParser.json());
// Initialize Sequelize with PostgreSQL database
sequelize
.authenticate()
.then(() => {
console.log("Database connection has been established successfully.");
})
.catch((err) => {
console.error("Unable to connect to the database:", err);
});
// Define User model
// User.init(sequelize);
// Sync the model with the database
sequelize.sync();
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
};
passport.use(
new JwtStrategy(jwtOptions, (payload, done) => {
User.findByPk(payload.id)
.then((user) => {
if (!user) {
return done(null, false);
}
return done(null, user);
})
.catch((error) => {
return done(error, false);
});
})
);
// Define routes
// Register and login routes
const authRoutes = require("./routes/auth");
app.use("/api/auth", authRoutes);
// User routes (protected by JWT)
const userRoutes = require("./routes/users");
app.use(
"/api/users",
passport.authenticate("jwt", { session: false }),
userRoutes
);
// Todo routes (protected by JWT)
const todoRoutes = require("./routes/todos");
app.use(
"/api/todos",
passport.authenticate("jwt", { session: false }),
todoRoutes
);
// Start the Express server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});