-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
188 lines (145 loc) · 4.7 KB
/
index.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import 'dotenv/config'
import express from "express";
import bodyParser from "body-parser";
import session from 'express-session';
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
import {
createUser, isPasswordCorrect, userAlreadyExists, createPost, getUserById, listPosts, updatePost, deletePost
} from './app/database/dbfuncs.js';
const app = express();
const port = 3000;
let posts = await listPosts();
// Config Express
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
// Config Sessions
app.use(session({
secret: process.env.SECRETPHRASE,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 3600000
}
}));
// How Passport should handle Registration
passport.use("local-register", new LocalStrategy(async (username, password, done) => {
try {
const userExists = await userAlreadyExists(username);
if (userExists) {
return done(null, false);
}
const newbie = await createUser(username, password);
return done (null, newbie);
} catch (error) {
done(error);
}
}));
// How Passport should handle LogIn
passport.use("local-login", new LocalStrategy(async (username, password, done) => {
try {
const user = await userAlreadyExists(username);
if (!user) {
return done(null, false, {message: 'Invalid Username or Password!'});
};
const matchPass = await isPasswordCorrect(password, user.pass);
if (!matchPass) return done(null, false, {message: 'Invalid Username or Password!'});
return done(null, user);
} catch (error) {
done(error);
}
}));
// Serialize and deserialize for sessions
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await getUserById(id);
done(null, user);
} catch (error) {
done(error);
}
});
app.use(passport.initialize());
app.use(passport.session());
// Handling Routes - GETs
app.get("/", async (req, res) => {
if (req.isAuthenticated()) {
posts = await listPosts(); // Update Posts
let userInfo;
for (let i = 0; i < posts.length; i++) {
userInfo = await getUserById(posts[i].user_id)
posts[i]['username'] = userInfo.username;
};
res.render("index", {user: req.user, posts, isEditing: false});
} else {
res.redirect("/login");
}
});
app.get("/login", (req, res) => {
const errorMessage = req.session['messages'] ? req.session['messages'][0] : false;
res.render("login", {err: errorMessage});
});
app.get("/register", (req, res) => {
res.render("register");
});
app.get("/logout", (req, res) => {
res.clearCookie("connect.sid");
req.logOut(() => {
res.redirect("/login");
});
});
app.get("/user", (req, res) => {
if (req.isAuthenticated()) {
const userId = parseInt(req.query.id);
const postsFromUser = posts.filter((post) => post.user_id == userId);
res.render("index", {user: req.user, posts: postsFromUser, isEditing: false});
} else {
res.redirect("/login");
}
});
app.get("/edit", async (req, res) => {
if (req.isAuthenticated()) {
const post = posts.filter((post) => post.post_id == req.query.id)[0];
if (post.user_id === req.user.id) {
res.render("edit-post", {user: req.user, isEditing: true, thought: post.post_text});
} else {
res.redirect("/");
};
} else {
res.redirect("/login");
};
});
app.get("/delete", async (req, res) => {
if (req.isAuthenticated()) {
await deletePost(parseInt(req.query.id), req.user.id);
res.redirect("/");
} else {
res.redirect("/login");
};
});
// Handling Routes - POSTs
app.post("/login", passport.authenticate('local-login', {failureMessage: true, failureRedirect: '/login', successRedirect: '/'}));
app.post("/register", passport.authenticate('local-register', {failureRedirect: '/register', successRedirect: '/login'}));
app.post("/", async (req, res) => {
const newPost = {
...req.body,
post_date: new Date(),
user: req.user.id,
};
await createPost(newPost);
posts = await listPosts();
res.redirect("/");
});
app.post("/edit", async (req, res) => {
const newThought = req.body.thought;
const postId = parseInt(req.query.id);
await updatePost(postId, newThought);
res.redirect("/");
});
app.listen(port, () => {
console.log(`Listening in port ${port}.`);
});