eventman_server.py 38 KB

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