eventman_server.py 34 KB

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