-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
101 lines (85 loc) · 2.39 KB
/
app.js
File metadata and controls
101 lines (85 loc) · 2.39 KB
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
import 'dotenv/config';
import express from 'express';
import ejs from 'ejs';
import mongoose from 'mongoose';
import session from 'express-session';
import flash from 'express-flash';
import passport from 'passport';
import LocalStrategy from 'passport-local';
import bcrypt from 'bcryptjs';
import User from './models/User.js'
import { logError, errorHandler } from './middleware/errorLogger.js';
const app = express();
const port = 3000
// database connection
mongoose.connect(process.env.MONGO_URI)
.then(()=>{
console.log("Succesfully connected to the database.")
}).catch(err=>{console.log(err)})
app.set('view engine', 'ejs');
app.use(express.static('public'))
app.use(express.urlencoded({extended:true}))
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true
}))
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
}, async (email, password, done) => {
try {
const user = await User.findOne({ email });
if (!user || !await bcrypt.compare(password, user.password)) {
return done(null, false, { message: 'Invalid email or password.' });
}
return done(null, user);
} catch (err) {
return done(err);
}
}));
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);
}
});
// Route imports
import index from './routes/index.js';
import dashboard from './routes/dashboard.js'
import analyse from './routes/analyse.js'
import login from './routes/login.js'
import signup from './routes/signup.js'
// routes implement
app.use('/', index);
app.use('/dashboard', dashboard)
app.use('/analyse', analyse)
app.use('/signup', signup)
app.use('/login', login)
app.use((req, res) => {
res.status(404).render('404', { url: req.originalUrl });
});
app.use((req, res) => {
res.status(500).render('500', { url: req.originalUrl });
});
app.get('/logout', function (req, res, next) {
req.logout(function (err) {
if (err) {
return next(err);
}
res.redirect('/');
});
});
app.use(logError);
app.use(errorHandler);
app.listen(port, ()=>{
console.log(`App started on PORT ${port}`)
})