eventman_server.py 37 KB

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