eventman_server.py 35 KB

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