eventman_server.py 28 KB

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