eventman_server.py 30 KB

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