eventman_server.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. #!/usr/bin/env python
  2. """Event Man(ager)
  3. Your friendly manager of attendees at an event.
  4. Copyright 2015-2016 Davide Alberani <da@erlug.linux.it>
  5. RaspiBO <info@raspibo.org>
  6. Licensed under the Apache License, Version 2.0 (the "License");
  7. you may not use this file except in compliance with the License.
  8. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. """
  15. import os
  16. import re
  17. import glob
  18. import json
  19. import time
  20. import string
  21. import random
  22. import logging
  23. import datetime
  24. import tornado.httpserver
  25. import tornado.ioloop
  26. import tornado.options
  27. from tornado.options import define, options
  28. import tornado.web
  29. import tornado.websocket
  30. from tornado import gen, escape, process
  31. import utils
  32. import backend
  33. ENCODING = 'utf-8'
  34. PROCESS_TIMEOUT = 60
  35. API_VERSION = '1.0'
  36. re_env_key = re.compile('[^A-Z_]+')
  37. re_slashes = re.compile(r'//+')
  38. def authenticated(method):
  39. """Decorator to handle authentication."""
  40. original_wrapper = tornado.web.authenticated(method)
  41. @tornado.web.functools.wraps(method)
  42. def my_wrapper(self, *args, **kwargs):
  43. # If no authentication was required from the command line or config file.
  44. if not self.authentication:
  45. return method(self, *args, **kwargs)
  46. # unauthenticated API calls gets redirected to /v1.0/[...]
  47. if self.is_api() and not self.current_user:
  48. self.redirect('/v%s%s' % (API_VERSION, self.get_login_url()))
  49. return
  50. return original_wrapper(self, *args, **kwargs)
  51. return my_wrapper
  52. class BaseException(Exception):
  53. """Base class for EventMan custom exceptions.
  54. :param message: text message
  55. :type message: str
  56. :param status: numeric http status code
  57. :type status: int"""
  58. def __init__(self, message, status=400):
  59. super(BaseException, self).__init__(message)
  60. self.message = message
  61. self.status = status
  62. class InputException(BaseException):
  63. """Exception raised by errors in input handling."""
  64. pass
  65. class BaseHandler(tornado.web.RequestHandler):
  66. """Base class for request handlers."""
  67. permissions = {
  68. 'event|read': True,
  69. 'event:tickets|all': True,
  70. 'event:tickets-all|create': True,
  71. 'events|read': True,
  72. 'persons|create': True,
  73. 'users|create': True
  74. }
  75. _users_cache = {}
  76. # A property to access the first value of each argument.
  77. arguments = property(lambda self: dict([(k, v[0])
  78. for k, v in self.request.arguments.iteritems()]))
  79. # A property to access both the UUID and the clean arguments.
  80. @property
  81. def uuid_arguments(self):
  82. uuid = None
  83. arguments = self.arguments
  84. if 'uuid' in arguments:
  85. uuid = arguments['uuid']
  86. del arguments['uuid']
  87. return uuid, arguments
  88. _bool_convert = {
  89. '0': False,
  90. 'n': False,
  91. 'f': False,
  92. 'no': False,
  93. 'off': False,
  94. 'false': False,
  95. '1': True,
  96. 'y': True,
  97. 't': True,
  98. 'on': True,
  99. 'yes': True,
  100. 'true': True
  101. }
  102. def write_error(self, status_code, **kwargs):
  103. """Default error handler."""
  104. if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
  105. exc = kwargs['exc_info'][1]
  106. status_code = exc.status
  107. message = exc.message
  108. else:
  109. message = 'internal error'
  110. self.build_error(message, status=status_code)
  111. def is_api(self):
  112. """Return True if the path is from an API call."""
  113. return self.request.path.startswith('/v%s' % API_VERSION)
  114. def tobool(self, obj):
  115. """Convert some textual values to boolean."""
  116. if isinstance(obj, (list, tuple)):
  117. obj = obj[0]
  118. if isinstance(obj, (str, unicode)):
  119. obj = obj.lower()
  120. return self._bool_convert.get(obj, obj)
  121. def arguments_tobool(self):
  122. """Return a dictionary of arguments, converted to booleans where possible."""
  123. return dict([(k, self.tobool(v)) for k, v in self.arguments.iteritems()])
  124. def initialize(self, **kwargs):
  125. """Add every passed (key, value) as attributes of the instance."""
  126. for key, value in kwargs.iteritems():
  127. setattr(self, key, value)
  128. @property
  129. def current_user(self):
  130. """Retrieve current user name from the secure cookie."""
  131. return self.get_secure_cookie("user")
  132. @property
  133. def current_user_info(self):
  134. """Information about the current user, including their permissions."""
  135. current_user = self.current_user
  136. if current_user in self._users_cache:
  137. return self._users_cache[current_user]
  138. permissions = set([k for (k, v) in self.permissions.iteritems() if v is True])
  139. user_info = {'permissions': permissions}
  140. if current_user:
  141. user_info['username'] = current_user
  142. res = self.db.query('users', {'username': current_user})
  143. if res:
  144. user = res[0]
  145. user_info = user
  146. permissions.update(set(user.get('permissions') or []))
  147. user_info['permissions'] = permissions
  148. self._users_cache[current_user] = user_info
  149. return user_info
  150. def has_permission(self, permission):
  151. """Check permissions of the current user.
  152. :param permission: the permission to check
  153. :type permission: str
  154. :returns: True if the user is allowed to perform the action or False
  155. :rtype: bool
  156. """
  157. user_info = self.current_user_info or {}
  158. user_permissions = user_info.get('permissions') or []
  159. global_permission = '%s|all' % permission.split('|')[0]
  160. if 'admin|all' in user_permissions or global_permission in user_permissions or permission in user_permissions:
  161. return True
  162. collection_permission = self.permissions.get(permission)
  163. if isinstance(collection_permission, bool):
  164. return collection_permission
  165. if callable(collection_permission):
  166. return collection_permission(permission)
  167. return False
  168. def build_error(self, message='', status=400):
  169. """Build and write an error message."""
  170. self.set_status(status)
  171. self.write({'error': True, 'message': message})
  172. def logout(self):
  173. """Remove the secure cookie used fro authentication."""
  174. if self.current_user in self._users_cache:
  175. del self._users_cache[self.current_user]
  176. self.clear_cookie("user")
  177. class RootHandler(BaseHandler):
  178. """Handler for the / path."""
  179. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  180. @gen.coroutine
  181. @authenticated
  182. def get(self, *args, **kwargs):
  183. # serve the ./angular_app/index.html file
  184. with open(self.angular_app_path + "/index.html", 'r') as fd:
  185. self.write(fd.read())
  186. # Keep track of WebSocket connections.
  187. _ws_clients = {}
  188. class CollectionHandler(BaseHandler):
  189. """Base class for handlers that need to interact with the database backend.
  190. Introduce basic CRUD operations."""
  191. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  192. document = None
  193. collection = None
  194. # set of documents used to store incremental sequences
  195. counters_collection = 'counters'
  196. _id_chars = string.ascii_lowercase + string.digits
  197. def get_next_seq(self, seq):
  198. """Increment and return the new value of a ever-incrementing counter.
  199. :param seq: unique name of the sequence
  200. :type seq: str
  201. :returns: the next value of the sequence
  202. :rtype: int
  203. """
  204. if not self.db.query(self.counters_collection, {'seq_name': seq}):
  205. self.db.add(self.counters_collection, {'seq_name': seq, 'seq': 0})
  206. merged, doc = self.db.update(self.counters_collection,
  207. {'seq_name': seq},
  208. {'seq': 1},
  209. operation='increment')
  210. return doc.get('seq', 0)
  211. def gen_id(self, seq='ids', random_alpha=32):
  212. """Generate a unique, non-guessable ID.
  213. :param seq: the scope of the ever-incrementing sequence
  214. :type seq: str
  215. :param random_alpha: number of random lowercase alphanumeric chars
  216. :type random_alpha: int
  217. :returns: unique ID
  218. :rtype: str"""
  219. t = str(time.time()).replace('.', '_')
  220. seq = str(self.get_next_seq(seq))
  221. rand = ''.join([random.choice(self._id_chars) for x in xrange(random_alpha)])
  222. return '-'.join((t, seq, rand))
  223. def _filter_results(self, results, params):
  224. """Filter a list using keys and values from a dictionary.
  225. :param results: the list to be filtered
  226. :type results: list
  227. :param params: a dictionary of items that must all be present in an original list item to be included in the return
  228. :type params: dict
  229. :returns: list of items that have all the keys with the same values as params
  230. :rtype: list"""
  231. if not params:
  232. return results
  233. params = backend.convert(params)
  234. filtered = []
  235. for result in results:
  236. add = True
  237. for key, value in params.iteritems():
  238. if key not in result or result[key] != value:
  239. add = False
  240. break
  241. if add:
  242. filtered.append(result)
  243. return filtered
  244. def _clean_dict(self, data):
  245. """Filter a dictionary (in place) to remove unwanted keywords.
  246. :param data: dictionary to clean
  247. :type data: dict"""
  248. if isinstance(data, dict):
  249. for key in data.keys():
  250. if isinstance(key, (str, unicode)) and key.startswith('$'):
  251. del data[key]
  252. return data
  253. def _dict2env(self, data):
  254. """Convert a dictionary into a form suitable to be passed as environment variables.
  255. :param data: dictionary to convert
  256. :type data: dict"""
  257. ret = {}
  258. for key, value in data.iteritems():
  259. if isinstance(value, (list, tuple, dict)):
  260. continue
  261. try:
  262. key = key.upper().encode('ascii', 'ignore')
  263. key = re_env_key.sub('', key)
  264. if not key:
  265. continue
  266. ret[key] = unicode(value).encode(ENCODING)
  267. except:
  268. continue
  269. return ret
  270. def apply_filter(self, data, filter_name):
  271. """Apply a filter to the data.
  272. :param data: the data to filter
  273. :returns: the modified (possibly also in place) data
  274. """
  275. filter_method = getattr(self, 'filter_%s' % filter_name, None)
  276. if filter_method is not None:
  277. data = filter_method(data)
  278. return data
  279. @gen.coroutine
  280. @authenticated
  281. def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
  282. if resource:
  283. # Handle access to sub-resources.
  284. permission = '%s:%s%s|read' % (self.document, resource, '-all' if resource_id is None else '')
  285. if acl and not self.has_permission(permission):
  286. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  287. handler = getattr(self, 'handle_get_%s' % resource, None)
  288. if handler and callable(handler):
  289. output = handler(id_, resource_id, **kwargs) or {}
  290. output = self.apply_filter(output, 'get_%s' % resource)
  291. self.write(output)
  292. return
  293. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  294. if id_ is not None:
  295. # read a single document
  296. permission = '%s|read' % self.document
  297. if acl and not self.has_permission(permission):
  298. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  299. output = self.db.get(self.collection, id_)
  300. output = self.apply_filter(output, 'get')
  301. self.write(output)
  302. else:
  303. # return an object containing the list of all objects in the collection;
  304. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  305. # Please, never return JSON lists that are not encapsulated into an object,
  306. # to avoid XSS vulnerabilities.
  307. permission = '%s|read' % self.collection
  308. if acl and not self.has_permission(permission):
  309. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  310. output = {self.collection: self.db.query(self.collection, self.arguments)}
  311. output = self.apply_filter(output, 'get_all')
  312. self.write(output)
  313. @gen.coroutine
  314. @authenticated
  315. def post(self, id_=None, resource=None, resource_id=None, **kwargs):
  316. data = escape.json_decode(self.request.body or '{}')
  317. self._clean_dict(data)
  318. method = self.request.method.lower()
  319. crud_method = 'create' if method == 'post' else 'update'
  320. now = datetime.datetime.now()
  321. user_info = self.current_user_info
  322. user_id = user_info.get('_id')
  323. if crud_method == 'create':
  324. data['created_by'] = user_id
  325. data['created_at'] = now
  326. data['updated_by'] = user_id
  327. data['updated_at'] = now
  328. if resource:
  329. permission = '%s:%s%s|%s' % (self.document, resource, '-all' if resource_id is None else '', crud_method)
  330. if not self.has_permission(permission):
  331. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  332. # Handle access to sub-resources.
  333. handler = getattr(self, 'handle_%s_%s' % (method, resource), None)
  334. if handler and callable(handler):
  335. data = self.apply_filter(data, 'input_%s_%s' % (method, resource))
  336. output = handler(id_, resource_id, data, **kwargs)
  337. output = self.apply_filter(output, 'get_%s' % resource)
  338. self.write(output)
  339. return
  340. if id_ is not None:
  341. permission = '%s|%s' % (self.document, crud_method)
  342. if not self.has_permission(permission):
  343. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  344. data = self.apply_filter(data, 'input_%s' % method)
  345. merged, newData = self.db.update(self.collection, id_, data)
  346. newData = self.apply_filter(newData, method)
  347. else:
  348. permission = '%s|%s' % (self.collection, crud_method)
  349. if not self.has_permission(permission):
  350. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  351. data = self.apply_filter(data, 'input_%s_all' % method)
  352. newData = self.db.add(self.collection, data, _id=self.gen_id())
  353. newData = self.apply_filter(newData, '%s_all' % method)
  354. self.write(newData)
  355. # PUT (update an existing document) is handled by the POST (create a new document) method
  356. put = post
  357. @gen.coroutine
  358. @authenticated
  359. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  360. if resource:
  361. # Handle access to sub-resources.
  362. permission = '%s:%s%s|delete' % (self.document, resource, '-all' if resource_id is None else '')
  363. if not self.has_permission(permission):
  364. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  365. method = getattr(self, 'handle_delete_%s' % resource, None)
  366. if method and callable(method):
  367. self.write(method(id_, resource_id, **kwargs))
  368. return
  369. if id_:
  370. permission = '%s|delete' % self.document
  371. if not self.has_permission(permission):
  372. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  373. self.db.delete(self.collection, id_)
  374. else:
  375. self.write({'success': False})
  376. self.write({'success': True})
  377. def on_timeout(self, cmd, pipe):
  378. """Kill a process that is taking too long to complete."""
  379. logging.debug('cmd %s is taking too long: killing it' % ' '.join(cmd))
  380. try:
  381. pipe.proc.kill()
  382. except:
  383. pass
  384. def on_exit(self, returncode, cmd, pipe):
  385. """Callback executed when a subprocess execution is over."""
  386. self.ioloop.remove_timeout(self.timeout)
  387. logging.debug('cmd: %s returncode: %d' % (' '.join(cmd), returncode))
  388. @gen.coroutine
  389. def run_subprocess(self, cmd, stdin_data=None, env=None):
  390. """Execute the given action.
  391. :param cmd: the command to be run with its command line arguments
  392. :type cmd: list
  393. :param stdin_data: data to be sent over stdin
  394. :type stdin_data: str
  395. :param env: environment of the process
  396. :type env: dict
  397. """
  398. self.ioloop = tornado.ioloop.IOLoop.instance()
  399. p = process.Subprocess(cmd, close_fds=True, stdin=process.Subprocess.STREAM,
  400. stdout=process.Subprocess.STREAM, stderr=process.Subprocess.STREAM, env=env)
  401. p.set_exit_callback(lambda returncode: self.on_exit(returncode, cmd, p))
  402. self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
  403. lambda: self.on_timeout(cmd, p))
  404. yield gen.Task(p.stdin.write, stdin_data or '')
  405. p.stdin.close()
  406. out, err = yield [gen.Task(p.stdout.read_until_close),
  407. gen.Task(p.stderr.read_until_close)]
  408. logging.debug('cmd: %s' % ' '.join(cmd))
  409. logging.debug('cmd stdout: %s' % out)
  410. logging.debug('cmd strerr: %s' % err)
  411. raise gen.Return((out, err))
  412. @gen.coroutine
  413. def run_triggers(self, action, stdin_data=None, env=None):
  414. """Asynchronously execute triggers for the given action.
  415. :param action: action name; scripts in directory ./data/triggers/{action}.d will be run
  416. :type action: str
  417. :param stdin_data: a python dictionary that will be serialized in JSON and sent to the process over stdin
  418. :type stdin_data: dict
  419. :param env: environment of the process
  420. :type stdin_data: dict
  421. """
  422. logging.debug('running triggers for action "%s"' % action)
  423. stdin_data = stdin_data or {}
  424. try:
  425. stdin_data = json.dumps(stdin_data)
  426. except:
  427. stdin_data = '{}'
  428. for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
  429. if not (os.path.isfile(script) and os.access(script, os.X_OK)):
  430. continue
  431. out, err = yield gen.Task(self.run_subprocess, [script], stdin_data, env)
  432. def build_ws_url(self, path, proto='ws', host=None):
  433. """Return a WebSocket url from a path."""
  434. return 'ws://127.0.0.1:%s/ws/%s' % (self.listen_port + 1, path)
  435. @gen.coroutine
  436. def send_ws_message(self, path, message):
  437. """Send a WebSocket message to all the connected clients.
  438. :param path: partial path used to build the WebSocket url
  439. :type path: str
  440. :param message: message to send
  441. :type message: str
  442. """
  443. ws = yield tornado.websocket.websocket_connect(self.build_ws_url(path))
  444. ws.write_message(message)
  445. ws.close()
  446. class PersonsHandler(CollectionHandler):
  447. """Handle requests for Persons."""
  448. document = 'person'
  449. collection = 'persons'
  450. def handle_get_events(self, id_, resource_id=None, **kwargs):
  451. # Get a list of events attended by this person.
  452. # Inside the data of each event, a 'person_data' dictionary is
  453. # created, duplicating the entry for the current person (so that
  454. # there's no need to parse the 'persons' list on the client).
  455. #
  456. # If resource_id is given, only the specified event is considered.
  457. #
  458. # If the 'all' parameter is given, every event (also unattended ones) is returned.
  459. args = self.request.arguments
  460. query = {}
  461. if id_ and not self.tobool(args.get('all')):
  462. query = {'persons.person_id': id_}
  463. if resource_id:
  464. query['_id'] = resource_id
  465. events = self.db.query('events', query)
  466. for event in events:
  467. person_data = {}
  468. for persons in event.get('persons') or []:
  469. if str(persons.get('person_id')) == id_:
  470. person_data = persons
  471. break
  472. if 'persons' in event:
  473. del event['persons']
  474. event['person_data'] = person_data
  475. if resource_id and events:
  476. return events[0]
  477. return {'events': events}
  478. class EventsHandler(CollectionHandler):
  479. """Handle requests for Events."""
  480. document = 'event'
  481. collection = 'events'
  482. def filter_get(self, output):
  483. if not self.has_permission('persons-all|read'):
  484. if 'persons' in output:
  485. output['persons'] = []
  486. return output
  487. def filter_get_all(self, output):
  488. if not self.has_permission('persons-all|read'):
  489. for event in output.get('events') or []:
  490. if 'persons' in event:
  491. event['persons'] = []
  492. return output
  493. def filter_input_post_tickets(self, data):
  494. if not self.has_permission('event|update'):
  495. if 'attended' in data:
  496. del data['attended']
  497. return data
  498. filter_input_put_tickets = filter_input_post_tickets
  499. def _get_person_data(self, person_id_or_query, persons):
  500. """Filter a list of persons returning the first item with a given person_id
  501. or which set of keys specified in a dictionary match their respective values."""
  502. for person in persons:
  503. if isinstance(person_id_or_query, dict):
  504. if all(person.get(k) == v for k, v in person_id_or_query.iteritems()):
  505. return person
  506. else:
  507. if str(person.get('person_id')) == person_id_or_query:
  508. return person
  509. return {}
  510. def handle_get_persons(self, id_, resource_id=None, match_query=None):
  511. # Return every person registered at this event, or the information
  512. # about a specific person.
  513. query = {'_id': id_}
  514. event = self.db.query('events', query)[0]
  515. if match_query is None:
  516. match_query = resource_id
  517. if resource_id:
  518. return {'person': self._get_person_data(match_query, event.get('persons') or [])}
  519. persons = self._filter_results(event.get('persons') or [], self.arguments)
  520. return {'persons': persons}
  521. def handle_get_tickets(self, id_, resource_id=None):
  522. if resource_id is None and not self.has_permission('event:tickets|all'):
  523. return self.build_error(status=401, message='insufficient permissions: event:tickets|all')
  524. return self.handle_get_persons(id_, resource_id, {'_id': resource_id})
  525. def handle_post_persons(self, id_, person_id, data):
  526. # Add a person to the list of persons registered at this event.
  527. uuid, arguments = self.uuid_arguments
  528. self._clean_dict(data)
  529. data['seq'] = self.get_next_seq('event_%s_persons' % id_)
  530. data['seq_hex'] = '%06X' % data['seq']
  531. doc = self.db.query('events',
  532. {'_id': id_, 'persons.person_id': person_id})
  533. ret = {'action': 'add', 'person_id': person_id, 'person': data, 'uuid': uuid}
  534. if '_id' in data:
  535. del data['_id']
  536. self.send_ws_message('event/%s/updates' % id_, json.dumps(ret))
  537. if not doc:
  538. data['_id'] = self.gen_id()
  539. merged, doc = self.db.update('events',
  540. {'_id': id_},
  541. {'persons': data},
  542. operation='appendUnique',
  543. create=False)
  544. return ret
  545. handle_post_tickets = handle_post_persons
  546. def handle_put_persons(self, id_, person_id, data, ticket=False):
  547. # Update an existing entry for a person registered at this event.
  548. self._clean_dict(data)
  549. uuid, arguments = self.uuid_arguments
  550. query = dict([('persons.%s' % k, v) for k, v in arguments.iteritems()])
  551. query['_id'] = id_
  552. if ticket:
  553. query['persons._id'] = person_id
  554. person_query = {'_id': person_id}
  555. elif person_id is not None:
  556. query['persons.person_id'] = person_id
  557. person_query = person_id
  558. else:
  559. person_query = self.arguments
  560. old_person_data = {}
  561. current_event = self.db.query(self.collection, query)
  562. if current_event:
  563. current_event = current_event[0]
  564. else:
  565. current_event = {}
  566. old_person_data = self._get_person_data(person_query,
  567. current_event.get('persons') or [])
  568. merged, doc = self.db.update('events', query,
  569. data, updateList='persons', create=False)
  570. new_person_data = self._get_person_data(person_query,
  571. doc.get('persons') or [])
  572. env = self._dict2env(new_person_data)
  573. # always takes the person_id from the new person (it may have
  574. # be a ticket_id).
  575. person_id = str(new_person_data.get('person_id'))
  576. env.update({'PERSON_ID': person_id, 'EVENT_ID': id_,
  577. 'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user,
  578. 'WEB_REMOTE_IP': self.request.remote_ip})
  579. stdin_data = {'old': old_person_data,
  580. 'new': new_person_data,
  581. 'event': doc,
  582. 'merged': merged
  583. }
  584. self.run_triggers('update_person_in_event', stdin_data=stdin_data, env=env)
  585. if old_person_data and old_person_data.get('attended') != new_person_data.get('attended'):
  586. if new_person_data.get('attended'):
  587. self.run_triggers('attends', stdin_data=stdin_data, env=env)
  588. ret = {'action': 'update', 'person_id': person_id, 'person': new_person_data, 'uuid': uuid}
  589. if old_person_data != new_person_data:
  590. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  591. return ret
  592. def handle_put_tickets(self, id_, person_id, data):
  593. return self.handle_put_persons(id_, person_id, data, True)
  594. def handle_delete_persons(self, id_, person_id):
  595. # Remove a specific person from the list of persons registered at this event.
  596. uuid, arguments = self.uuid_arguments
  597. doc = self.db.query('events',
  598. {'_id': id_, 'persons.person_id': person_id})
  599. ret = {'action': 'delete', 'person_id': person_id, 'uuid': uuid}
  600. if doc:
  601. merged, doc = self.db.update('events',
  602. {'_id': id_},
  603. {'persons': {'person_id': person_id}},
  604. operation='delete',
  605. create=False)
  606. self.send_ws_message('event/%s/updates' % id_, json.dumps(ret))
  607. return ret
  608. handle_delete_tickets = handle_delete_persons
  609. class UsersHandler(CollectionHandler):
  610. """Handle requests for Users."""
  611. document = 'user'
  612. collection = 'users'
  613. def filter_input_post_all(self, data):
  614. username = (data.get('username') or '').strip()
  615. password = (data.get('password') or '').strip()
  616. email = (data.get('email') or '').strip()
  617. if not (username and password):
  618. raise InputException('missing username or password')
  619. res = self.db.query('users', {'username': username})
  620. if res:
  621. raise InputException('username already exists')
  622. return {'username': username, 'password': utils.hash_password(password),
  623. 'email': email, '_id': self.gen_id()}
  624. class EbCSVImportPersonsHandler(BaseHandler):
  625. """Importer for CSV files exported from eventbrite."""
  626. csvRemap = {
  627. 'Nome evento': 'event_title',
  628. 'ID evento': 'event_id',
  629. 'N. codice a barre': 'ebqrcode',
  630. 'Cognome acquirente': 'surname',
  631. 'Nome acquirente': 'name',
  632. 'E-mail acquirente': 'email',
  633. 'Cognome': 'surname',
  634. 'Nome': 'name',
  635. 'E-mail': 'email',
  636. 'Indirizzo e-mail': 'email',
  637. 'Tipologia biglietto': 'ticket_kind',
  638. 'Data partecipazione': 'attending_datetime',
  639. 'Data check-in': 'checkin_datetime',
  640. 'Ordine n.': 'order_nr',
  641. 'ID ordine': 'order_nr',
  642. 'Titolo professionale': 'job_title',
  643. 'Azienda': 'company',
  644. 'Prefisso': 'name_title',
  645. 'Prefisso (Sig., Sig.ra, ecc.)': 'name_title',
  646. 'Order #': 'order_nr',
  647. 'Prefix': 'name_title',
  648. 'First Name': 'name',
  649. 'Last Name': 'surname',
  650. 'Suffix': 'name_suffix',
  651. 'Email': 'email',
  652. 'Attendee #': 'attendee_nr',
  653. 'Barcode #': 'ebqrcode',
  654. 'Company': 'company',
  655. }
  656. # Only these information are stored in the person collection.
  657. keepPersonData = ('name', 'surname', 'email', 'name_title', 'name_suffix',
  658. 'company', 'job_title')
  659. @gen.coroutine
  660. @authenticated
  661. def post(self, **kwargs):
  662. # import a CSV list of persons
  663. event_handler = EventsHandler(self.application, self.request)
  664. event_handler.db = self.db
  665. targetEvent = None
  666. try:
  667. targetEvent = self.get_body_argument('targetEvent')
  668. except:
  669. pass
  670. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  671. for fieldname, contents in self.request.files.iteritems():
  672. for content in contents:
  673. filename = content['filename']
  674. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  675. reply['total'] += parseStats['total']
  676. reply['valid'] += parseStats['valid']
  677. for person in persons:
  678. person_data = dict([(k, person[k]) for k in self.keepPersonData
  679. if k in person])
  680. merged, stored_person = self.db.update('persons',
  681. [('email', 'name', 'surname')],
  682. person_data)
  683. if merged:
  684. reply['merged'] += 1
  685. if targetEvent and stored_person:
  686. event_id = targetEvent
  687. person_id = stored_person['_id']
  688. registered_data = {
  689. 'person_id': person_id,
  690. 'attended': False,
  691. 'from_file': filename}
  692. person.update(registered_data)
  693. if not self.db.query('events',
  694. {'_id': event_id, 'persons.person_id': person_id}):
  695. event_handler.handle_post_persons(event_id, person_id, person)
  696. reply['new_in_event'] += 1
  697. self.write(reply)
  698. class SettingsHandler(BaseHandler):
  699. """Handle requests for Settings."""
  700. @gen.coroutine
  701. @authenticated
  702. def get(self, **kwds):
  703. query = self.arguments_tobool()
  704. settings = self.db.query('settings', query)
  705. self.write({'settings': settings})
  706. class InfoHandler(BaseHandler):
  707. """Handle requests for Info."""
  708. @gen.coroutine
  709. @authenticated
  710. def get(self, **kwds):
  711. info = {}
  712. user_info = self.current_user_info
  713. if user_info:
  714. info['user'] = user_info
  715. self.write({'info': info})
  716. class WebSocketEventUpdatesHandler(tornado.websocket.WebSocketHandler):
  717. """Manage websockets."""
  718. def _clean_url(self, url):
  719. return re_slashes.sub('/', url)
  720. def open(self, event_id, *args, **kwds):
  721. logging.debug('WebSocketEventUpdatesHandler.on_open event_id:%s' % event_id)
  722. _ws_clients.setdefault(self._clean_url(self.request.uri), set()).add(self)
  723. logging.debug('WebSocketEventUpdatesHandler.on_open %s clients connected' % len(_ws_clients))
  724. def on_message(self, message):
  725. logging.debug('WebSocketEventUpdatesHandler.on_message')
  726. count = 0
  727. for client in _ws_clients.get(self._clean_url(self.request.uri), []):
  728. if client == self:
  729. continue
  730. client.write_message(message)
  731. count += 1
  732. logging.debug('WebSocketEventUpdatesHandler.on_message sent message to %d clients' % count)
  733. def on_close(self):
  734. logging.debug('WebSocketEventUpdatesHandler.on_close')
  735. try:
  736. if self in _ws_clients.get(self._clean_url(self.request.uri), []):
  737. _ws_clients[self._clean_url(self.request.uri)].remove(self)
  738. except Exception as e:
  739. logging.warn('WebSocketEventUpdatesHandler.on_close error closing websocket: %s', str(e))
  740. class LoginHandler(BaseHandler):
  741. """Handle user authentication requests."""
  742. re_split_salt = re.compile(r'\$(?P<salt>.+)\$(?P<hash>.+)')
  743. @gen.coroutine
  744. def get(self, **kwds):
  745. # show the login page
  746. if self.is_api():
  747. self.set_status(401)
  748. self.write({'error': True,
  749. 'message': 'authentication required'})
  750. else:
  751. with open(self.angular_app_path + "/login.html", 'r') as fd:
  752. self.write(fd.read())
  753. def _authorize(self, username, password, email=None):
  754. """Return True is this username/password is valid."""
  755. query = [{'username': username}]
  756. if email is not None:
  757. query.append({'email': email})
  758. res = self.db.query('users', query)
  759. if not res:
  760. return False
  761. user = res[0]
  762. db_password = user.get('password') or ''
  763. if not db_password:
  764. return False
  765. match = self.re_split_salt.match(db_password)
  766. if not match:
  767. return False
  768. salt = match.group('salt')
  769. if utils.hash_password(password, salt=salt) == db_password:
  770. return True
  771. return False
  772. @gen.coroutine
  773. def post(self, *args, **kwargs):
  774. # authenticate a user
  775. try:
  776. password = self.get_body_argument('password')
  777. username = self.get_body_argument('username')
  778. except tornado.web.MissingArgumentError:
  779. data = escape.json_decode(self.request.body or '{}')
  780. username = data.get('username')
  781. password = data.get('password')
  782. if not (username and password):
  783. self.set_status(401)
  784. self.write({'error': True, 'message': 'missing username or password'})
  785. return
  786. if self._authorize(username, password):
  787. logging.info('successful login for user %s' % username)
  788. self.set_secure_cookie("user", username)
  789. self.write({'error': False, 'message': 'successful login'})
  790. return
  791. logging.info('login failed for user %s' % username)
  792. self.set_status(401)
  793. self.write({'error': True, 'message': 'wrong username and password'})
  794. class LogoutHandler(BaseHandler):
  795. """Handle user logout requests."""
  796. @gen.coroutine
  797. def get(self, **kwds):
  798. # log the user out
  799. logging.info('logout')
  800. self.logout()
  801. self.write({'error': False, 'message': 'logged out'})
  802. def run():
  803. """Run the Tornado web application."""
  804. # command line arguments; can also be written in a configuration file,
  805. # specified with the --config argument.
  806. define("port", default=5242, help="run on the given port", type=int)
  807. define("address", default='', help="bind the server at the given address", type=str)
  808. define("data_dir", default=os.path.join(os.path.dirname(__file__), "data"),
  809. help="specify the directory used to store the data")
  810. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_cert.pem'),
  811. help="specify the SSL certificate to use for secure connections")
  812. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_key.pem'),
  813. help="specify the SSL private key to use for secure connections")
  814. define("mongo_url", default=None,
  815. help="URL to MongoDB server", type=str)
  816. define("db_name", default='eventman',
  817. help="Name of the MongoDB database to use", type=str)
  818. define("authentication", default=False, help="if set to true, authentication is required")
  819. define("debug", default=False, help="run in debug mode")
  820. define("config", help="read configuration file",
  821. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  822. tornado.options.parse_command_line()
  823. logger = logging.getLogger()
  824. logger.setLevel(logging.INFO)
  825. if options.debug:
  826. logger.setLevel(logging.DEBUG)
  827. # database backend connector
  828. db_connector = backend.EventManDB(url=options.mongo_url, dbName=options.db_name)
  829. init_params = dict(db=db_connector, data_dir=options.data_dir, listen_port=options.port,
  830. authentication=options.authentication, logger=logger)
  831. # If not present, we store a user 'admin' with password 'eventman' into the database.
  832. if not db_connector.query('users', {'username': 'admin'}):
  833. db_connector.add('users',
  834. {'username': 'admin', 'password': utils.hash_password('eventman'),
  835. 'permissions': ['admin|all']})
  836. # If present, use the cookie_secret stored into the database.
  837. cookie_secret = db_connector.query('settings', {'setting': 'server_cookie_secret'})
  838. if cookie_secret:
  839. cookie_secret = cookie_secret[0]['cookie_secret']
  840. else:
  841. # the salt guarantees its uniqueness
  842. cookie_secret = utils.hash_password('__COOKIE_SECRET__')
  843. db_connector.add('settings',
  844. {'setting': 'server_cookie_secret', 'cookie_secret': cookie_secret})
  845. _ws_handler = (r"/ws/+event/+(?P<event_id>[\w\d_-]+)/+tickets/+updates/?", WebSocketEventUpdatesHandler)
  846. _persons_path = r"/persons/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  847. _events_path = r"/events/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  848. _users_path = r"/users/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  849. application = tornado.web.Application([
  850. (_persons_path, PersonsHandler, init_params),
  851. (r'/v%s%s' % (API_VERSION, _persons_path), PersonsHandler, init_params),
  852. (_events_path, EventsHandler, init_params),
  853. (r'/v%s%s' % (API_VERSION, _events_path), EventsHandler, init_params),
  854. (_users_path, UsersHandler, init_params),
  855. (r'/v%s%s' % (API_VERSION, _users_path), UsersHandler, init_params),
  856. (r"/(?:index.html)?", RootHandler, init_params),
  857. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  858. (r"/settings", SettingsHandler, init_params),
  859. (r"/info", InfoHandler, init_params),
  860. _ws_handler,
  861. (r'/login', LoginHandler, init_params),
  862. (r'/v%s/login' % API_VERSION, LoginHandler, init_params),
  863. (r'/logout', LogoutHandler),
  864. (r'/v%s/logout' % API_VERSION, LogoutHandler),
  865. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  866. ],
  867. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  868. static_path=os.path.join(os.path.dirname(__file__), "static"),
  869. cookie_secret='__COOKIE_SECRET__',
  870. login_url='/login',
  871. debug=options.debug)
  872. ssl_options = {}
  873. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  874. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  875. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  876. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  877. options.address if options.address else '127.0.0.1',
  878. options.port)
  879. http_server.listen(options.port, options.address)
  880. # Also listen on options.port+1 for our local ws connection.
  881. ws_application = tornado.web.Application([_ws_handler], debug=options.debug)
  882. ws_http_server = tornado.httpserver.HTTPServer(ws_application)
  883. ws_http_server.listen(options.port+1, address='127.0.0.1')
  884. logger.debug('Starting WebSocket on ws://127.0.0.1:%d', options.port+1)
  885. tornado.ioloop.IOLoop.instance().start()
  886. if __name__ == '__main__':
  887. run()