This repository has been archived by the owner on Jan 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
1418 lines (1321 loc) · 46.4 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ######################################
### require modules ###
######################################
*/
// dev
const debug = require('debug') // debug for development
const clipboardy = require('clipboardy') // write to and from clipboard (for development)
// settings
const settings = require('./settings.json') // local settings file (leave at top)
const env = process.env.NODE_ENV // are we in production or development?
// express
const path = require('path') // nodejs native package
const express = require('express') // express
const app = express(); // create local instance of express
const engines = require('consolidate') // use consolidate with whiskers template engine
// Mongo
const { ObjectId } = require('mongodb')
const mongoUrl = `mongodb://${settings.mongo_user}:${settings.mongo_password}@${settings.mongo_url}/${settings.mongo_db}`
const db = require('./lib/db')
/* ######################################
### start ###
######################################
*/
// wait for database to connect before doing anything
db.connect().then( function() {
debug.log("running..")
// require locals
const queries = require('./lib/queries.js') // local database queries module
const { updateUserContacts, updateUserBlogs, updateUserPocketFilters, unsubscribeFromPocket, updateUserPermission } = require('./lib/users.js') // local database updates module
const { approveBlog, deleteBlog, editBlog, registerBlog, suspendBlog } = require('./lib/blogs.js') // local database updates module
const { authorisePocket, finalisePocketAuthentication, makeOpml, sendEmail } = require('./lib/utilities.js') // local pocket functions
const feeds = require('./lib/feeds.js')
const announcements = require('./lib/announcements.js') // local database blogs module
// managing users
const session = require('express-session') // sessions so people can log in
const passwordless = require('passwordless') // passwordless for ...passwordless logins
const TokenStore = require('passwordless-mongostore-bcryptjs') // for creating and storing passwordless tokens
const MongoStore = require('connect-mongo')(session); // session storage
// set up session params
const sessionOptions = {
resave: false,
saveUninitialized: true,
store: new MongoStore( { url: mongoUrl }),
secret: settings.session_secret,
cookie: {
maxAge: 6048e5 // expire cookies after a week
}
}
// dealing with form data
const bodyParser = require('body-parser') // bodyparser for form data
const { body, validationResult } = require('express-validator/check') // validate
// other stuff
const flash = require('express-flash') // flash messages
const feedfinder = require('@hughrun/feedfinder') // get feeds from site URLs
const fs = require('fs') // node file system
/* ######################################
### initiate and configure modules ###
######################################
*/
// MongoDB TokenStore for passwordless login tokens
const pathToMongoDb = `mongodb://${settings.mongo_user}:${settings.mongo_password}@${settings.mongo_url}/passwordless-token?authSource=${settings.mongo_db}` // mongo collection for tokens
passwordless.init(new TokenStore(pathToMongoDb, { useNewUrlParser: true})) // initiate store
// Set up an email delivery service for passwordless logins
passwordless.addDelivery('email',
function(tokenToSend, uidToSend, recipient, callback, req) {
var message = {
text: 'Hello!\nAccess your account here: ' + settings.app_url + '/tokens/?token=' + tokenToSend + '&uid=' + encodeURIComponent(uidToSend),
to: recipient,
subject: 'Log in to ' + settings.app_name,
attachment: [
{data: `<html><p>Somebody is trying to log in to ${settings.app_name} with this email address. If it was you, please <a href="${settings.app_url + '/tokens/?token=' + tokenToSend + '&uid=' + encodeURIComponent(uidToSend)}">log in</a> now.</p><p>If it wasn't you, simply delete this email.</p></html>`, alternative: true}
]
}
sendEmail(message)
.then( err => {
callback(err)
})
})
// Users can manually enter the codes if corporate email scanning tools
// are triggering the URL prematurely
passwordless.addDelivery('manual',
function(tokenToSend, uidToSend, recipient, callback, req) {
var message = {
text: `Somebody is trying to log in to ${settings.app_name} with this email address. If it was you, please access your account here: ${settings.app_url}/login-with-token\n\nYour login token is: ${tokenToSend}`,
to: recipient,
subject: `Your code to log in to ${settings.app_name}`,
attachment: [
{data: `<html><p>Somebody is trying to log in to ${settings.app_name} with this email address. If it was you, please <a href="${settings.app_url}/login-with-token?uid=${encodeURIComponent(uidToSend)}">access your account here</a>:</p>
<p>Your login token is: <code style="color: maroon">${tokenToSend}</code></p>
<p>If it wasn't you, simply delete this email.</p></html>`, alternative: true}
]
}
sendEmail(message)
.then( err => {
callback(err)
})
})
// passwordless for dev (bypass email and send the token to the clipboard instead)
passwordless.addDelivery('clipboard',
function(tokenToSend, uidToSend, recipient, callback, req) {
var address = settings.app_url + '/tokens/?token=' + tokenToSend + '&uid=' + encodeURIComponent(uidToSend)
clipboardy.writeSync(address)
if (env === 'development') {
debug.log("Login link copied to clipboard")
}
callback(null, recipient)
})
/* ######################################
### app settings and routing ###
######################################
*/
// template views
app.set('views', path.join(__dirname, 'views'))
app.engine('html', engines.whiskers)
app.set('view engine', 'html')
// routing middleware
app.use(bodyParser.urlencoded({ extended: false })) // use bodyParser with form data
app.use(bodyParser.json()) // use bodyParser with JSON
app.use(session(sessionOptions)) // use sessions
app.use(passwordless.sessionSupport()) // makes session persistent
app.use(passwordless.acceptToken({ successRedirect: '/user'})) // checks token and redirects
app.use(express.static(__dirname + '/public')) // serve static files from 'public' directory
app.use(flash()) // use flash messages for non-vue messages. This may be replaced in future but works for now
// locals (variables for all routes)
app.locals.pageTitle = settings.app_name
app.locals.appName = settings.app_name
app.locals.appTagline = settings.app_tagline
app.locals.appDescription = settings.app_description
app.locals.orgName = settings.org_name
app.locals.orgUrl = settings.org_url
app.locals.blogClub = settings.blog_club_name
app.locals.blogClubUrl = settings.blog_club_url
app.locals.blogCategories = settings.blog_categories
app.locals.legacy = settings.legacy_db
app.locals.showCredits = settings.show_credits
/* ######################################
### routes ###
######################################
*/
/*
###############
PUBLIC ROUTES
###############
*/
// home
app.get('/', (req, res) =>
Promise.all([queries.getArticles(), queries.getTopTags])
.catch( err => {
console.error(`DB error: ${err}`)
res.sendStatus(500)
})
.then( function(vals) {
newVals = vals.reduce( function(result, item, index) {
let key = Object.keys(item)[0];
result[key] = item[key]
return result
}, {})
res.render('index', {
partials: {
articleList: __dirname+'/views/partials/articleList.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html',
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
search: __dirname+'/views/partials/search.html',
searchNav: __dirname+'/views/partials/searchNav.html',
toptags: __dirname+'/views/partials/toptags.html'
},
articles: newVals.articles,
tags: newVals.tags,
user: req.session.passwordless
})
})
.catch(err => debug.log(err))
)
// search
app.get('/search/', (req, res) => queries.getArticles(req.query.tag, req.query.page, req.query.q, req.query.month)
.catch( err => {
console.error(`DB error: ${err}`)
res.sendStatus(500)
})
.then( docs => res.render('tag', {
partials: {
articleList: __dirname+'/views/partials/articleList.html',
search: __dirname+'/views/partials/search.html',
head: __dirname+'/views/partials/head.html',
foot: __dirname+'/views/partials/foot.html',
header: __dirname+'/views/partials/header.html',
footer: __dirname+'/views/partials/footer.html',
searchNav: __dirname+'/views/partials/searchNav.html',
},
articles: docs.articles,
searchterm: req.query.tag ? req.query.tag : req.query.q,
tag: req.query.tag,
searchTermEncoded: req.query.tag ? 'tag=' + encodeURIComponent(req.query.tag) : req.query.q ? 'q=' + encodeURIComponent(req.query.q) : '',
next: req.query.page ? Number(req.query.page) + 1 : 1,
prev: Number(req.query.page) - 1,
prevExists: isNaN(Number(req.query.page)) ? false : Number(req.query.page),
month: req.query.month,
monthName: docs.monthName,
hasNext: docs.hasNext,
hasPrev: docs.hasPrev,
user: req.session.passwordless
})
)
.catch(err => debug.log(err))
)
// subscribe
app.get('/subscribe', function (req, res) {
res.render('subscribe', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.session.passwordless,
errors: req.flash('error'),
mastodon_url: `https://${settings.mastodon.domain_name}/${settings.mastodon.username}`,
twitter_url: `https://twitter.com/${settings.twitter.username}`
})
})
// help
app.get('/help', function(req, res) {
res.render('help', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html',
filters: __dirname+'/views/partials/filters.html'
},
contentWarnings: settings.content_warnings,
errors: req.flash('error'),
excluded: settings.excluded_tags,
included: settings.included_tags,
user: req.session.passwordless
})
})
app.get('/opml', function(req, res) {
makeOpml()
.then( file => {
let filepath = path.join(__dirname, 'public/files/feeds.opml')
fs.writeFileSync(filepath, file)
let options = {
root: path.join(__dirname, 'public/files'),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
}
res.download('/feeds.opml', 'feeds.opml', options)
})
})
/*
###############
LOGIN ROUTES
###############
*/
/* GET login screen. */
app.get('/letmein', function(req, res) {
if (req.session.passwordless) {
res.redirect('/user')
} else {
res.render('login', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.session.passwordless,
delivery: settings.deliver_tokens_by // allows bypassing email when in development
})
}
})
/* POST login email address */
app.post('/sendtoken',
passwordless.requestToken(
function(user, delivery, callback, req) {
body('user').isEmail().normalizeEmail() // check it's email and downcases everything
if (validationResult(req).isEmpty()) {
return callback(null, user)
} else {
debug.log('ERROR: %O', validationResult(req)) // log errors
return res.status(422) // return error status
// NOTE: given the field is an 'email' field, the only way to get to this error
// is if someone is using a really old browser and enters something that is not an email address
}
},
{ failureRedirect: '/logged-out' }
),
function(req, res) {
// success!
res.redirect('/token-sent')
})
// info screen after login token sent
app.get('/token-sent', function(req, res) {
res.render( 'checkEmail', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.session.passwordless
})
})
/* GET login screen for showing tokens. */
app.get('/get-login-token', function(req, res) {
if (req.session.passwordless) {
res.redirect('/user')
} else {
res.render('getLoginToken', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.session.passwordless,
delivery: 'manual'
})
}
})
app.post('/send-manual-token',
passwordless.requestToken(
function(user, passwordlessManual, callback, req) {
body('user').isEmail().normalizeEmail()
if (validationResult(req).isEmpty()) {
return callback(null, user)
} else {
debug.log('ERROR: %O', validationResult(req))
return res.status(422)
}
},
{ failureRedirect: '/logged-out' }
),
function(req, res) {
// success!
res.redirect('/token-sent')
})
app.get('/login-with-token', function(req,res) {
res.render('loginWithToken', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.query.user,
uid: req.query.uid
})
})
app.post('/login-with-token', function(req,res) {
let token = req.body.token
let uid = req.body.uid
res.redirect(`/tokens/?token=${token}&uid=${uid}`)
})
/*
###############
USER ROUTES
###############
*/
// restrict all user paths to logged in users
app.all('/user*',
passwordless.restricted({ failureRedirect: '/letmein' }),
(req, res, next) =>
next()
)
// user dashboard
// all logic should be in the vue API calls
app.get('/user',
function (req, res) {
res.render('user', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.user
})
})
// pocket routes
app.get('/user/pocket',
(req, res) => {
var args = {}
args.user = req.user
queries.getUserDetails(args)
.then(authorisePocket)
.then( args => {
req.session.pocketCode = args.code
res.redirect(`https://getpocket.com/auth/authorize?request_token=${args.code}&redirect_uri=${settings.app_url}/user/pocket-redirect`)
})
.catch( err => {
debug.log(err)
req.flash('error', `Something went wrong trying to authenticate with Pocket: ${err}`)
res.redirect('/subscribe')
})
})
app.get('/user/pocket-redirect',
(req, res) => {
// user has now authorised us to authenticate to pocket and get an access token
const args = {}
args.code = req.session.pocketCode
args.key = settings.pocket_consumer_key
args.user = req.user
finalisePocketAuthentication(args)
.then( () => {
req.flash('success', 'Pocket account registered')
res.redirect('/user')
})
.catch(e => {
req.flash('error', e.message)
console.log(JSON.stringify(e))
res.redirect('/subscribe')
})
})
/*
###############
ADMIN ROUTES
###############
*/
// restrict all admin paths
app.all('/admin*',
passwordless.restricted({ failureRedirect: '/letmein' }),
function (req, res, next) {
var args = {}
args.user = req.user
queries.getUserDetails(args)
.then( doc => {
if (doc.user.permission && doc.user.permission === "admin") {
next()
} else {
req.flash('error', 'You are not allowed to view admin pages because you are not an administrator')
res.status(403)
res.redirect('/user')
}
})
.catch(err => {
debug.log(`Error accessing admin page: ${err}`)
req.flash('error', 'Something went wrong')
res.redirect('/user')
})
})
// admin home page
app.get('/admin', function (req, res) {
res.render('admin', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.user
})
})
// browse page
app.get('/browse', function (req, res) {
res.render('browse', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.user
})
})
/*
#######################
LOGOUT AND ERROR ROUTES
#######################
*/
// logout
app.get('/logout',
passwordless.logout(),
function(req, res) {
res.redirect('/')
})
// show token expired screen if token already used or too old
app.get('/tokens', function(req, res) {
res.render('expired', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
},
user: req.session.passwordless
})
})
// email-updated to log out users who change their email address
app.get('/email-updated',
passwordless.logout(), // force logout
function(req, res) {
res.render('emailUpdated', {
partials: {
head: __dirname+'/views/partials/head.html',
header: __dirname+'/views/partials/header.html',
foot: __dirname+'/views/partials/foot.html',
footer: __dirname+'/views/partials/footer.html'
}
})
})
/*
#######################
API ROUTES
#######################
*/
app.get('/api/v1/browse', function (req, res) {
queries.getBlogs({
query: {
approved: true
}
})
.then( data => {
if (req.user) {
data.query = {email: req.user}
queries.getUsers(data)
.then( response => {
if (response.users[0] && response.users[0].blogs) {
for (let blog of data.blogs) {
blog.owned = response.users[0].blogs.some( x => blog._id.equals(x) )
blog.claimed = response.users[0].blogsForApproval.some( x => blog._id.equals(x) )
}
}
res.json({
blogs: data.blogs,
legacy: settings.legacy_db,
user: response.users[0]
})
})
.catch(err => {
console.error(err)
res.json({error: `${err}`})
})
} else {
res.json({
blogs: data.blogs,
legacy: settings.legacy_db,
user: null
})
}
}) // FIXME: do something more useful
.catch( err => console.error(`DB error: ${err}`))
})
app.get('/api/v1/categories', function (req, res) {
res.json({categories: settings.blog_categories})
})
app.get('/api/v1/legacy', function (req, res) {
res.json({legacy: settings.legacy_db})
})
// must have logged in user for all other api routes
app.all('/api/v1/*',
passwordless.restricted(),
(req, res, next) => {
next()
})
/* ########
GET
########
*/
app.get('/api/v1/user/info', function(req, res) {
queries.getUsers({query: {"email" : req.user}})
.then(
doc => {
var data = {}
if (doc.users.length > 0) {
data.user = doc.users[0]._id
data.email = doc.users[0].email
data.twitter = doc.users[0].twitter || null
data.mastodon = doc.users[0].mastodon || null
data.pocket = doc.users[0].pocket || false
data.admin = doc.users[0].permission === 'admin'
} else {
data.email = req.user // send back the user email so they don't have to re-type it
data.error = {class: 'flash-warning', text: "You don't have an account yet! Click 'edit' to create your user profile."}
}
res.json(data)
})
.catch( err => {
debug.log(err)
})
})
app.get('/api/v1/user/blogs', function(req, res) {
queries.getUsers({query: {"email" : req.user}})
.then( // now get the approved blogs
doc => {
if (doc.users.length > 0 && doc.users[0].blogs) {
doc.query = {"_id": {$in: doc.users[0].blogs}}
} else {
doc.query = {"_id": null}
}
return doc
})
.then(queries.getBlogs)
.then( data => {
let user = data.users.length > 0 ? data.users[0].idString : null
res.json({user: user, blogs: data.blogs})
})
.catch( err => {
console.log("error in app.get('/api/v1/user/blogs') in app.js")
debug.log(err)
})
})
app.get('/api/v1/user/unapproved-blogs', function(req, res) {
queries.getUsers({query: {"email" : req.user}})
.then( // now get the unapproved blogs
doc => {
if (doc.users.length > 0 && doc.users[0].blogsForApproval) {
doc.query = {
"_id": {$in: doc.users[0].blogsForApproval},
}
} else {
doc.query = {"_id": null}
}
return doc
})
.then(queries.getBlogs)
.then( data => {
res.json(data.blogs)
})
.catch( err => {
console.log("error in app.get('/api/v1/user/unapproved-blogs') in app.js")
debug.log(err)
})
})
/* #############
USER POST
#############
*/
// UPDATE/user routes
// NOTE: all routes **MUST** use req.user to identify user to update
// DO NOT make routes taking logged in user id or current email from req.body
// update user contact info
app.post('/api/v1/update/user/info',
[
// normalise email
body('email').isEmail(),
// validate twitter with custom check
body('twitter').custom( val => {
return val === '' || val.match(/^@+[A-Za-z0-9_]*$/)
}).withMessage("Twitter handles must start with '@' and contain only alphanumerics or underscores"),
// validate twitter length
body('twitter').isLength({max: 16}).withMessage("Twitter handles must contain fewer than 16 characters"),
// validate mastodon with custom check
body('mastodon').custom( val => {
return val === '' || val.match(/^@+[A-Za-z0-9_]+@+[A-Za-z0-9_\.]*$/)
}).withMessage("Mastodon addresses should be in the form '@user@server.com'")
],
(req, res) => {
if (!validationResult(req).isEmpty()) { // if there are validation errors
// validation errors are an array
// we turn this into multiple error messages on the client end
let errors = validationResult(req).array()
res.send({
error: errors
})
} else { // if no validation errors
var args = req.body
args.user = req.user
queries.checkEmailIsUnique(args)
.then(updateUserContacts)
.then(args => {
if (args.user.email != req.user) {
res.send(
{
redirect: '/email-updated',
error: null
}
)
} else {
args.msg = {}
args.msg.class = 'flash-success'
args.msg.text = 'Your details have been updated'
res.send(
{
msg: args.msg,
user: args.user, // NOTE: this is *only* the data that was sent! i.e. it's "args"
error: null
}
)
}
})
.catch(err => {
res.send({
error: {
class: 'flash-error',
text: `${err}`
}
})
})
}
})
// register blog
app.post( '/api/v1/update/user/register-blog',
function(req, res) {
feedfinder.getFeed(req.body.url)
.then( ff => {
const args = req.body
args.user = req.user
args.title = ff.title
args.feed = ff.feed // add the feed to the form data object
args.action = "register" // this is used in updateUserBlogs
args.url = args.url.replace(/\/+$/, "") // get rid of trailing slashes
// we match on the FEED rather than the URL (below)
// because if there is a redirect, the URL might not match even though it's the same blog
args.query = {feed: args.feed}
return args
})
.then(queries.getBlogs) // check the blog isn't already registered
.then(
args => {
if (args.blogs.length < 1) {
registerBlog(args) // create new blog document
.then(updateUserBlogs) // add blog _id to user's blogsForApproval array
.then( args => {
message = {
text: `User ${req.user} has registered ${args.url} with ${settings.app_name}.\n\nLog in at ${settings.app_url}/letmein to accept or reject the registration.`,
to: 'admins',
subject: `New blog registered for ${settings.app_name}`,
}
sendEmail(message) // send email to admins
res.send({status: 'ok', msg: {class: 'flash-success', text: 'blog registered!'}})
})
.catch( e => {
res.send({status: 'error', msg: {class: 'flash-error', text: `Something went wrong registering your blog: ${e}`} })
})
} else {
res.send({status: 'error', msg: {class: 'flash-error', text: `That blog is already registered`} })
}
})
.catch(err => {
res.send({status: 'error', msg: {class: 'flash-error', text: `Something went wrong registering your blog: ${err}`} })
})
})
// claim blog
app.post('/api/v1/update/user/claim-blog', function(req, res) {
const args = req.body
args.query = { "_id" : ObjectId(args.idString)}
args.action = "register"
args.user = req.user
queries.getBlogs(args)
// then check users for any claiming this blog
.then( args => {
if (args.blogs.length < 1) {
throw new Error("Blog does not exist: check the URL or try registering") // if there are no results the blog doesn't exist
} else {
args.blog = args.blogs[0].idString
args.query = {
$or: [
{"blogs" : args.blogs[0]._id},
{"blogsForApproval" : args.blogs[0]._id}
]
}
return args
}
})
.then(queries.getUsers)
.then( args => {
if (args.users.length < 1) {
return args
} else {
throw new Error(`Another user owns or has claimed ${args.url}`)
}
})
.then(updateUserBlogs)
.then( args => {
message = {
text: `User ${req.user} has claimed ${args.url} on ${settings.app_name}.\n\nLog in at ${settings.app_url}/letmein to accept or reject the registration.`,
to: 'admins',
subject: `New blog claimed on ${settings.app_name}`,
}
sendEmail(message) // send email to admins
res.send({status: 'ok'})
}).catch( err => {
res.send({ error: { message: `${err}` } })
})
})
app.post('/api/v1/update/user/delete-pending-registration', function(req, res) {
const args = req.body
args.user = req.user
args.query = {"_id" : ObjectId(args.blog)} // for getBlogs
updateUserBlogs(args)
.then(queries.getBlogs)
.then( args => {
if (args.blogs[0].approved) {
return args // if the blog is approved then this was a legacy claim
} else {
return deleteBlog(args) // if the blog isn't approved it's just a new registration
}
})
.then( args => {
let blog = args.blogs[0]
message = {
text: `User ${req.user} has cancelled their registration of ${blog.url} with ${settings.app_name}. There is no need to take any action in response to this email.`,
to: 'admins',
subject: `Registration of ${blog.url} has been cancelled`,
}
sendEmail(message) // send email to admins
res.send(
{
msg: {
type: 'success',
class:'flash-success',
text: 'Pending blog registration cancelled!'
},
error: null
}
)
})
.catch( e => {
debug.log('**ERROR DELETING BLOG REGISTRATION**')
debug.log(e)
res.send({
blogs: null,
msg: {
class:'flash-error',
text: `Error deleting pending blog registration: ${e.message}`
}
})
})
})
// delete blog
app.post('/api/v1/update/user/delete-blog', function(req, res) {
const args = req.body
args.user = req.user // for updateUserBlogs & getUserDetails
updateUserBlogs(args)
.then(deleteBlog)
.then( () => {
res.send(
{
msg: {
type: 'success',
class:'flash-success',
text: 'Blog deleted'
},
error: null
}
)
})
.catch( e => {
debug.log('**ERROR DELETING BLOG**')
debug.log(e)
res.send({
blogs: null,
msg: {
class:'flash-error',
text: `Error deleting blog: ${e.message}`
}
})
})
})
// edit blog category or update title andnd/or feed
app.post('/api/v1/update/user/edit-blog',
(req, res) => {
feedfinder.getFeed(req.body.url)
.then( ff => {
const args = req.body // url and category
args.user = req.user
args.title = ff.title
args.feed = ff.feed
return args
})
.then(editBlog)
.then( () => {
res.json({
msg: {class: 'flash-success', text: 'blog updated'}
})
})
.catch(e => {
debug.log(e)
res.json({
error: {class: 'flash-error', text: 'error updating blog'}
})
})
})
// exclude or include (un-exclude) a blog from pocket
app.post('/api/v1/update/user/filter-pocket',
(req, res) => {
let args = req.body // blog (idString) and exclude (true/false)
args.user = req.user
updateUserPocketFilters(args)
.then( () => {
res.send({
result: 'ok'
})
})
.catch(err => {
debug.log('error updating exclusion list', err)
res.send({
error: err.message
})
})
})
// unsubscribe from Pocket
app.post('/api/v1/update/user/remove-pocket',
(req, res) => {
unsubscribeFromPocket(req.user)
.then( () => {
res.send({
class: 'flash-success',
text: 'Pocket account unsubscribed. You should also "remove access" for this app at https://getpocket.com/connected_applications'
})
})
.catch(err => {
debug.log('error removing pocket account', err)
res.send({
msg: {
class: 'flash-error',
text: err.message
}
})
})
})
// protect admin routes
app.all('/api/v1/admin*',
function (req, res, next) {
var args = {}
args.user = req.user
queries.getUserDetails(args)
.then( doc => {
if (doc.user.permission && doc.user.permission === "admin") {
next()
} else {
req.flash('error', 'You are not allowed to view admin pages because you are not an administrator')