-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheventman_server.py
More file actions
executable file
·1349 lines (1208 loc) · 55.1 KB
/
eventman_server.py
File metadata and controls
executable file
·1349 lines (1208 loc) · 55.1 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EventMan(ager)
Your friendly manager of attendees at an event.
Copyright 2015-2017 Davide Alberani <da@erlug.linux.it>
RaspiBO <info@raspibo.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import re
import glob
import json
import time
import string
import random
import logging
import datetime
import dateutil.tz
import dateutil.parser
import tornado.httpserver
import tornado.ioloop
import tornado.options
from tornado.options import define, options
import tornado.web
import tornado.websocket
from tornado import gen, escape, process
import utils
import monco
import collections
ENCODING = 'utf-8'
PROCESS_TIMEOUT = 60
API_VERSION = '1.0'
re_env_key = re.compile('[^a-zA-Z_]+')
re_slashes = re.compile(r'//+')
# Keep track of WebSocket connections.
_ws_clients = {}
def authenticated(method):
"""Decorator to handle forced authentication."""
original_wrapper = tornado.web.authenticated(method)
@tornado.web.functools.wraps(method)
def my_wrapper(self, *args, **kwargs):
# If no authentication was required from the command line or config file.
if not self.authentication:
return method(self, *args, **kwargs)
# unauthenticated API calls gets redirected to /v1.0/[...]
if self.is_api() and not self.current_user:
self.redirect('/v%s%s' % (API_VERSION, self.get_login_url()))
return
return original_wrapper(self, *args, **kwargs)
return my_wrapper
class BaseException(Exception):
"""Base class for EventMan custom exceptions.
:param message: text message
:type message: str
:param status: numeric http status code
:type status: int"""
def __init__(self, message, status=400):
super(BaseException, self).__init__(message)
self.message = message
self.status = status
class InputException(BaseException):
"""Exception raised by errors in input handling."""
pass
class BaseHandler(tornado.web.RequestHandler):
"""Base class for request handlers."""
permissions = {
'event|read': True,
'event:tickets|read': True,
'event:tickets|create': True,
'event:tickets|update': True,
'event:tickets-all|create': True,
'events|read': True,
'users|create': True
}
# Cache currently connected users.
_users_cache = {}
# A property to access the first value of each argument.
arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
for k, v in self.request.arguments.items()]))
# A property to access both the UUID and the clean arguments.
@property
def uuid_arguments(self):
uuid = None
arguments = self.arguments
if 'uuid' in arguments:
uuid = arguments['uuid']
del arguments['uuid']
return uuid, arguments
_bool_convert = {
'0': False,
'n': False,
'f': False,
'no': False,
'off': False,
'false': False,
'1': True,
'y': True,
't': True,
'on': True,
'yes': True,
'true': True
}
_re_split_salt = re.compile(r'\$(?P<salt>.+)\$(?P<hash>.+)')
def write_error(self, status_code, **kwargs):
"""Default error handler."""
if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
exc = kwargs['exc_info'][1]
status_code = exc.status
message = exc.message
else:
message = 'internal error'
self.build_error(message, status=status_code)
def is_api(self):
"""Return True if the path is from an API call."""
return self.request.path.startswith('/v%s' % API_VERSION)
def tobool(self, obj):
"""Convert some textual values to boolean."""
if isinstance(obj, (list, tuple)):
obj = obj[0]
if isinstance(obj, str):
obj = obj.lower()
return self._bool_convert.get(obj, obj)
def arguments_tobool(self):
"""Return a dictionary of arguments, converted to booleans where possible."""
return dict([(k, self.tobool(v)) for k, v in self.arguments.items()])
def initialize(self, **kwargs):
"""Add every passed (key, value) as attributes of the instance."""
for key, value in kwargs.items():
setattr(self, key, value)
@property
def current_user(self):
"""Retrieve current user name from the secure cookie."""
current_user = self.get_secure_cookie("user")
if isinstance(current_user, bytes):
current_user = current_user.decode('utf-8')
return current_user
@property
def current_user_info(self):
"""Information about the current user, including their permissions."""
current_user = self.current_user
if current_user in self._users_cache:
return self._users_cache[current_user]
permissions = set([k for (k, v) in self.permissions.items() if v is True])
user_info = {'permissions': permissions}
if current_user:
user_info['_id'] = current_user
user = self.db.getOne('users', {'_id': current_user})
if user:
user_info = user
permissions.update(set(user.get('permissions') or []))
user_info['permissions'] = permissions
user_info['isRegistered'] = True
self._users_cache[current_user] = user_info
return user_info
def add_access_info(self, doc):
"""Add created/updated by/at to a document (modified in place and returned).
:param doc: the doc to be updated
:type doc: dict
:returns: the updated document
:rtype: dict"""
user_id = self.current_user
now = datetime.datetime.utcnow()
if 'created_by' not in doc:
doc['created_by'] = user_id
if 'created_at' not in doc:
doc['created_at'] = now
doc['updated_by'] = user_id
doc['updated_at'] = now
return doc
def has_permission(self, permission):
"""Check permissions of the current user.
:param permission: the permission to check
:type permission: str
:returns: True if the user is allowed to perform the action or False
:rtype: bool
"""
user_info = self.current_user_info or {}
user_permissions = user_info.get('permissions') or []
global_permission = '%s|all' % permission.split('|')[0]
if 'admin|all' in user_permissions or global_permission in user_permissions or permission in user_permissions:
return True
collection_permission = self.permissions.get(permission)
if isinstance(collection_permission, bool):
return collection_permission
if isinstance(collection_permission, collections.Callable):
return collection_permission(permission)
return False
def user_authorized(self, username, password):
"""Check if a combination of username/password is valid.
:param username: username or email
:type username: str
:param password: password
:type password: str
:returns: tuple like (bool_user_is_authorized, dict_user_info)
:rtype: dict"""
query = [{'username': username}, {'email': username}]
res = self.db.query('users', query)
if not res:
return (False, {})
user = res[0]
db_password = user.get('password') or ''
if not db_password:
return (False, {})
match = self._re_split_salt.match(db_password)
if not match:
return (False, {})
salt = match.group('salt')
if utils.hash_password(password, salt=salt) == db_password:
return (True, user)
return (False, {})
def build_error(self, message='', status=400):
"""Build and write an error message.
:param message: textual message
:type message: str
:param status: HTTP status code
:type status: int
"""
self.set_status(status)
self.write({'error': True, 'message': message})
def logout(self):
"""Remove the secure cookie used fro authentication."""
if self.current_user in self._users_cache:
del self._users_cache[self.current_user]
self.clear_cookie("user")
class RootHandler(BaseHandler):
"""Handler for the / path."""
angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
@gen.coroutine
def get(self, *args, **kwargs):
# serve the ./angular_app/index.html file
with open(self.angular_app_path + "/index.html", 'r') as fd:
self.write(fd.read())
class CollectionHandler(BaseHandler):
"""Base class for handlers that need to interact with the database backend.
Introduce basic CRUD operations."""
# set of documents we're managing (a collection in MongoDB or a table in a SQL database)
document = None
collection = None
# set of documents used to store incremental sequences
counters_collection = 'counters'
_id_chars = string.ascii_lowercase + string.digits
def get_next_seq(self, seq):
"""Increment and return the new value of a ever-incrementing counter.
:param seq: unique name of the sequence
:type seq: str
:returns: the next value of the sequence
:rtype: int
"""
if not self.db.query(self.counters_collection, {'seq_name': seq}):
self.db.add(self.counters_collection, {'seq_name': seq, 'seq': 0})
merged, doc = self.db.update(self.counters_collection,
{'seq_name': seq},
{'seq': 1},
operation='increment')
return doc.get('seq', 0)
def gen_id(self, seq='ids', random_alpha=32):
"""Generate a unique, non-guessable ID.
:param seq: the scope of the ever-incrementing sequence
:type seq: str
:param random_alpha: number of random lowercase alphanumeric chars
:type random_alpha: int
:returns: unique ID
:rtype: str"""
t = str(time.time()).replace('.', '_')
seq = str(self.get_next_seq(seq))
rand = ''.join([random.choice(self._id_chars) for x in range(random_alpha)])
return '-'.join((t, seq, rand))
def _filter_results(self, results, params):
"""Filter a list using keys and values from a dictionary.
:param results: the list to be filtered
:type results: list
:param params: a dictionary of items that must all be present in an original list item to be included in the return
:type params: dict
:returns: list of items that have all the keys with the same values as params
:rtype: list"""
if not params:
return results
params = monco.convert(params)
filtered = []
for result in results:
add = True
for key, value in params.items():
if key not in result or result[key] != value:
add = False
break
if add:
filtered.append(result)
return filtered
def _clean_dict(self, data):
"""Filter a dictionary (in place) to remove unwanted keywords in db queries.
:param data: dictionary to clean
:type data: dict"""
if isinstance(data, dict):
for key in list(data.keys()):
if (isinstance(key, str) and key.startswith('$')) or key in ('_id', 'created_by', 'created_at',
'updated_by', 'updated_at', 'isRegistered'):
del data[key]
return data
def _dict2env(self, data):
"""Convert a dictionary into a form suitable to be passed as environment variables.
:param data: dictionary to convert
:type data: dict"""
ret = {}
for key, value in data.items():
if isinstance(value, (list, tuple, dict, set)):
continue
try:
key = re_env_key.sub('', key)
key = key.upper().encode('ascii', 'ignore')
if not key:
continue
if not isinstance(value, str):
value = str(value)
ret[key] = value
except:
continue
return ret
def apply_filter(self, data, filter_name):
"""Apply a filter to the data.
:param data: the data to filter
:returns: the modified (possibly also in place) data
"""
filter_method = getattr(self, 'filter_%s' % filter_name, None)
if filter_method is not None:
data = filter_method(data)
return data
@gen.coroutine
@authenticated
def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
if resource:
# Handle access to sub-resources.
permission = '%s:%s%s|read' % (self.document, resource, '-all' if resource_id is None else '')
if acl and not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
handler = getattr(self, 'handle_get_%s' % resource, None)
if handler and isinstance(handler, collections.Callable):
output = handler(id_, resource_id, **kwargs) or {}
output = self.apply_filter(output, 'get_%s' % resource)
self.write(output)
return
return self.build_error(status=404, message='unable to access resource: %s' % resource)
if id_ is not None:
# read a single document
permission = '%s|read' % self.document
if acl and not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
output = self.db.get(self.collection, id_)
output = self.apply_filter(output, 'get')
self.write(output)
else:
# return an object containing the list of all objects in the collection;
# e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
# Please, never return JSON lists that are not encapsulated into an object,
# to avoid XSS vulnerabilities.
permission = '%s|read' % self.collection
if acl and not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
db_query = {k: v for k, v in self.arguments.items() if not k.startswith('_')}
output = {self.collection: self.db.query(self.collection, db_query)}
output = self.apply_filter(output, 'get_all')
self.write(output)
@gen.coroutine
@authenticated
def post(self, id_=None, resource=None, resource_id=None, _rawData=None, **kwargs):
if _rawData:
data = _rawData
else:
data = escape.json_decode(self.request.body or '{}')
self._clean_dict(data)
method = self.request.method.lower()
crud_method = 'create' if method == 'post' else 'update'
env = {}
if id_ is not None:
env['%s_ID' % self.document.upper()] = id_
self.add_access_info(data)
if resource:
permission = '%s:%s%s|%s' % (self.document, resource, '-all' if resource_id is None else '', crud_method)
if not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
# Handle access to sub-resources.
handler = getattr(self, 'handle_%s_%s' % (method, resource), None)
if handler and isinstance(handler, collections.Callable):
data = self.apply_filter(data, 'input_%s_%s' % (method, resource))
output = handler(id_, resource_id, data, **kwargs)
output = self.apply_filter(output, 'get_%s' % resource)
env['RESOURCE'] = resource
if resource_id:
env['%s_ID' % resource] = resource_id
self.run_triggers('%s_%s_%s' % ('create' if resource_id is None else 'update', self.document, resource),
stdin_data=output, env=env)
self.write(output)
return
return self.build_error(status=404, message='unable to access resource: %s' % resource)
if id_ is not None:
permission = '%s|%s' % (self.document, crud_method)
if not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
data = self.apply_filter(data, 'input_%s' % method)
merged, newData = self.db.update(self.collection, id_, data)
newData = self.apply_filter(newData, method)
self.run_triggers('update_%s' % self.document, stdin_data=newData, env=env)
else:
permission = '%s|%s' % (self.collection, crud_method)
if not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
data = self.apply_filter(data, 'input_%s_all' % method)
newData = self.db.add(self.collection, data, _id=self.gen_id())
newData = self.apply_filter(newData, '%s_all' % method)
self.run_triggers('create_%s' % self.document, stdin_data=newData, env=env)
self.write(newData)
# PUT (update an existing document) is handled by the POST (create a new document) method;
# in subclasses you can always separate sub-resources handlers like handle_post_tickets and handle_put_tickets
put = post
@gen.coroutine
@authenticated
def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
env = {}
if id_ is not None:
env['%s_ID' % self.document.upper()] = id_
if resource:
# Handle access to sub-resources.
permission = '%s:%s%s|delete' % (self.document, resource, '-all' if resource_id is None else '')
if not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
method = getattr(self, 'handle_delete_%s' % resource, None)
if method and isinstance(method, collections.Callable):
output = method(id_, resource_id, **kwargs)
env['RESOURCE'] = resource
if resource_id:
env['%s_ID' % resource] = resource_id
self.run_triggers('delete_%s_%s' % (self.document, resource), stdin_data=env, env=env)
self.write(output)
return
return self.build_error(status=404, message='unable to access resource: %s' % resource)
if id_ is not None:
permission = '%s|delete' % self.document
if not self.has_permission(permission):
return self.build_error(status=401, message='insufficient permissions: %s' % permission)
howMany = self.db.delete(self.collection, id_)
env['DELETED_ITEMS'] = howMany
self.run_triggers('delete_%s' % self.document, stdin_data=env, env=env)
else:
self.write({'success': False})
self.write({'success': True})
def on_timeout(self, cmd, pipe):
"""Kill a process that is taking too long to complete."""
logging.debug('the trigger %s is taking too long: killing it' % ' '.join(cmd))
try:
pipe.proc.kill()
except:
pass
def on_exit(self, returncode, cmd, pipe):
"""Callback executed when a subprocess execution is over."""
self.ioloop.remove_timeout(self.timeout)
logging.debug('trigger: %s returncode: %d' % (' '.join(cmd), returncode))
@gen.coroutine
def run_subprocess(self, cmd, stdin_data=None, env=None):
"""Execute the given action.
:param cmd: the command to be run with its command line arguments
:type cmd: list
:param stdin_data: data to be sent over stdin
:type stdin_data: str
:param env: environment of the process
:type env: dict
"""
self.ioloop = tornado.ioloop.IOLoop.instance()
processed_env = self._dict2env(env)
p = process.Subprocess(cmd, close_fds=True, stdin=process.Subprocess.STREAM,
stdout=process.Subprocess.STREAM, stderr=process.Subprocess.STREAM, env=processed_env)
p.set_exit_callback(lambda returncode: self.on_exit(returncode, cmd, p))
self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
lambda: self.on_timeout(cmd, p))
yield gen.Task(p.stdin.write, stdin_data.encode(ENCODING) or b'')
p.stdin.close()
out, err = yield [gen.Task(p.stdout.read_until_close),
gen.Task(p.stderr.read_until_close)]
logging.debug('trigger: %s' % ' '.join(cmd))
if out:
logging.debug('trigger stdout: %s' % out.decode(ENCODING))
if err:
logging.debug('trigger strerr: %s' % err.decode(ENCODING))
raise gen.Return((out, err))
@gen.coroutine
def run_triggers(self, action, stdin_data=None, env=None):
"""Asynchronously execute triggers for the given action.
:param action: action name; scripts in directory ./data/triggers/{action}.d will be run
:type action: str
:param stdin_data: a python dictionary that will be serialized in JSON and sent to the process over stdin
:type stdin_data: dict
:param env: environment of the process
:type stdin_data: dict
"""
if not hasattr(self, 'data_dir'):
return
logging.debug('running triggers for action "%s"' % action)
stdin_data = stdin_data or {}
try:
stdin_data = json.dumps(stdin_data)
except:
stdin_data = '{}'
for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
if not (os.path.isfile(script) and os.access(script, os.X_OK)):
continue
out, err = yield gen.Task(self.run_subprocess, [script], stdin_data, env)
def build_ws_url(self, path, proto='ws', host=None):
"""Return a WebSocket url from a path."""
try:
args = '?uuid=%s' % self.get_argument('uuid')
except:
args = ''
if not hasattr(self, 'listen_port'):
return None
return 'ws://127.0.0.1:%s/ws/%s%s' % (self.listen_port + 1, path, args)
@gen.coroutine
def send_ws_message(self, path, message):
"""Send a WebSocket message to all the connected clients.
:param path: partial path used to build the WebSocket url
:type path: str
:param message: message to send
:type message: str
"""
try:
url = self.build_ws_url(path)
if not url:
return
ws = yield tornado.websocket.websocket_connect(url)
ws.write_message(message)
ws.close()
except Exception as e:
self.logger.error('Error yielding WebSocket message: %s', e)
class EventsHandler(CollectionHandler):
"""Handle requests for Events."""
document = 'event'
collection = 'events'
def _mangle_event(self, event):
# Some in-place changes to an event
if 'tickets' in event:
valid_tickets = [t for t in event['tickets'] if not t.get('cancelled')]
event['tickets_sold'] = len(valid_tickets)
event['total_attendees'] = len([t for t in valid_tickets if t.get('attended')])
event['no_tickets_for_sale'] = False
try:
self._check_sales_datetime(event)
self._check_number_of_tickets(event)
except InputException:
event['no_tickets_for_sale'] = True
if not self.has_permission('event|write'):
event['group_id'] = ''
if '_summary' in self.arguments or not self.has_permission('tickets-all|read'):
event['tickets'] = []
return event
def filter_get(self, output):
return self._mangle_event(output)
def filter_get_all(self, output):
for event in output.get('events') or []:
self._mangle_event(event)
return output
def filter_input_post(self, data):
# Auto-generate the group_id, if missing.
if 'group_id' not in data:
data['group_id'] = self.gen_id()
return data
filter_input_post_all = filter_input_post
filter_input_put = filter_input_post
def filter_input_post_tickets(self, data):
# Avoid users to be able to auto-update their 'attendee' status.
if not self.has_permission('event|update'):
if 'attended' in data:
del data['attended']
self.add_access_info(data)
return data
filter_input_put_tickets = filter_input_post_tickets
def handle_get_group_persons(self, id_, resource_id=None):
persons = []
this_query = {'_id': id_}
this_event = self.db.query('events', this_query)[0]
group_id = this_event.get('group_id')
if group_id is None:
return {'persons': persons}
this_persons = [p for p in (this_event.get('tickets') or []) if not p.get('cancelled')]
this_emails = [_f for _f in [p.get('email') for p in this_persons] if _f]
all_query = {'group_id': group_id}
events = self.db.query('events', all_query)
for event in events:
if id_ is not None and str(event.get('_id')) == id_:
continue
persons += [p for p in (event.get('tickets') or []) if p.get('email') and p.get('email') not in this_emails]
return {'persons': persons}
def _get_ticket_data(self, ticket_id_or_query, tickets, only_one=True):
"""Filter a list of tickets returning the first item with a given _id
or which set of keys specified in a dictionary match their respective values."""
matches = []
for ticket in tickets:
if isinstance(ticket_id_or_query, dict):
if all(ticket.get(k) == v for k, v in ticket_id_or_query.items()):
matches.append(ticket)
if only_one:
break
else:
if str(ticket.get('_id')) == ticket_id_or_query:
matches.append(ticket)
if only_one:
break
if only_one:
if matches:
return matches[0]
return {}
return matches
def handle_get_tickets(self, id_, resource_id=None):
# Return every ticket registered at this event, or the information
# about a specific ticket.
query = {'_id': id_}
event = self.db.query('events', query)[0]
if resource_id:
return {'ticket': self._get_ticket_data(resource_id, event.get('tickets') or [])}
tickets = self._filter_results(event.get('tickets') or [], self.arguments)
return {'tickets': tickets}
def _check_number_of_tickets(self, event):
if self.has_permission('admin|all'):
return
number_of_tickets = event.get('number_of_tickets')
if number_of_tickets is None:
return
try:
number_of_tickets = int(number_of_tickets)
except ValueError:
return
tickets = event.get('tickets') or []
tickets = [t for t in tickets if not t.get('cancelled')]
if len(tickets) >= event['number_of_tickets']:
raise InputException('no more tickets available')
def _check_sales_datetime(self, event):
if self.has_permission('admin|all'):
return
begin_date = event.get('ticket_sales_begin_date')
begin_time = event.get('ticket_sales_begin_time')
end_date = event.get('ticket_sales_end_date')
end_time = event.get('ticket_sales_end_time')
utc = dateutil.tz.tzutc()
is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)
if begin_date is None:
begin_date = datetime.datetime.now(tz=utc).replace(hour=0, minute=0, second=0, microsecond=0)
else:
begin_date = dateutil.parser.parse(begin_date)
# Compensate UTC and DST offset, that otherwise would be added 2 times (one for date, one for time)
begin_date = begin_date + datetime.timedelta(seconds=utc_offset)
if begin_time is None:
begin_time_h = 0
begin_time_m = 0
else:
begin_time = dateutil.parser.parse(begin_time)
begin_time_h = begin_time.hour
begin_time_m = begin_time.minute
now = datetime.datetime.now(tz=utc)
begin_datetime = begin_date + datetime.timedelta(hours=begin_time_h, minutes=begin_time_m)
if now < begin_datetime:
raise InputException('ticket sales not yet started')
if end_date is None:
end_date = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=utc)
else:
end_date = dateutil.parser.parse(end_date)
end_date = end_date + datetime.timedelta(seconds=utc_offset)
if end_time is None:
end_time = end_date
end_time_h = 23
end_time_m = 59
else:
end_time = dateutil.parser.parse(end_time, yearfirst=True)
end_time_h = end_time.hour
end_time_m = end_time.minute
end_datetime = end_date + datetime.timedelta(hours=end_time_h, minutes=end_time_m+1)
if now > end_datetime:
raise InputException('ticket sales has ended')
def handle_post_tickets(self, id_, resource_id, data, _skipTriggers=False):
event = self.db.query('events', {'_id': id_})[0]
self._check_sales_datetime(event)
self._check_number_of_tickets(event)
uuid, arguments = self.uuid_arguments
self._clean_dict(data)
data['seq'] = self.get_next_seq('event_%s_tickets' % id_)
data['seq_hex'] = '%06X' % data['seq']
data['_id'] = ticket_id = self.gen_id()
self.add_access_info(data)
ret = {'action': 'add', 'ticket': data, 'uuid': uuid}
merged, doc = self.db.update('events',
{'_id': id_},
{'tickets': data},
operation='appendUnique',
create=False)
if doc and not _skipTriggers:
self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
ticket = self._get_ticket_data(ticket_id, doc.get('tickets') or [])
env = dict(ticket)
env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
'WEB_REMOTE_IP': self.request.remote_ip})
stdin_data = {'new': ticket,
'event': doc,
'merged': merged
}
self.run_triggers('create_ticket_in_event', stdin_data=stdin_data, env=env)
return ret
def handle_put_tickets(self, id_, ticket_id, data):
# Update an existing entry for a ticket registered at this event.
self._clean_dict(data)
uuid, arguments = self.uuid_arguments
_errorMessage = ''
if '_errorMessage' in arguments:
_errorMessage = arguments['_errorMessage']
del arguments['_errorMessage']
_searchFor = False
if '_searchFor' in arguments:
_searchFor = arguments['_searchFor']
del arguments['_searchFor']
query = dict([('tickets.%s' % k, v) for k, v in arguments.items()])
query['_id'] = id_
if ticket_id is not None:
query['tickets._id'] = ticket_id
ticket_query = {'_id': ticket_id}
else:
ticket_query = arguments
old_ticket_data = {}
current_event = self.db.query(self.collection, query)
if current_event:
current_event = current_event[0]
else:
current_event = {}
self._check_sales_datetime(current_event)
tickets = current_event.get('tickets') or []
matching_tickets = self._get_ticket_data(ticket_query, tickets, only_one=False)
nr_matches = len(matching_tickets)
if nr_matches > 1:
ret = {'error': True, 'message': 'more than one ticket matched. %s' % _errorMessage, 'query': query,
'searchFor': _searchFor, 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
self.set_status(400)
return ret
elif nr_matches == 0:
ret = {'error': True, 'message': 'no ticket matched. %s' % _errorMessage, 'query': query,
'searchFor': _searchFor, 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
self.set_status(400)
return ret
else:
old_ticket_data = matching_tickets[0]
# We have changed the "cancelled" status of a ticket to False; check if we still have a ticket available
if 'number_of_tickets' in current_event and old_ticket_data.get('cancelled') and not data.get('cancelled'):
self._check_number_of_tickets(current_event)
self.add_access_info(data)
merged, doc = self.db.update('events', query,
data, updateList='tickets', create=False)
new_ticket_data = self._get_ticket_data(ticket_query,
doc.get('tickets') or [])
env = dict(new_ticket_data)
# always takes the ticket_id from the new ticket
ticket_id = str(new_ticket_data.get('_id'))
env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
'WEB_REMOTE_IP': self.request.remote_ip})
stdin_data = {'old': old_ticket_data,
'new': new_ticket_data,
'event': doc,
'merged': merged
}
self.run_triggers('update_ticket_in_event', stdin_data=stdin_data, env=env)
if old_ticket_data and old_ticket_data.get('attended') != new_ticket_data.get('attended'):
if new_ticket_data.get('attended'):
self.run_triggers('attends', stdin_data=stdin_data, env=env)
ret = {'action': 'update', '_id': ticket_id, 'ticket': new_ticket_data,
'uuid': uuid, 'username': self.current_user_info.get('username', '')}
if old_ticket_data != new_ticket_data:
self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
return ret
def handle_delete_tickets(self, id_, ticket_id):
# Remove a ticket (or all tickets) from the list of tickets registered at this event.
uuid, arguments = self.uuid_arguments
doc = self.db.query('events', {'_id': id_})
ret = {'action': 'delete', '_id': ticket_id, 'uuid': uuid}
if doc:
ticket = self._get_ticket_data(ticket_id, doc[0].get('tickets') or [])
ticket_query = {}
if ticket:
ticket_query['_id'] = ticket_id
merged, rdoc = self.db.update('events',
{'_id': id_},
{'tickets': ticket_query},
operation='delete',
create=False)
if ticket:
self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
env = dict(ticket)
env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
'EVENT_TITLE': rdoc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
'WEB_REMOTE_IP': self.request.remote_ip})
stdin_data = {'old': ticket,
'event': rdoc,
'merged': merged
}
self.run_triggers('delete_ticket_in_event', stdin_data=stdin_data, env=env)
return ret
class UsersHandler(CollectionHandler):
"""Handle requests for Users."""
document = 'user'
collection = 'users'
def filter_get(self, data):
if 'password' in data:
del data['password']
if '_id' in data:
# Also add a 'tickets' list with all the tickets created by this user
tickets = []
events = self.db.query('events', {'tickets.created_by': data['_id']})
for event in events:
event_title = event.get('title') or ''
event_id = str(event.get('_id'))
evt_tickets = self._filter_results(event.get('tickets') or [], {'created_by': data['_id']})
for evt_ticket in evt_tickets:
evt_ticket['event_title'] = event_title
evt_ticket['event_id'] = event_id
tickets.extend(evt_tickets)
data['tickets'] = tickets
return data
def filter_get_all(self, data):
if 'users' not in data:
return data
for user in data['users']:
if 'password' in user:
del user['password']
return data
@gen.coroutine
@authenticated
def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
if id_ is not None:
if (self.has_permission('user|read') or self.current_user == id_):
acl = False
super(UsersHandler, self).get(id_, resource, resource_id, acl=acl, **kwargs)
def filter_input_post_all(self, data):
username = (data.get('username') or '').strip()
password = (data.get('password') or '').strip()
email = (data.get('email') or '').strip()
if not (username and password):
raise InputException('missing username or password')
res = self.db.query('users', {'username': username})
if res:
raise InputException('username already exists')
return {'username': username, 'password': utils.hash_password(password),
'email': email, '_id': self.gen_id()}
def filter_input_put(self, data):
old_pwd = data.get('old_password')
new_pwd = data.get('new_password')
if old_pwd is not None:
del data['old_password']
if new_pwd is not None:
del data['new_password']
authorized, user = self.user_authorized(data['username'], old_pwd)
if not (self.has_permission('user|update') or (authorized and
self.current_user_info.get('username') == data['username'])):
raise InputException('not authorized to change password')
data['password'] = utils.hash_password(new_pwd)
if '_id' in data:
del data['_id']
if 'username' in data:
del data['username']
if 'tickets' in data:
del data['tickets']
if not self.has_permission('admin|all'):
if 'permissions' in data:
del data['permissions']
else:
if 'isAdmin' in data:
if not 'permissions' in data:
data['permissions'] = []
if 'admin|all' in data['permissions'] and not data['isAdmin']:
data['permissions'].remove('admin|all')
elif 'admin|all' not in data['permissions'] and data['isAdmin']:
data['permissions'].append('admin|all')
del data['isAdmin']
return data
@gen.coroutine
@authenticated
def put(self, id_=None, resource=None, resource_id=None, **kwargs):
if id_ is None:
return self.build_error(status=404, message='unable to access the resource')