eventman_server.py 30 KB

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