This repository has been archived by the owner on Jun 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
77 lines (66 loc) · 1.98 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 mongoose = require("mongoose");
const app = express();
const port = 3000;
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const uri =
"mongodb+srv://julian:thesky@cluster0.bjsvk.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
const session = require("express-session");
const User = require("./User");
passport.use(
new LocalStrategy(function (username, password, done) {
User.find({ username: username }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: "Incorrect username." });
}
if (user.password !== password) {
return done(null, false, { message: "Incorrect password." });
}
return done(null, user);
});
})
);
passport.serializeUser(function (user, done) {
done(null, user.email);
});
passport.deserializeUser(function (username, done) {
User.find({ username: username }, function (err, user) {
done(err, user);
});
});
app.use(
session({ secret: "keyboard cat", resave: false, saveUninitialized: true })
);
app.use(passport.initialize());
app.use(passport.session());
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
})
);
app.post("/signup", (req, res) => {
const username = req.body.username;
const password = req.body.password;
const newUser = new User({ username, password });
newUser.save((error) => {
if (error) {
console.log("there was an error saving the new user");
console.log(error);
}
});
res.redirect("/login");
});
app.get("/logout", function (req, res) {
req.logout();
res.redirect("/");
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});