-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
122 lines (107 loc) · 3.63 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const GitHubStrategy = require('passport-github2').Strategy;
const bcrypt = require('bcryptjs');
const User = require('./models/User');
require('dotenv').config();
const app = express();
// Handlebars Configuration
app.engine('hbs', exphbs.engine({
extname: 'hbs',
layoutsDir: path.join(__dirname, 'views', 'layouts'),
partialsDir: path.join(__dirname, 'views', 'partials'),
helpers: {
eq: (a, b) => a === b, // Add eq helper function for equality comparison
},
}));
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
// Middleware
app.use(express.urlencoded({ extended: true })); // For form data
app.use(express.json()); // For JSON data
app.use(express.static(path.join(__dirname, 'public')));
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB Connected'))
.catch((err) => console.log('MongoDB Error:', err));
// Configure Session
app.use(
session({
secret: process.env.SESSION_SECRET || 'your_secret_key', // Replace with a strong secret
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGO_URI, // Use the same MongoDB URI
}),
cookie: { maxAge: 1000 * 60 * 60 * 24 }, // 1 day
})
);
// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());
// Passport Local Strategy for username/password authentication
passport.use(new LocalStrategy(
{ usernameField: 'username' }, // You can change the field name if necessary
async (username, password, done) => {
try {
const user = await User.findOne({ username });
if (!user) {
return done(null, false, { message: 'Invalid username or password' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return done(null, false, { message: 'Invalid username or password' });
}
return done(null, user);
} catch (err) {
return done(err);
}
}
));
// Passport GitHub OAuth Strategy
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: 'http://localhost:3000/auth/github/callback', // Adjust for production
}, async (accessToken, refreshToken, profile, done) => {
try {
let user = await User.findOne({ username: profile.username });
if (!user) {
user = new User({
username: profile.username,
role: 'user', // Default role for new users
});
await user.save();
}
return done(null, user);
} catch (err) {
return done(err);
}
}));
// Serialize and Deserialize user
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err);
}
});
// Routes
const indexRouter = require('./routes/index');
const authRouter = require('./routes/auth');
app.use('/', indexRouter);
app.use('/auth', authRouter); // Add authentication routes
module.exports = app;