eventman_server.py 32 KB

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