-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
91 lines (89 loc) · 2.49 KB
/
app.ts
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
import dotenv from "dotenv";
dotenv.config();
import {
Request,
Response,
NextFunction,
Express,
} from "express-serve-static-core";
import createError from "http-errors";
import session from "express-session";
import express from "express";
import path from "node:path";
import "./auth/passport.local";
import "./auth/passport.github";
import cookieParser from "cookie-parser";
import logger from "morgan";
import indexRouter from "./routes/index";
import loginPage from "./routes/login";
import signupPage from "./routes/signup";
import controllers from "./controllers/controllers";
import passport from "passport";
import User from "./model/User";
import { connect } from "mongoose";
import createMemoryStore from "memorystore";
var app: Express = express();
app.set("views", path.resolve("./", "views"));
app.set("view engine", "pug");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.resolve("./", "public")));
(async function () {
await connect(process.env.MONGODB_URL as string);
})();
const memorystore = createMemoryStore(session);
app.use(
session({
secret: process.env.AUTHSEC as string,
saveUninitialized: false,
resave: true,
store: new memorystore({
checkPeriod: 86400000,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 3,
},
}),
);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => {
//@ts-ignore
done(null, user._id);
});
passport.deserializeUser(async function (id, done) {
let $user = await User.findById({ _id: id });
done(null, $user);
});
app.use(controllers);
app.use((req, res, next) => {
(async function () {
await connect(process.env.MONGODB_URL as string).then(() => {
next();
});
})();
});
app.use("/login", loginPage);
app.use("/signup", signupPage);
app.use((req, res, next) => {
if (req.user) {
next();
} else {
res.redirect("/login");
}
});
app.use("/", indexRouter);
app.use(function (req: Request, res: Response, next: NextFunction) {
next(createError(404));
});
app.use(function (err: any, req: Request, res: Response, next: NextFunction) {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
res.status(err.status || 500);
res.render("error", {
error: err.message,
});
});
export default app;