-
Notifications
You must be signed in to change notification settings - Fork 5
/
api.lua
711 lines (580 loc) · 23.9 KB
/
api.lua
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
-- API module
-- ==========
-- User creation, project uploading, project fetching and so on
local app = require 'app'
local app_helpers = require 'lapis.application'
local validate = require 'lapis.validate'
local md5 = require 'md5'
local bcrypt = require 'bcrypt'
local db = require 'lapis.db'
local Model = require('lapis.db.model').Model
local util = require('lapis.util')
local respond_to = require('lapis.application').respond_to
local xml = require('xml')
local config = require "lapis.config".get()
require 'backend_utils'
-- Response generation
errorResponse = function (errorText)
return jsonResponse({ error = errorText })
end
jsonResponse = function (json)
return {
layout = false,
status = 200,
readyState = 4,
json = json
}
end
cors_options = function (self)
self.res.headers['access-control-allow-headers'] = 'Content-Type'
self.res.headers['access-control-allow-method'] = 'POST, GET, OPTIONS'
return { status = 200, layout = false }
end
err = {
notLoggedIn = errorResponse('you are not logged in'),
notfound = errorResponse('not found'),
auth = errorResponse('authentication error'),
nonexistentUser = errorResponse('no user with this username exists'),
nonexistentProject = errorResponse('this project does not exist, or you do not have permissions to access it')
}
-- Database abstractions
local Users = Model:extend('users', {
primary_key = { 'username' }
})
local Projects = Model:extend('projects', {
primary_key = { 'username', 'projectname' }
})
local Likes = Model:extend('likes', {
primary_key = { 'id' }
})
local Comments = Model:extend('comments', {
primary_key = { 'id' }
})
-- Before filter
app:before_filter(function (self)
-- unescape all parameters
for k,v in pairs(self.params) do
self.params[k] = util.unescape(v)
end
-- Set Access Control header
self.res.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080'
self.res.headers['Access-Control-Allow-Credentials'] = 'true'
if (not self.session.username) then
self.session.username = ''
end
end)
-- Data retrieval
app:get('/api', function (self)
return { layout = false, 'Beetle Cloud API' }
end)
app:get('/api/users', function (self)
return jsonResponse(Users:select({ fields = 'username' }))
end)
app:get('/api/users/:username', function (self)
-- find() doesn't allow for field filtering
return jsonResponse(Users:select('where username = ?', self.params.username, { fields = 'username, location, about, joined' })[1])
end)
app:get('/api/users/:username/gravatar', function (self)
local user = Users:find(self.params.username)
if (user) then
return {
layout = false,
status = 200,
readyState = 4,
"http://www.gravatar.com/avatar/"
.. md5.sumhexa(user.email)
}
else
return err.nonexistentUser
end
end)
app:get('/api/users/:username/become', function (self)
local visitor = Users:find(self.session.username)
if (visitor and visitor.isadmin) then
self.session.username = self.params.username
return jsonResponse({ text = visitor.username .. ' became ' .. self.params.username })
else
return err.auth
end
end)
app:get('/api/projects/:selection/:limit/:offset(/:username)', function (self)
local username = self.params.username or 'Examples'
local list = self.params.list or ''
local tag = self.params.tag or ''
local notes = self.params.notes or ''
local query = {
newest = 'projectName, username from projects where isPublic = true order by id desc',
popular = 'count(*) as likecount, projects.projectName, projects.username from projects, likes where projects.isPublic = true and projects.projectName = likes.projectName and projects.username = likes.projectowner group by projects.projectname, projects.username order by likecount desc',
favorite = 'distinct projects.id, projects.projectName, projects.username from projects, likes where projects.projectName = likes.projectName and projects.username = likes.projectowner and likes.liker = \'' .. username .. '\' group by projects.projectname, projects.username order by projects.id desc',
shared = 'projectName, username from projects where isPublic = true and username = \'' .. username .. '\' order by id desc',
notes = 'projectName, username from projects where isPublic = true and username = \'' .. username .. '\' and notes = \'' .. notes .. '\' order by id desc',
list = 'projectName, username from projects where isPublic = true and username = \'' .. username .. '\' and projectName in ' .. list .. ' order by id desc',
tag = 'projectName, username from projects where isPublic = true and admin_tags ilike \'%' .. tag .. '%\' order by id desc'
}
return jsonResponse(
db.select(
query[self.params.selection] .. ' limit ? offset ?',
self.params.limit or 5,
self.params.offset or 0))
end)
app:get('/api/users/:username/projects/:projectname/image', function (self)
local project = Projects:find(self.params.username, self.params.projectname)
if (project) then
if (project.imageisfeatured) then
return altImageFor(project)
else
return {
layout = false,
status = 200,
readyState = 4,
project.thumbnail
}
end
else
return err.nonexistentProject
end
end)
app:match('project_list', '/api/users/:username/projects', respond_to({
OPTIONS = cors_options,
GET = function (self)
-- returns all projects by a user
if (self.params.username == self.session.username) then
return jsonResponse(Projects:find_all(
{ self.params.username },
{ key = 'username' }))
else
return jsonResponse(Projects:find_all(
{ self.params.username },
{
key = 'username',
where = { ispublic = true }
}))
end
end
}))
app:match('fetch_project', '/api/users/:username/projects/:projectname', respond_to({
OPTIONS = cors_options,
GET = function (self)
local project = Projects:find(self.params.username, self.params.projectname)
local visitor = Users:find(self.session.username)
if (project and (project.ispublic or (visitor and visitor.isadmin) or self.params.username == self.session.username)) then
return jsonResponse(project)
else
return err.nonexistentProject
end
end
}))
app:get('/api/search/:query', function (self)
local query = '.*' .. self.params.query .. '.*'
local matchingUsers = Users:select('where username ~* ? or about ~* ? order by id desc limit 10', query, query, { fields = 'username' })
local matchingProjects = Projects:select('where ispublic = \'true\' and projectname ~* ? or notes ~* ? order by id desc limit 10', query, query, { fields = 'projectname, username' })
return jsonResponse({ users = matchingUsers, projects = matchingProjects })
end)
-- Session management
app:match('login', '/api/users/login', respond_to({
OPTIONS = cors_options,
GET = function (self)
local user = Users:find(self.params.username)
local comesFromWebClient = ngx.var.http_referer:match('/run') == nil
if (user == nil) then
if comesFromWebClient then
return { redirect_to = '/login?fail=true' }
else
return errorResponse('invalid username')
end
elseif (bcrypt.verify(self.params.password, user.password)) then
self.session.username = user.username
self.session.email = user.email
self.session.gravatar = md5.sumhexa(user.email)
if comesFromWebClient then
return { redirect_to = '/' }
else
return jsonResponse({
text = 'User ' .. self.params.username .. ' logged in'
})
end
else
if comesFromWebClient then
return { redirect_to = '/login?fail=true' }
else
return errorResponse('invalid password')
end
end
end
}))
app:match('logout', '/api/users/logout', respond_to({
OPTIONS = cors_options,
GET = function (self)
local username = self.session.username
local comesFromWebClient = ngx.var.http_referer:match('/run') == nil
self.session.username = ''
if comesFromWebClient then
return { redirect_to = '/' }
else
return jsonResponse({
text = 'User ' .. username .. ' logged out'
})
end
end
}))
app:match('current_user', '/api/user', respond_to({
-- Gives back the currently logged user
OPTIONS = cors_options,
GET = function (self)
return jsonResponse({ username = self.session.username })
end
}))
-- Data insertion
app:match('new_user', '/api/users/new', respond_to({
OPTIONS = cors_options,
POST = function (self)
local comesFromWebClient = ngx.var.http_referer:match('/run') == nil
validate.assert_valid(self.params, {
{ 'username', exists = true, min_length = 3, max_length = 200 },
{ 'password', exists = true, min_length = 3 },
{ 'email', exists = true, min_length = 3 }
})
if (comesFromWebClient and not self.params.password == self.params.password_repeat) then
return { redirect_to = '/signup?fail=true&reason=Passwords%20do%20not%20match' }
end
if (Users:find(self.params.username)) then
if (comesFromWebClient) then
return { redirect_to = '/signup?fail=true&reason=Username%20already%20exists' }
else
return errorResponse('a user with this username already exists')
end
end
Users:create({
username = self.params.username,
password = bcrypt.digest(self.params.password, 11),
email = self.params.email,
isadmin = false,
joined = db.format_date()
})
if (comesFromWebClient) then
return { redirect_to = '/user_created' }
else
return jsonResponse({ text = 'User ' .. self.params.username .. ' created' })
end
end
}))
app:match('update_user', '/api/users/:username/update/:property', respond_to({
OPTIONS = cors_options,
POST = function (self)
local user = Users:find(self.params.username);
if (not user) then
return err.nonexistentUser
end
if (self.params.username ~= self.session.username) then
return err.auth
end
local options = {}
ngx.req.read_body()
options[self.params.property] = ngx.req.get_body_data()
user:update(options)
end
}))
app:match('update_project', '/api/users/:username/projects/:projectname/update/:property', respond_to({
OPTIONS = cors_options,
POST = function (self)
local project = Projects:find(self.params.username, self.params.projectname);
if (not project) then
return err.nonexistentProject
end
if (self.params.property == 'admin_tags') then
local visitor = Users:find(self.session.username)
if (not visitor.isadmin) then
return err.auth
end
else
if (self.params.username ~= self.session.username) then
return err.auth
end
end
local options = {}
ngx.req.read_body()
options[self.params.property] = ngx.req.get_body_data()
if (self.params.property == 'notes') then
-- Special case! Notes are saved both in a column and inside the XML
local xmlData = xml.load(project.contents)
xml.find(xmlData, 'notes')[1] = options['notes']
options['contents'] = xml.dump(xmlData)
end
if options['admin_tags'] == nil then
options['admin_tags'] = ""
end
project:update(options)
end
}))
app:match('save_project', '/api/projects/save', respond_to({
OPTIONS = cors_options,
POST = function (self)
-- can't use camel case because SQL doesn't care about case
self.params.ispublic = (self.params.ispublic == 'true')
validate.assert_valid(self.params, {
{ 'projectname', exists = true, min_length = 3 },
{ 'username', exists = true },
{ 'ispublic', type = 'boolean' },
{ 'contents', exists = true }
})
if (not Users:find(self.params.username)) then
return err.nonexistentUser
end
if (self.params.username ~= self.session.username) then
return err.auth
end
ngx.req.read_body()
local existingProject = Projects:find(self.params.username, self.params.projectname)
local xmlString = ngx.req.get_body_data()
local xmlData = xml.load(xmlString)
if (existingProject) then
existingProject:update({
contents = xmlString,
updated = db.format_date(),
notes = xml.find(xmlData, 'notes')[1] or '',
thumbnail = xml.find(xmlData, 'thumbnail')[1]
})
if ((existingProject.shared == nil and self.params.ispublic == 'true')
or (self.params.ispublic == 'true' and not existingProject.ispublic)) then
existingProject:update({ shared = db.format_date() })
end
return jsonResponse({ text = 'project ' .. self.params.projectname .. ' updated' })
else
project = Projects:create({
projectname = self.params.projectname,
username = self.params.username,
ispublic = self.params.ispublic,
contents = xmlString,
updated = db.format_date(),
notes = xml.find(xmlData, 'notes')[1] or '',
thumbnail = xml.find(xmlData, 'thumbnail')[1]
})
if (self.params.ispublic == 'true') then
project:update({ shared = db.format_date() })
end
return jsonResponse({ text = 'project ' .. self.params.projectname .. ' created' })
end
end
}))
app:match('set_visibility', '/api/users/:username/projects/:projectname/visibility', respond_to({
OPTIONS = cors_options,
GET = function (self)
local visitor = Users:find(self.session.username)
if (not Users:find(self.params.username)) then
return err.nonexistentUser
end
if (self.params.username ~= self.session.username and not (visitor or visitor.isadmin)) then
return err.auth
end
local project = Projects:find(self.params.username, self.params.projectname)
if (project) then
project:update({ ispublic = self.params.ispublic == 'true' })
if (self.params.ispublic == 'true') then
project:update({ shared = db.format_date() })
end
return jsonResponse({
text = 'project ' .. self.params.projectname .. ' is now ' ..
(self.params.ispublic == 'true' and 'public' or 'private')
})
else
return err.nonexistentProject
end
end
}))
app:match('remove_project', '/api/users/:username/projects/:projectname/delete', respond_to({
OPTIONS = cors_options,
GET = function (self)
-- can't use camel case because SQL doesn't care about case
local visitor = Users:find(self.session.username)
if (not Users:find(self.params.username)) then
return err.nonexistentUser
end
if (self.params.username ~= self.session.username and not (visitor or visitor.isadmin)) then
return err.auth
end
local project = Projects:find(self.params.username, self.params.projectname)
if (project) then
db.delete('likes', { projectowner = self.params.username, projectname = self.params.projectname })
project:delete()
return jsonResponse({ text = 'project ' .. self.params.projectname .. ' removed' })
else
return err.nonexistentProject
end
end
}))
app:match('toggle_like', '/api/users/:username/projects/:projectname/like', respond_to({
OPTIONS = cors_options,
GET = function (self)
-- can't use camel case because SQL doesn't care about case
if (not self.session.username) then
return err.notLoggedIn
end
if (self.session.username == self.params.username) then
return jsonResponse({ text = 'of course you do, it\'s your own project! ;)'})
end
local project = Projects:find(self.params.username, self.params.projectname)
local user = Users:find(self.params.username)
if (project) then
if (Likes:count('liker = ? and projectname = ? and projectowner = ?',
self.session.username,
self.params.projectname,
self.params.username) == 0) then
Likes:create({
projectname = self.params.projectname,
projectowner = self.params.username,
liker = self.session.username
})
if (user.notify_like) then
ok, err = send_mail(user.email, "Someone likes your project",
"Dear " .. self.params.username .. ", \n\n"
.. "Your project \"" .. self.params.projectname .. "\" got "
.. "a thumb up from user "
.. self.session.username .. "\n\n"
.. "Visit your project and see all likes here: \n"
.. self:build_url("/users/" .. self.params.username .. "/projects/" .. util.escape(self.params.projectname))
.. config.mail_footer
)
end
return jsonResponse({ text = 'project liked' })
else
db.delete(
'likes',
'liker = ? and projectname = ? and projectowner = ?',
self.session.username,
self.params.projectname,
self.params.username)
return jsonResponse({ text = 'project unliked' })
end
else
return err.nonexistentProject
end
end
}))
app:match('alternate_image', '/api/users/:username/projects/:projectname/altimage', respond_to({
OPTIONS = cors_options,
GET = function (self)
local project = Projects:find(self.params.username, self.params.projectname)
if (not project) then
return err.nonexistentProject
end
if (self.params.featureImage) then
-- we got the featureImage parameter, meaning we want to change the featured image
-- for this project
if (not self.session.username) then
return err.notLoggedIn
end
if (self.params.username ~= self.session.username) then
return err.auth
end
project:update({ imageisfeatured = self.params.featureImage == 'true' })
else
-- we are just asking for the alternate image for this project
return altImageFor(project)
end
end,
POST = function (self)
if (not self.session.username) then
return err.notLoggedIn
end
if (self.params.username ~= self.session.username) then
return err.auth
end
local project = Projects:find(self.params.username, self.params.projectname)
if (project) then
ngx.req.read_body();
image = ngx.req.get_body_data();
local dir = 'projects/' .. math.floor(project.id / 1000) .. '/' .. project.id -- we store max 1000 projects per dir
os.execute('mkdir -p ' .. dir)
local file = io.open(dir .. '/image.png', 'w+')
file:write(image)
file:close()
return jsonResponse('image uploaded')
else
return err.nonexistentProject
end
end
}))
-- Stats
app:match('stats', '/api/stats', respond_to({
OPTIONS = cors_options,
GET = function (self)
return jsonResponse(getStats())
end
}))
-- comments
app:match('new_comment', '/api/comments/new', respond_to({
OPTIONS = cors_options,
POST = function (self)
validate.assert_valid(self.params, {
{ 'projectname', exists = true, min_length = 3 },
{ 'projectowner', exists = true },
{ 'author', exists = true, min_length = 3 },
{ 'contents', exists = true, min_length = 3 }
})
if (string.len(self.params.contents) < 3) then
return errorResponse('comment too short')
end
if (self.params.author ~= self.session.username) then
return err.auth
end
local existingProject = Projects:find(self.params.projectowner, self.params.projectname)
if (existingProject) then
self.params.contents = self.params.contents:gsub("^%s*(.-)%s*$", "%1")
self.params.contents = self.params.contents:gsub("%b<>", "")
comment = Comments:create({
projectname = self.params.projectname,
author = self.params.author,
contents = self.params.contents,
projectowner = self.params.projectowner,
date = os.date()
})
if (self.params.author ~= self.params.projectowner) then
user = Users:find(self.params.projectowner)
if (user.notify_comment) then
ok, err = send_mail(user.email, "New comment",
"Dear " .. self.params.projectowner .. ", \n\n"
.. "Your project \"" .. self.params.projectname .. "\" received "
.. "a new comment from user "
.. self.params.author .. "\n\n"
.. "Visit your project and read all comments here: \n"
.. self:build_url("/users/" .. self.params.projectowner .. "/projects/" .. util.escape(self.params.projectname))
.. config.mail_footer
)
end
end
return jsonResponse({ comment = comment})
else
return err.nonexistentProject
end
end
}))
app:get('/api/users/:username/projects/:projectname/comments', function (self)
return jsonResponse(
-- Comments:select('where projectowner = ? and projectname = ? order by id desc',
-- self.params.username,
-- self.params.projectname)
db.select(
'distinct comments.contents, comments.id, comments.date, username as author, md5(email) as gravatar from comments, users where comments.projectname = ? and comments.projectowner = ? and comments.author = users.username order by comments.id desc',
self.params.projectname,
self.params.username)
)
end)
app:get('/api/comment/:id', function (self)
return jsonResponse(
db.select(
'distinct comments.contents, comments.id, comments.date, users.username as author, md5(users.email) as gravatar from comments, users where comments.id = ? and comments.author = users.username',
self.params.id)
)
end)
app:get('/api/comment/delete/:id', function (self)
local visitor = Users:find(self.session.username)
local comment = Comments:find(self.params.id)
if (not comment) then
return err.notfound
end
if (self.params.username ~= self.session.username and not (visitor or visitor.isadmin)) then
return err.auth
end
comment:delete()
return jsonResponse({ text = 'comment removed', id = self.params.id })
end)