-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
314 lines (276 loc) · 9.77 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
* Module dependencies.
*/
var express = require('express'),
fs = require('fs'),
port = process.env.PORT || 8081,
http = require('http'),
path = require('path'),
Feed = require('feed'),
mongoose = require('mongoose'),
passport = require("passport"),
flash = require("connect-flash"),
cons = require('consolidate'),
morgan = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
sm = require('sitemap'),
Poet = require('poet'),
Comment = require("./app/models/Comment"),
crypto = require("crypto"),
moment = require("moment"),
swig = require("swig"),
routes = require("./config/routes"),
nodemailer = require("nodemailer");
var env = process.env.NODE_ENV || 'development',
config = require('./config/config')[env];
mongoose.connect(config.db);
var Auth = require('./config/middlewares/authorization.js')(config);
var models_dir = __dirname + '/app/models';
fs.readdirSync(models_dir).forEach(function (file) {
if(file[0] === '.') return;
require(models_dir+'/'+ file);
});
require('./config/passport')(passport, config)
var app = express();
app.set('views', __dirname + '/app/views');
app.engine('html', cons.swig);
app.set('view engine', 'html');
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
// required for passport
app.use(session({ secret: 'ilovewebdevelopmentandiamcrazyabouttechnology' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(path.join(__dirname, 'public')));
require("./config/routes")(app,passport,config);
/**
* Instantiate and hook Poet into express; no defaults defined
*/
var poet = Poet(app,{
posts: './posts/',
postsPerPage: config.postperpage,
metaFormat: 'json',
readMoreLink:function(post){
return '';
}
});
var sitemap = null;
var generateSitemap = function(){
var urls = [];
var posts = poet.helpers.getPosts();
for(var key in posts) {
urls.push({
url: posts[key].url,
changefreq:'monthly',
priority:0.5
});
}
urls.push({
url: "http://www.supnig.com/about",
changefreq:'monthly',
priority:0.7
});
sitemap = sm.createSitemap ({
hostname: 'http://www.supnig.com',
cacheTime: 600000, // 600 sec - cache purge period
urls: urls
});
};
var generateGalleries = function() {
var re = /<!--gallery:(.*?)-->/g,
match,gpath,images,gallerytemplate=__dirname + '/app/views/gallery.html';
poet.clearCache();
Object.keys(poet.posts).map(function (title) {
var post = poet.posts[title];
while (match = re.exec(post.content)) {
images = [];
gpath = __dirname + '/public/'+match[1];
if (fs.existsSync(gpath)) {
fs.readdirSync(gpath).forEach(function (file) {
images.push("/"+match[1]+"/"+file);
});
var needle = "<!--gallery:" + match[1] + "-->";
swig.renderFile(gallerytemplate,{"images":images},function(err,result){
if (err) {
return;
}
post.content = post.content.replace(needle, result);
});
}
}
});
};
var prettydate = function(date) {
return moment(date).fromNow();
};
var renderPostWithComments = function(postslug, req, res,captchaerror,commenterror) {
var post = poet.helpers.getPost(postslug);
Comment.find({"post":postslug}).sort('-date').exec(function(err,comments){
if (err) {
console.error(err);
}
if (post) {
var captchaValue = crypto.randomBytes(64).toString('hex');
req.session.capchaValue = captchaValue;
var field1 = crypto.randomBytes(64).toString('hex');
var field2 = crypto.randomBytes(64).toString('hex');
if (Math.random() > 0.5) {
req.session.empty = field1;
req.session.captcha = field2;
} else {
req.session.empty = field2;
req.session.captcha = field1;
}
res.render('post', { "post": post,
"comments":comments,
"captchaValue":captchaValue,
"captcha":req.session.captcha,
"name1":field1,
"name2":field2,
"captchaerror":captchaerror,
"commenterror":commenterror,
"prettydate":prettydate,
"isadmin":req.user && req.user.email == config.adminemail
});
} else {
res.sendStatus(404);
}
});
};
/**
* In this example, upon initialization, we can modify the posts,
* like format the dates using a library, or modify titles.
* We'll add some asterisks to the titles of all posts for fun.
*/
poet.watch(function () {
generateGalleries();
generateSitemap();
}).init().then(function () {
generateGalleries();
generateSitemap();
});
/**
* Now we set up custom routes; based on the route (ex: '/post/:post'),
* it'll override the default route for the same type and update
* all appropriate helper methods
*/
poet.addRoute('/blog/:post', function (req, res) {
renderPostWithComments(req.params.post,req, res,false,false);
});
app.post('/comment/:post', function (req, res) {
if (req.body[req.session.captcha] != req.session.capchaValue) {
renderPostWithComments(req.params.post, req, res,true,false);
} else {
var comment = Comment.createComment({
name: req.body.name,
email: req.body.email,
comment: req.body.comment,
post: req.params.post,
date: new Date()
}).then(function () {
renderPostWithComments(req.params.post, req, res,false,false);
}, function (err) {
console.error("Error while saving comment for ", req.params.post, err);
//in case of error we render the thing anyway
renderPostWithComments(req.params.post, req, res,false,true);
});
}
});
app.get('/comment/delete/:post/:comment',Auth.isAdmin, function(req, res){
console.log("deleting comment " + req.params.comment + " of post " + req.params.post);
Comment.deleteComment(req.params.comment).then(function(){
console.log("finished deleting");
renderPostWithComments(req.params.post, req, res,false,false);
}, function(){
console.error("Error while saving comment for ", req.params.post, err);
//in case of error we render the thing anyway
renderPostWithComments(req.params.post, req, res,false,true);
});
})
poet.addRoute('/tags/:tag', function (req, res) {
var taggedPosts = poet.helpers.postsWithTag(req.params.tag);
if (taggedPosts.length) {
res.render('index', {
"posts": taggedPosts,
"tag": req.params.tag,
"prettydate":prettydate
});
}
});
poet.addRoute('/category/:category', function (req, res) {
var categorizedPosts = poet.helpers.postsWithCategory(req.params.category);
if (categorizedPosts.length) {
res.render('index', {
"posts": categorizedPosts,
"category": req.params.category,
"prettydate":prettydate
});
}
});
poet.addRoute('/pages/:page', function (req, res) {
var page = req.params.page,
lastPost = page * 3;
res.render('index', {
posts: poet.helpers.getPosts(lastPost - 3, lastPost),
page: page
});
});
poet.addRoute('/overview', function (req, res) {
res.render('overview', {
"categories": poet.helpers.getCategories(),
"tags": poet.helpers.getTags()
});
});
app.get('/', function (req, res) {
res.render('index', {
"posts": poet.helpers.getPosts(),
"prettydate":prettydate
});
});
app.get('/about', function (req, res) {
res.render('about');
});
app.get('/rss', function (req, res) {
var feed = new Feed({
title: 'Christopher Supnig - Blog',
description: 'This is the RSS feed to my blog!',
link: 'http://www.supnig.com/',
copyright: 'Copyright © 2014 Christopher Supnig. All rights reserved',
author: {
name: 'Christopher Supnig',
email: '[email protected]',
link: 'https://www.supnig.com'
}
});
var posts = poet.helpers.getPosts();
if(typeof posts == 'undefined' || posts.length <=0)
res.send('404 Not found', 404);
else {
for(var key in posts) {
feed.addItem({
title: posts[key].title,
link: posts[key].url,
description: posts[key].preview,
date: posts[key].date
});
}
// Setting the appropriate Content-Type
res.set('Content-Type', 'text/xml');
// Sending the feed as a response
res.send(feed.render('rss-2.0'));
}
});
app.get('/sitemap', function (req, res) {
sitemap.toXML( function (xml) {
res.header('Content-Type', 'application/xml');
res.send( xml );
});
});
app.listen(port);
console.log('Finished setting up server on port ' + port);