eventman_server.py 35 KB

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