-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
86 lines (75 loc) · 2.01 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
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const csrf = require("csurf");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const { connecting } = require("./db.js");
const { postsRouter } = require("./routes/posts.js");
const { Users } = require("./models/models.js");
const { authRouter } = require("./routes/auth.js");
const PORT = 4001;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
app.use(cookieParser());
app.use(
session({
secret: "HGBJdsofldsg26",
resave: true,
saveUninitialized: false,
})
);
app.use(csrf({ cookie: true }));
app.use(passport.initialize());
app.use(passport.session());
connecting()
.then(() => console.log("connecting"))
.catch((error) => console.log(error));
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
try {
const findingUser = await Users.findOne({ email, pwd: password });
console.log(findingUser);
if (!findingUser) {
done(null, false);
return;
} else {
done(null, findingUser);
}
} catch (error) {
console.log(error);
done(null, false);
}
}
)
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await Users.findOne({ id });
console.log(id, user);
if (!user) {
return done(null, false);
}
done(null, user);
} catch (error) {
console.log(error);
done(null, false);
}
});
app.set("view engine", "ejs");
app.use("/auth", authRouter);
app.use("/home", postsRouter);
module.exports = passport;
app.listen(PORT, () => console.log("listening"));