-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
93 lines (85 loc) · 2.7 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
// Terminal run command: node app.js
const express = require('express');
const path = require('path');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs')
require('dotenv').config()
const mongoDB = process.env.MONGO_URI
mongoose.connect(mongoDB, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'mongo connection error'));
const User = mongoose.model(
'User',
new Schema({
username: { type: String, required: true },
password: { type: String, required: true }
})
);
const app = express();
app.set('views', __dirname);
app.set('view engine', 'ejs');
passport.use(
new LocalStrategy((username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { msg: 'Incorrect username' });
}
bcrypt.compare(password, user.password, (err, res) => {
if (res) {
// passwords match! log user in
return done(null, user)
} else {
// passwords do not match!
return done(null, false, {msg: "Incorrect password"})
}
})
return done(null, user);
});
})
);
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.use(session({ secret: process.env.SECRET, resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.urlencoded({ extended: false }));
app.get("/", (req, res) => {
res.render("index", { user: req.user });
});
app.get('/sign-up', (req, res) => res.render('sign-up-form'));
app.post('/sign-up', (req, res, next) => {
password: bcrypt.hash(req.body.password, 10, (err, hashedPassword) => {
const user = new User({
username: req.body.username,
password: hashedPassword
}).save(err => {
if (err) {
return next(err);
}
res.redirect('/');
});
})
});
app.post('/log-in', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/'
})
);
app.get("/log-out", (req, res) => {
req.logout();
res.redirect("/");
});
app.listen(3000, () => console.log('### App listening on port 3000 ###'));