-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
259 lines (211 loc) · 6.38 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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
var express = require('express'),
ejs = require('ejs'),
request = require('request'),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
path = require('path'),
cookieParser = require("cookie-parser"),
mongoose = require('mongoose'),
passport = require("passport"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"),
User = require("./models/user"),
Article = require("./models/article"),
app = express()
// CONNECT LOCAL MONGOOSE DATABASE
app.set('port', (process.env.PORT || 3000));
// mongoose.connect("mongodb://localhost:27017/essayEveryday", {useNewUrlParser: true});
// mongoose.connect("mongodb+srv://mayankchauhan971:[email protected]/test?retryWrites=true&w=majority",
// {
// useNewUrlParser: true
// });
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser('secret'));
// settings for hashing passwords
app.use(require("express-session")({
secret: "Mayank Chauhan made essay everyday",
resave: false,
saveUninitialized: false
}));
// include passport to my app
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// static files path
app.use(express.static(path.join(__dirname, 'vendor')));
app.use(function (req, res, next) {
res.locals.login = req.isAuthenticated();
next();
});
// set my view engine i.e what i will use for templating
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render("index");
});
app.get("/login", function(req,res){
res.render("login");
});
app.post("/login", passport.authenticate("local", {
successRedirect: "/write",
failureRedirect: "/login"
}), function(req,res){
});
app.get("/register", function(req, res){
res.render("register");
});
app.post("/register", function(req, res){
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
if(err){
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/write");
});
});
});
app.get('/logout', function(req,res){
req.logout();
res.redirect('/');
});
app.get('/write', isLoggedIn, function(req,res){
// if authenticated show write
// else login
res.render("write", {login: req.user});
});
app.get('/my-essay', isLoggedIn, (req, res) => {
// //that is the id of the current logged in user
// const userId = ;
// query article with field of user equals to
// current logged-in user
Article.find({ user: req.user._id })
.then((articles) => {
res.render('my-essay', { articles })
})
.catch(function (err) {
res.send(err.message);
})
});
app.get('/my-essay/:id', isLoggedIn, function (req,res) {
Article.findById(req.params.id)
.then(function (article) {
res.render("show-essay", {
data: {
articleId: article._id,
title: article.title,
content: JSON.stringify(article.content)
}
});
// res.render("Hey");
})
.catch(function (err) {
res.send(err.message);
})
});
// Render edit page
app.get('/my-essay/:id/edit', isLoggedIn, function(req,res){
Article.findById(req.params.id)
.then(function (article) {
res.render("edit-essay", {
data: {
articleId: article._id,
title: article.title,
content: JSON.stringify(article.content)
}
});
})
.catch(function (err) {
res.send(err.message);
})
});
// Handle ajax request from client
// This one to create new article
app.post('/write', function (req, res) {
// get input from request body
var content = req.body.content;
var title =req.body.title;
// check if user input is present
var errors = [];
if (!content) {
errors.push({
content: '`content` is required',
})
}
if (!title) {
errors.push({
title: '`title` is required',
})
}
// if there is any error, return response with errors
if (errors.length) {
return res.status(422).json({
errors: errors
})
}
// prepare data for db persisting
var data = {
user: req.user._id, // object id of user currently logged in,
title: title,
content: content
}
Article.create(data)
.then(function (newArticle) {
// send json response to client
res.json({ newArticle: newArticle })
})
.catch(function (err) {
res.status(500).json({
message: err.message,
});
})
});
// For updating existing essay
app.put('/essay/:id', function (request, response) {
var articleId = request.params.id;
var content = request.body.content;
var title =request.body.title;
Article.findById(articleId)
.then(function (article) {
if (!article) return response.status(404).json({
message: "Cant find article"
})
article.title = title;
article.content = content;
return article.save();
})
.then((data) => {
response.json({
article: data
})
})
.catch(function(err){
res.send(err.message);
})
});
// as we want to check at multiple pages sp we make
// a separate function
function isLoggedIn(req, res, next){
// if(req.isAuthenticated()){
return next();
// }
res.redirect("/login");
}
// app.listen(3000, function(req,res){
// console.log('App on 3000');
// });
Promise.resolve()
.then(() => {
// mongoose.connect("mongodb+srv://mayankchauhan:[email protected]/test?retryWrites=true&w=majority", {
// useNewUrlParser: true
// });
mongoose.connect("mongodb://localhost:27017/essayEveryday", {useNewUrlParser: true});
})
.then(() => {
app.listen(app.get("port"), function(){
console.log("running server on port");
});
});