eventman_server.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """EventMan(ager)
  4. Your friendly manager of attendees at an event.
  5. Copyright 2015-2017 Davide Alberani <da@erlug.linux.it>
  6. RaspiBO <info@raspibo.org>
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. """
  16. import os
  17. import re
  18. import glob
  19. import json
  20. import time
  21. import string
  22. import random
  23. import logging
  24. import datetime
  25. import dateutil.tz
  26. import dateutil.parser
  27. import tornado.httpserver
  28. import tornado.ioloop
  29. import tornado.options
  30. from tornado.options import define, options
  31. import tornado.web
  32. import tornado.websocket
  33. from tornado import gen, escape, process
  34. import utils
  35. import monco
  36. import collections
  37. ENCODING = 'utf-8'
  38. PROCESS_TIMEOUT = 60
  39. API_VERSION = '1.0'
  40. re_env_key = re.compile('[^a-zA-Z_]+')
  41. re_slashes = re.compile(r'//+')
  42. # Keep track of WebSocket connections.
  43. _ws_clients = {}
  44. def authenticated(method):
  45. """Decorator to handle forced authentication."""
  46. original_wrapper = tornado.web.authenticated(method)
  47. @tornado.web.functools.wraps(method)
  48. def my_wrapper(self, *args, **kwargs):
  49. # If no authentication was required from the command line or config file.
  50. if not self.authentication:
  51. return method(self, *args, **kwargs)
  52. # unauthenticated API calls gets redirected to /v1.0/[...]
  53. if self.is_api() and not self.current_user:
  54. self.redirect('/v%s%s' % (API_VERSION, self.get_login_url()))
  55. return
  56. return original_wrapper(self, *args, **kwargs)
  57. return my_wrapper
  58. class BaseException(Exception):
  59. """Base class for EventMan custom exceptions.
  60. :param message: text message
  61. :type message: str
  62. :param status: numeric http status code
  63. :type status: int"""
  64. def __init__(self, message, status=400):
  65. super(BaseException, self).__init__(message)
  66. self.message = message
  67. self.status = status
  68. class InputException(BaseException):
  69. """Exception raised by errors in input handling."""
  70. pass
  71. class BaseHandler(tornado.web.RequestHandler):
  72. """Base class for request handlers."""
  73. permissions = {
  74. 'event|read': True,
  75. 'event:tickets|read': True,
  76. 'event:tickets|create': True,
  77. 'event:tickets|update': True,
  78. 'event:tickets-all|create': True,
  79. 'events|read': True,
  80. 'users|create': True
  81. }
  82. # Cache currently connected users.
  83. _users_cache = {}
  84. # A property to access the first value of each argument.
  85. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  86. for k, v in self.request.arguments.items()]))
  87. # A property to access both the UUID and the clean arguments.
  88. @property
  89. def uuid_arguments(self):
  90. uuid = None
  91. arguments = self.arguments
  92. if 'uuid' in arguments:
  93. uuid = arguments['uuid']
  94. del arguments['uuid']
  95. return uuid, arguments
  96. _bool_convert = {
  97. '0': False,
  98. 'n': False,
  99. 'f': False,
  100. 'no': False,
  101. 'off': False,
  102. 'false': False,
  103. '1': True,
  104. 'y': True,
  105. 't': True,
  106. 'on': True,
  107. 'yes': True,
  108. 'true': True
  109. }
  110. _re_split_salt = re.compile(r'\$(?P<salt>.+)\$(?P<hash>.+)')
  111. def write_error(self, status_code, **kwargs):
  112. """Default error handler."""
  113. if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
  114. exc = kwargs['exc_info'][1]
  115. status_code = exc.status
  116. message = exc.message
  117. else:
  118. message = 'internal error'
  119. self.build_error(message, status=status_code)
  120. def is_api(self):
  121. """Return True if the path is from an API call."""
  122. return self.request.path.startswith('/v%s' % API_VERSION)
  123. def tobool(self, obj):
  124. """Convert some textual values to boolean."""
  125. if isinstance(obj, (list, tuple)):
  126. obj = obj[0]
  127. if isinstance(obj, str):
  128. obj = obj.lower()
  129. return self._bool_convert.get(obj, obj)
  130. def arguments_tobool(self):
  131. """Return a dictionary of arguments, converted to booleans where possible."""
  132. return dict([(k, self.tobool(v)) for k, v in self.arguments.items()])
  133. def initialize(self, **kwargs):
  134. """Add every passed (key, value) as attributes of the instance."""
  135. for key, value in kwargs.items():
  136. setattr(self, key, value)
  137. @property
  138. def current_user(self):
  139. """Retrieve current user name from the secure cookie."""
  140. current_user = self.get_secure_cookie("user")
  141. if isinstance(current_user, bytes):
  142. current_user = current_user.decode('utf-8')
  143. return current_user
  144. @property
  145. def current_user_info(self):
  146. """Information about the current user, including their permissions."""
  147. current_user = self.current_user
  148. if current_user in self._users_cache:
  149. return self._users_cache[current_user]
  150. permissions = set([k for (k, v) in self.permissions.items() if v is True])
  151. user_info = {'permissions': permissions}
  152. if current_user:
  153. user_info['_id'] = current_user
  154. user = self.db.getOne('users', {'_id': current_user})
  155. if user:
  156. user_info = user
  157. permissions.update(set(user.get('permissions') or []))
  158. user_info['permissions'] = permissions
  159. user_info['isRegistered'] = True
  160. self._users_cache[current_user] = user_info
  161. return user_info
  162. def add_access_info(self, doc):
  163. """Add created/updated by/at to a document (modified in place and returned).
  164. :param doc: the doc to be updated
  165. :type doc: dict
  166. :returns: the updated document
  167. :rtype: dict"""
  168. user_id = self.current_user
  169. now = datetime.datetime.utcnow()
  170. if 'created_by' not in doc:
  171. doc['created_by'] = user_id
  172. if 'created_at' not in doc:
  173. doc['created_at'] = now
  174. doc['updated_by'] = user_id
  175. doc['updated_at'] = now
  176. return doc
  177. def has_permission(self, permission):
  178. """Check permissions of the current user.
  179. :param permission: the permission to check
  180. :type permission: str
  181. :returns: True if the user is allowed to perform the action or False
  182. :rtype: bool
  183. """
  184. user_info = self.current_user_info or {}
  185. user_permissions = user_info.get('permissions') or []
  186. global_permission = '%s|all' % permission.split('|')[0]
  187. if 'admin|all' in user_permissions or global_permission in user_permissions or permission in user_permissions:
  188. return True
  189. collection_permission = self.permissions.get(permission)
  190. if isinstance(collection_permission, bool):
  191. return collection_permission
  192. if isinstance(collection_permission, collections.Callable):
  193. return collection_permission(permission)
  194. return False
  195. def user_authorized(self, username, password):
  196. """Check if a combination of username/password is valid.
  197. :param username: username or email
  198. :type username: str
  199. :param password: password
  200. :type password: str
  201. :returns: tuple like (bool_user_is_authorized, dict_user_info)
  202. :rtype: dict"""
  203. query = [{'username': username}, {'email': username}]
  204. res = self.db.query('users', query)
  205. if not res:
  206. return (False, {})
  207. user = res[0]
  208. db_password = user.get('password') or ''
  209. if not db_password:
  210. return (False, {})
  211. match = self._re_split_salt.match(db_password)
  212. if not match:
  213. return (False, {})
  214. salt = match.group('salt')
  215. if utils.hash_password(password, salt=salt) == db_password:
  216. return (True, user)
  217. return (False, {})
  218. def build_error(self, message='', status=400):
  219. """Build and write an error message.
  220. :param message: textual message
  221. :type message: str
  222. :param status: HTTP status code
  223. :type status: int
  224. """
  225. self.set_status(status)
  226. self.write({'error': True, 'message': message})
  227. def logout(self):
  228. """Remove the secure cookie used fro authentication."""
  229. if self.current_user in self._users_cache:
  230. del self._users_cache[self.current_user]
  231. self.clear_cookie("user")
  232. class RootHandler(BaseHandler):
  233. """Handler for the / path."""
  234. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  235. @gen.coroutine
  236. def get(self, *args, **kwargs):
  237. # serve the ./angular_app/index.html file
  238. with open(self.angular_app_path + "/index.html", 'r') as fd:
  239. self.write(fd.read())
  240. class CollectionHandler(BaseHandler):
  241. """Base class for handlers that need to interact with the database backend.
  242. Introduce basic CRUD operations."""
  243. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  244. document = None
  245. collection = None
  246. # set of documents used to store incremental sequences
  247. counters_collection = 'counters'
  248. _id_chars = string.ascii_lowercase + string.digits
  249. def get_next_seq(self, seq):
  250. """Increment and return the new value of a ever-incrementing counter.
  251. :param seq: unique name of the sequence
  252. :type seq: str
  253. :returns: the next value of the sequence
  254. :rtype: int
  255. """
  256. if not self.db.query(self.counters_collection, {'seq_name': seq}):
  257. self.db.add(self.counters_collection, {'seq_name': seq, 'seq': 0})
  258. merged, doc = self.db.update(self.counters_collection,
  259. {'seq_name': seq},
  260. {'seq': 1},
  261. operation='increment')
  262. return doc.get('seq', 0)
  263. def gen_id(self, seq='ids', random_alpha=32):
  264. """Generate a unique, non-guessable ID.
  265. :param seq: the scope of the ever-incrementing sequence
  266. :type seq: str
  267. :param random_alpha: number of random lowercase alphanumeric chars
  268. :type random_alpha: int
  269. :returns: unique ID
  270. :rtype: str"""
  271. t = str(time.time()).replace('.', '_')
  272. seq = str(self.get_next_seq(seq))
  273. rand = ''.join([random.choice(self._id_chars) for x in range(random_alpha)])
  274. return '-'.join((t, seq, rand))
  275. def _filter_results(self, results, params):
  276. """Filter a list using keys and values from a dictionary.
  277. :param results: the list to be filtered
  278. :type results: list
  279. :param params: a dictionary of items that must all be present in an original list item to be included in the return
  280. :type params: dict
  281. :returns: list of items that have all the keys with the same values as params
  282. :rtype: list"""
  283. if not params:
  284. return results
  285. params = monco.convert(params)
  286. filtered = []
  287. for result in results:
  288. add = True
  289. for key, value in params.items():
  290. if key not in result or result[key] != value:
  291. add = False
  292. break
  293. if add:
  294. filtered.append(result)
  295. return filtered
  296. def _clean_dict(self, data):
  297. """Filter a dictionary (in place) to remove unwanted keywords in db queries.
  298. :param data: dictionary to clean
  299. :type data: dict"""
  300. if isinstance(data, dict):
  301. for key in list(data.keys()):
  302. if (isinstance(key, str) and key.startswith('$')) or key in ('_id', 'created_by', 'created_at',
  303. 'updated_by', 'updated_at', 'isRegistered'):
  304. del data[key]
  305. return data
  306. def _dict2env(self, data):
  307. """Convert a dictionary into a form suitable to be passed as environment variables.
  308. :param data: dictionary to convert
  309. :type data: dict"""
  310. ret = {}
  311. for key, value in data.items():
  312. if isinstance(value, (list, tuple, dict, set)):
  313. continue
  314. try:
  315. key = re_env_key.sub('', key)
  316. key = key.upper().encode('ascii', 'ignore')
  317. if not key:
  318. continue
  319. if not isinstance(value, str):
  320. value = str(value)
  321. ret[key] = value
  322. except:
  323. continue
  324. return ret
  325. def apply_filter(self, data, filter_name):
  326. """Apply a filter to the data.
  327. :param data: the data to filter
  328. :returns: the modified (possibly also in place) data
  329. """
  330. filter_method = getattr(self, 'filter_%s' % filter_name, None)
  331. if filter_method is not None:
  332. data = filter_method(data)
  333. return data
  334. @gen.coroutine
  335. @authenticated
  336. def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
  337. if resource:
  338. # Handle access to sub-resources.
  339. permission = '%s:%s%s|read' % (self.document, resource, '-all' if resource_id is None else '')
  340. if acl and not self.has_permission(permission):
  341. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  342. handler = getattr(self, 'handle_get_%s' % resource, None)
  343. if handler and isinstance(handler, collections.Callable):
  344. output = handler(id_, resource_id, **kwargs) or {}
  345. output = self.apply_filter(output, 'get_%s' % resource)
  346. self.write(output)
  347. return
  348. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  349. if id_ is not None:
  350. # read a single document
  351. permission = '%s|read' % self.document
  352. if acl and not self.has_permission(permission):
  353. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  354. output = self.db.get(self.collection, id_)
  355. output = self.apply_filter(output, 'get')
  356. self.write(output)
  357. else:
  358. # return an object containing the list of all objects in the collection;
  359. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  360. # Please, never return JSON lists that are not encapsulated into an object,
  361. # to avoid XSS vulnerabilities.
  362. permission = '%s|read' % self.collection
  363. if acl and not self.has_permission(permission):
  364. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  365. output = {self.collection: self.db.query(self.collection, self.arguments)}
  366. output = self.apply_filter(output, 'get_all')
  367. self.write(output)
  368. @gen.coroutine
  369. @authenticated
  370. def post(self, id_=None, resource=None, resource_id=None, **kwargs):
  371. data = escape.json_decode(self.request.body or '{}')
  372. self._clean_dict(data)
  373. method = self.request.method.lower()
  374. crud_method = 'create' if method == 'post' else 'update'
  375. env = {}
  376. if id_ is not None:
  377. env['%s_ID' % self.document.upper()] = id_
  378. self.add_access_info(data)
  379. if resource:
  380. permission = '%s:%s%s|%s' % (self.document, resource, '-all' if resource_id is None else '', crud_method)
  381. if not self.has_permission(permission):
  382. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  383. # Handle access to sub-resources.
  384. handler = getattr(self, 'handle_%s_%s' % (method, resource), None)
  385. if handler and isinstance(handler, collections.Callable):
  386. data = self.apply_filter(data, 'input_%s_%s' % (method, resource))
  387. output = handler(id_, resource_id, data, **kwargs)
  388. output = self.apply_filter(output, 'get_%s' % resource)
  389. env['RESOURCE'] = resource
  390. if resource_id:
  391. env['%s_ID' % resource] = resource_id
  392. self.run_triggers('%s_%s_%s' % ('create' if resource_id is None else 'update', self.document, resource),
  393. stdin_data=output, env=env)
  394. self.write(output)
  395. return
  396. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  397. if id_ is not None:
  398. permission = '%s|%s' % (self.document, crud_method)
  399. if not self.has_permission(permission):
  400. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  401. data = self.apply_filter(data, 'input_%s' % method)
  402. merged, newData = self.db.update(self.collection, id_, data)
  403. newData = self.apply_filter(newData, method)
  404. self.run_triggers('update_%s' % self.document, stdin_data=newData, env=env)
  405. else:
  406. permission = '%s|%s' % (self.collection, crud_method)
  407. if not self.has_permission(permission):
  408. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  409. data = self.apply_filter(data, 'input_%s_all' % method)
  410. newData = self.db.add(self.collection, data, _id=self.gen_id())
  411. newData = self.apply_filter(newData, '%s_all' % method)
  412. self.run_triggers('create_%s' % self.document, stdin_data=newData, env=env)
  413. self.write(newData)
  414. # PUT (update an existing document) is handled by the POST (create a new document) method;
  415. # in subclasses you can always separate sub-resources handlers like handle_post_tickets and handle_put_tickets
  416. put = post
  417. @gen.coroutine
  418. @authenticated
  419. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  420. env = {}
  421. if id_ is not None:
  422. env['%s_ID' % self.document.upper()] = id_
  423. if resource:
  424. # Handle access to sub-resources.
  425. permission = '%s:%s%s|delete' % (self.document, resource, '-all' if resource_id is None else '')
  426. if not self.has_permission(permission):
  427. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  428. method = getattr(self, 'handle_delete_%s' % resource, None)
  429. if method and isinstance(method, collections.Callable):
  430. output = method(id_, resource_id, **kwargs)
  431. env['RESOURCE'] = resource
  432. if resource_id:
  433. env['%s_ID' % resource] = resource_id
  434. self.run_triggers('delete_%s_%s' % (self.document, resource), stdin_data=env, env=env)
  435. self.write(output)
  436. return
  437. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  438. if id_ is not None:
  439. permission = '%s|delete' % self.document
  440. if not self.has_permission(permission):
  441. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  442. howMany = self.db.delete(self.collection, id_)
  443. env['DELETED_ITEMS'] = howMany
  444. self.run_triggers('delete_%s' % self.document, stdin_data=env, env=env)
  445. else:
  446. self.write({'success': False})
  447. self.write({'success': True})
  448. def on_timeout(self, cmd, pipe):
  449. """Kill a process that is taking too long to complete."""
  450. logging.debug('cmd %s is taking too long: killing it' % ' '.join(cmd))
  451. try:
  452. pipe.proc.kill()
  453. except:
  454. pass
  455. def on_exit(self, returncode, cmd, pipe):
  456. """Callback executed when a subprocess execution is over."""
  457. self.ioloop.remove_timeout(self.timeout)
  458. logging.debug('cmd: %s returncode: %d' % (' '.join(cmd), returncode))
  459. @gen.coroutine
  460. def run_subprocess(self, cmd, stdin_data=None, env=None):
  461. """Execute the given action.
  462. :param cmd: the command to be run with its command line arguments
  463. :type cmd: list
  464. :param stdin_data: data to be sent over stdin
  465. :type stdin_data: str
  466. :param env: environment of the process
  467. :type env: dict
  468. """
  469. self.ioloop = tornado.ioloop.IOLoop.instance()
  470. processed_env = self._dict2env(env)
  471. p = process.Subprocess(cmd, close_fds=True, stdin=process.Subprocess.STREAM,
  472. stdout=process.Subprocess.STREAM, stderr=process.Subprocess.STREAM, env=processed_env)
  473. p.set_exit_callback(lambda returncode: self.on_exit(returncode, cmd, p))
  474. self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
  475. lambda: self.on_timeout(cmd, p))
  476. yield gen.Task(p.stdin.write, stdin_data.encode(ENCODING) or b'')
  477. p.stdin.close()
  478. out, err = yield [gen.Task(p.stdout.read_until_close),
  479. gen.Task(p.stderr.read_until_close)]
  480. logging.debug('cmd: %s' % ' '.join(cmd))
  481. logging.debug('cmd stdout: %s' % out)
  482. logging.debug('cmd strerr: %s' % err)
  483. raise gen.Return((out, err))
  484. @gen.coroutine
  485. def run_triggers(self, action, stdin_data=None, env=None):
  486. """Asynchronously execute triggers for the given action.
  487. :param action: action name; scripts in directory ./data/triggers/{action}.d will be run
  488. :type action: str
  489. :param stdin_data: a python dictionary that will be serialized in JSON and sent to the process over stdin
  490. :type stdin_data: dict
  491. :param env: environment of the process
  492. :type stdin_data: dict
  493. """
  494. if not hasattr(self, 'data_dir'):
  495. return
  496. logging.debug('running triggers for action "%s"' % action)
  497. stdin_data = stdin_data or {}
  498. try:
  499. stdin_data = json.dumps(stdin_data)
  500. except:
  501. stdin_data = '{}'
  502. for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
  503. if not (os.path.isfile(script) and os.access(script, os.X_OK)):
  504. continue
  505. out, err = yield gen.Task(self.run_subprocess, [script], stdin_data, env)
  506. def build_ws_url(self, path, proto='ws', host=None):
  507. """Return a WebSocket url from a path."""
  508. try:
  509. args = '?uuid=%s' % self.get_argument('uuid')
  510. except:
  511. args = ''
  512. return 'ws://127.0.0.1:%s/ws/%s%s' % (self.listen_port + 1, path, args)
  513. @gen.coroutine
  514. def send_ws_message(self, path, message):
  515. """Send a WebSocket message to all the connected clients.
  516. :param path: partial path used to build the WebSocket url
  517. :type path: str
  518. :param message: message to send
  519. :type message: str
  520. """
  521. try:
  522. ws = yield tornado.websocket.websocket_connect(self.build_ws_url(path))
  523. ws.write_message(message)
  524. ws.close()
  525. except Exception as e:
  526. self.logger.error('Error yielding WebSocket message: %s', e)
  527. class EventsHandler(CollectionHandler):
  528. """Handle requests for Events."""
  529. document = 'event'
  530. collection = 'events'
  531. def _mangle_event(self, event):
  532. # Some in-place changes to an event
  533. if 'tickets' in event:
  534. event['tickets_sold'] = len([t for t in event['tickets'] if not t.get('cancelled')])
  535. event['no_tickets_for_sale'] = False
  536. try:
  537. self._check_sales_datetime(event)
  538. self._check_number_of_tickets(event)
  539. except InputException:
  540. event['no_tickets_for_sale'] = True
  541. if not self.has_permission('tickets-all|read'):
  542. event['tickets'] = []
  543. return event
  544. def filter_get(self, output):
  545. return self._mangle_event(output)
  546. def filter_get_all(self, output):
  547. for event in output.get('events') or []:
  548. self._mangle_event(event)
  549. return output
  550. def filter_input_post(self, data):
  551. # Auto-generate the group_id, if missing.
  552. if 'group_id' not in data:
  553. data['group_id'] = self.gen_id()
  554. return data
  555. filter_input_post_all = filter_input_post
  556. filter_input_put = filter_input_post
  557. def filter_input_post_tickets(self, data):
  558. # Avoid users to be able to auto-update their 'attendee' status.
  559. if not self.has_permission('event|update'):
  560. if 'attended' in data:
  561. del data['attended']
  562. self.add_access_info(data)
  563. return data
  564. filter_input_put_tickets = filter_input_post_tickets
  565. def handle_get_group_persons(self, id_, resource_id=None):
  566. persons = []
  567. this_query = {'_id': id_}
  568. this_event = self.db.query('events', this_query)[0]
  569. group_id = this_event.get('group_id')
  570. if group_id is None:
  571. return {'persons': persons}
  572. this_persons = [p for p in (this_event.get('tickets') or []) if not p.get('cancelled')]
  573. this_emails = [_f for _f in [p.get('email') for p in this_persons] if _f]
  574. all_query = {'group_id': group_id}
  575. events = self.db.query('events', all_query)
  576. for event in events:
  577. if id_ is not None and str(event.get('_id')) == id_:
  578. continue
  579. persons += [p for p in (event.get('tickets') or []) if p.get('email') and p.get('email') not in this_emails]
  580. return {'persons': persons}
  581. def _get_ticket_data(self, ticket_id_or_query, tickets, only_one=True):
  582. """Filter a list of tickets returning the first item with a given _id
  583. or which set of keys specified in a dictionary match their respective values."""
  584. matches = []
  585. for ticket in tickets:
  586. if isinstance(ticket_id_or_query, dict):
  587. if all(ticket.get(k) == v for k, v in ticket_id_or_query.items()):
  588. matches.append(ticket)
  589. if only_one:
  590. break
  591. else:
  592. if str(ticket.get('_id')) == ticket_id_or_query:
  593. matches.append(ticket)
  594. if only_one:
  595. break
  596. if only_one:
  597. if matches:
  598. return matches[0]
  599. return {}
  600. return matches
  601. def handle_get_tickets(self, id_, resource_id=None):
  602. # Return every ticket registered at this event, or the information
  603. # about a specific ticket.
  604. query = {'_id': id_}
  605. event = self.db.query('events', query)[0]
  606. if resource_id:
  607. return {'ticket': self._get_ticket_data(resource_id, event.get('tickets') or [])}
  608. tickets = self._filter_results(event.get('tickets') or [], self.arguments)
  609. return {'tickets': tickets}
  610. def _check_number_of_tickets(self, event):
  611. if self.has_permission('admin|all'):
  612. return
  613. number_of_tickets = event.get('number_of_tickets')
  614. if number_of_tickets is None:
  615. return
  616. try:
  617. number_of_tickets = int(number_of_tickets)
  618. except ValueError:
  619. return
  620. tickets = event.get('tickets') or []
  621. tickets = [t for t in tickets if not t.get('cancelled')]
  622. if len(tickets) >= event['number_of_tickets']:
  623. raise InputException('no more tickets available')
  624. def _check_sales_datetime(self, event):
  625. if self.has_permission('admin|all'):
  626. return
  627. begin_date = event.get('ticket_sales_begin_date')
  628. begin_time = event.get('ticket_sales_begin_time')
  629. end_date = event.get('ticket_sales_end_date')
  630. end_time = event.get('ticket_sales_end_time')
  631. utc = dateutil.tz.tzutc()
  632. is_dst = time.daylight and time.localtime().tm_isdst > 0
  633. utc_offset = - (time.altzone if is_dst else time.timezone)
  634. if begin_date is None:
  635. begin_date = datetime.datetime.now(tz=utc).replace(hour=0, minute=0, second=0, microsecond=0)
  636. else:
  637. begin_date = dateutil.parser.parse(begin_date)
  638. # Compensate UTC and DST offset, that otherwise would be added 2 times (one for date, one for time)
  639. begin_date = begin_date + datetime.timedelta(seconds=utc_offset)
  640. if begin_time is None:
  641. begin_time_h = 0
  642. begin_time_m = 0
  643. else:
  644. begin_time = dateutil.parser.parse(begin_time)
  645. begin_time_h = begin_time.hour
  646. begin_time_m = begin_time.minute
  647. now = datetime.datetime.now(tz=utc)
  648. begin_datetime = begin_date + datetime.timedelta(hours=begin_time_h, minutes=begin_time_m)
  649. if now < begin_datetime:
  650. raise InputException('ticket sales not yet started')
  651. if end_date is None:
  652. end_date = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=utc)
  653. else:
  654. end_date = dateutil.parser.parse(end_date)
  655. end_date = end_date + datetime.timedelta(seconds=utc_offset)
  656. if end_time is None:
  657. end_time = end_date
  658. end_time_h = 23
  659. end_time_m = 59
  660. else:
  661. end_time = dateutil.parser.parse(end_time, yearfirst=True)
  662. end_time_h = end_time.hour
  663. end_time_m = end_time.minute
  664. end_datetime = end_date + datetime.timedelta(hours=end_time_h, minutes=end_time_m+1)
  665. if now > end_datetime:
  666. raise InputException('ticket sales has ended')
  667. def handle_post_tickets(self, id_, resource_id, data):
  668. event = self.db.query('events', {'_id': id_})[0]
  669. self._check_sales_datetime(event)
  670. self._check_number_of_tickets(event)
  671. uuid, arguments = self.uuid_arguments
  672. self._clean_dict(data)
  673. data['seq'] = self.get_next_seq('event_%s_tickets' % id_)
  674. data['seq_hex'] = '%06X' % data['seq']
  675. data['_id'] = ticket_id = self.gen_id()
  676. self.add_access_info(data)
  677. ret = {'action': 'add', 'ticket': data, 'uuid': uuid}
  678. merged, doc = self.db.update('events',
  679. {'_id': id_},
  680. {'tickets': data},
  681. operation='appendUnique',
  682. create=False)
  683. if doc:
  684. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  685. ticket = self._get_ticket_data(ticket_id, doc.get('tickets') or [])
  686. env = dict(ticket)
  687. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  688. 'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
  689. 'WEB_REMOTE_IP': self.request.remote_ip})
  690. stdin_data = {'new': ticket,
  691. 'event': doc,
  692. 'merged': merged
  693. }
  694. self.run_triggers('create_ticket_in_event', stdin_data=stdin_data, env=env)
  695. return ret
  696. def handle_put_tickets(self, id_, ticket_id, data):
  697. # Update an existing entry for a ticket registered at this event.
  698. self._clean_dict(data)
  699. uuid, arguments = self.uuid_arguments
  700. _errorMessage = ''
  701. if '_errorMessage' in arguments:
  702. _errorMessage = arguments['_errorMessage']
  703. del arguments['_errorMessage']
  704. query = dict([('tickets.%s' % k, v) for k, v in arguments.items()])
  705. query['_id'] = id_
  706. if ticket_id is not None:
  707. query['tickets._id'] = ticket_id
  708. ticket_query = {'_id': ticket_id}
  709. else:
  710. ticket_query = arguments
  711. old_ticket_data = {}
  712. current_event = self.db.query(self.collection, query)
  713. if current_event:
  714. current_event = current_event[0]
  715. else:
  716. current_event = {}
  717. self._check_sales_datetime(current_event)
  718. tickets = current_event.get('tickets') or []
  719. matching_tickets = self._get_ticket_data(ticket_query, tickets, only_one=False)
  720. nr_matches = len(matching_tickets)
  721. if nr_matches > 1:
  722. ret = {'error': True, 'message': 'more than one ticket matched. %s' % _errorMessage, 'query': query,
  723. 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
  724. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  725. self.set_status(400)
  726. return ret
  727. elif nr_matches == 0:
  728. ret = {'error': True, 'message': 'no ticket matched. %s' % _errorMessage, 'query': query,
  729. 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
  730. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  731. self.set_status(400)
  732. return ret
  733. else:
  734. old_ticket_data = matching_tickets[0]
  735. # We have changed the "cancelled" status of a ticket to False; check if we still have a ticket available
  736. if 'number_of_tickets' in current_event and old_ticket_data.get('cancelled') and not data.get('cancelled'):
  737. self._check_number_of_tickets(current_event)
  738. self.add_access_info(data)
  739. merged, doc = self.db.update('events', query,
  740. data, updateList='tickets', create=False)
  741. new_ticket_data = self._get_ticket_data(ticket_query,
  742. doc.get('tickets') or [])
  743. env = dict(new_ticket_data)
  744. # always takes the ticket_id from the new ticket
  745. ticket_id = str(new_ticket_data.get('_id'))
  746. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  747. 'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
  748. 'WEB_REMOTE_IP': self.request.remote_ip})
  749. stdin_data = {'old': old_ticket_data,
  750. 'new': new_ticket_data,
  751. 'event': doc,
  752. 'merged': merged
  753. }
  754. self.run_triggers('update_ticket_in_event', stdin_data=stdin_data, env=env)
  755. if old_ticket_data and old_ticket_data.get('attended') != new_ticket_data.get('attended'):
  756. if new_ticket_data.get('attended'):
  757. self.run_triggers('attends', stdin_data=stdin_data, env=env)
  758. ret = {'action': 'update', '_id': ticket_id, 'ticket': new_ticket_data,
  759. 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
  760. if old_ticket_data != new_ticket_data:
  761. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  762. return ret
  763. def handle_delete_tickets(self, id_, ticket_id):
  764. # Remove a specific ticket from the list of tickets registered at this event.
  765. uuid, arguments = self.uuid_arguments
  766. doc = self.db.query('events',
  767. {'_id': id_, 'tickets._id': ticket_id})
  768. ret = {'action': 'delete', '_id': ticket_id, 'uuid': uuid}
  769. if doc:
  770. ticket = self._get_ticket_data(ticket_id, doc[0].get('tickets') or [])
  771. merged, rdoc = self.db.update('events',
  772. {'_id': id_},
  773. {'tickets': {'_id': ticket_id}},
  774. operation='delete',
  775. create=False)
  776. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  777. env = dict(ticket)
  778. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  779. 'EVENT_TITLE': rdoc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
  780. 'WEB_REMOTE_IP': self.request.remote_ip})
  781. stdin_data = {'old': ticket,
  782. 'event': rdoc,
  783. 'merged': merged
  784. }
  785. self.run_triggers('delete_ticket_in_event', stdin_data=stdin_data, env=env)
  786. return ret
  787. class UsersHandler(CollectionHandler):
  788. """Handle requests for Users."""
  789. document = 'user'
  790. collection = 'users'
  791. def filter_get(self, data):
  792. if 'password' in data:
  793. del data['password']
  794. if '_id' in data:
  795. # Also add a 'tickets' list with all the tickets created by this user
  796. tickets = []
  797. events = self.db.query('events', {'tickets.created_by': data['_id']})
  798. for event in events:
  799. event_title = event.get('title') or ''
  800. event_id = str(event.get('_id'))
  801. evt_tickets = self._filter_results(event.get('tickets') or [], {'created_by': data['_id']})
  802. for evt_ticket in evt_tickets:
  803. evt_ticket['event_title'] = event_title
  804. evt_ticket['event_id'] = event_id
  805. tickets.extend(evt_tickets)
  806. data['tickets'] = tickets
  807. return data
  808. def filter_get_all(self, data):
  809. if 'users' not in data:
  810. return data
  811. for user in data['users']:
  812. if 'password' in user:
  813. del user['password']
  814. return data
  815. @gen.coroutine
  816. @authenticated
  817. def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
  818. if id_ is not None:
  819. if (self.has_permission('user|read') or self.current_user == id_):
  820. acl = False
  821. super(UsersHandler, self).get(id_, resource, resource_id, acl=acl, **kwargs)
  822. def filter_input_post_all(self, data):
  823. username = (data.get('username') or '').strip()
  824. password = (data.get('password') or '').strip()
  825. email = (data.get('email') or '').strip()
  826. if not (username and password):
  827. raise InputException('missing username or password')
  828. res = self.db.query('users', {'username': username})
  829. if res:
  830. raise InputException('username already exists')
  831. return {'username': username, 'password': utils.hash_password(password),
  832. 'email': email, '_id': self.gen_id()}
  833. def filter_input_put(self, data):
  834. old_pwd = data.get('old_password')
  835. new_pwd = data.get('new_password')
  836. if old_pwd is not None:
  837. del data['old_password']
  838. if new_pwd is not None:
  839. del data['new_password']
  840. authorized, user = self.user_authorized(data['username'], old_pwd)
  841. if not (self.has_permission('user|update') or (authorized and
  842. self.current_user_info.get('username') == data['username'])):
  843. raise InputException('not authorized to change password')
  844. data['password'] = utils.hash_password(new_pwd)
  845. if '_id' in data:
  846. del data['_id']
  847. if 'username' in data:
  848. del data['username']
  849. if not self.has_permission('admin|all'):
  850. if 'permissions' in data:
  851. del data['permissions']
  852. else:
  853. if 'isAdmin' in data:
  854. if not 'permissions' in data:
  855. data['permissions'] = []
  856. if 'admin|all' in data['permissions'] and not data['isAdmin']:
  857. data['permissions'].remove('admin|all')
  858. elif 'admin|all' not in data['permissions'] and data['isAdmin']:
  859. data['permissions'].append('admin|all')
  860. del data['isAdmin']
  861. return data
  862. @gen.coroutine
  863. @authenticated
  864. def put(self, id_=None, resource=None, resource_id=None, **kwargs):
  865. if id_ is None:
  866. return self.build_error(status=404, message='unable to access the resource')
  867. if not (self.has_permission('user|update') or self.current_user == id_):
  868. return self.build_error(status=401, message='insufficient permissions: user|update or current user')
  869. super(UsersHandler, self).put(id_, resource, resource_id, **kwargs)
  870. class EbCSVImportPersonsHandler(BaseHandler):
  871. """Importer for CSV files exported from Eventbrite."""
  872. csvRemap = {
  873. 'Nome evento': 'event_title',
  874. 'ID evento': 'event_id',
  875. 'N. codice a barre': 'ebqrcode',
  876. 'Cognome acquirente': 'surname',
  877. 'Nome acquirente': 'name',
  878. 'E-mail acquirente': 'email',
  879. 'Cognome': 'surname',
  880. 'Nome': 'name',
  881. 'E-mail': 'email',
  882. 'Indirizzo e-mail': 'email',
  883. 'Tipologia biglietto': 'ticket_kind',
  884. 'Data partecipazione': 'attending_datetime',
  885. 'Data check-in': 'checkin_datetime',
  886. 'Ordine n.': 'order_nr',
  887. 'ID ordine': 'order_nr',
  888. 'Titolo professionale': 'job title',
  889. 'Azienda': 'company',
  890. 'Prefisso': 'name_title',
  891. 'Prefisso (Sig., Sig.ra, ecc.)': 'name title',
  892. 'Order #': 'order_nr',
  893. 'Prefix': 'name title',
  894. 'First Name': 'name',
  895. 'Last Name': 'surname',
  896. 'Suffix': 'name suffix',
  897. 'Email': 'email',
  898. 'Attendee #': 'attendee_nr',
  899. 'Barcode #': 'ebqrcode',
  900. 'Company': 'company'
  901. }
  902. @gen.coroutine
  903. @authenticated
  904. def post(self, **kwargs):
  905. # import a CSV list of persons
  906. event_handler = EventsHandler(self.application, self.request)
  907. event_handler.db = self.db
  908. event_handler.logger = self.logger
  909. event_id = None
  910. try:
  911. event_id = self.get_body_argument('targetEvent')
  912. except:
  913. pass
  914. if event_id is None:
  915. return self.build_error('invalid event')
  916. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  917. event_details = event_handler.db.query('events', {'_id': event_id})
  918. if not event_details:
  919. return self.build_error('invalid event')
  920. all_emails = set()
  921. #[x.get('email') for x in (event_details[0].get('tickets') or []) if x.get('email')])
  922. for ticket in (event_details[0].get('tickets') or []):
  923. all_emails.add('%s_%s_%s' % (ticket.get('name'), ticket.get('surname'), ticket.get('email')))
  924. for fieldname, contents in self.request.files.items():
  925. for content in contents:
  926. filename = content['filename']
  927. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  928. reply['total'] += parseStats['total']
  929. for person in persons:
  930. if not person:
  931. continue
  932. reply['valid'] += 1
  933. person['attended'] = False
  934. person['from_file'] = filename
  935. self.add_access_info(person)
  936. duplicate_check = '%s_%s_%s' % (person.get('name'), person.get('surname'), person.get('email'))
  937. if duplicate_check in all_emails:
  938. continue
  939. all_emails.add(duplicate_check)
  940. event_handler.handle_post_tickets(event_id, None, person)
  941. reply['new_in_event'] += 1
  942. self.write(reply)
  943. class SettingsHandler(BaseHandler):
  944. """Handle requests for Settings."""
  945. @gen.coroutine
  946. @authenticated
  947. def get(self, **kwargs):
  948. query = self.arguments_tobool()
  949. settings = self.db.query('settings', query)
  950. self.write({'settings': settings})
  951. class InfoHandler(BaseHandler):
  952. """Handle requests for information about the logged in user."""
  953. @gen.coroutine
  954. def get(self, **kwargs):
  955. info = {}
  956. user_info = self.current_user_info
  957. if user_info:
  958. info['user'] = user_info
  959. info['authentication_required'] = self.authentication
  960. self.write({'info': info})
  961. class WebSocketEventUpdatesHandler(tornado.websocket.WebSocketHandler):
  962. """Manage WebSockets."""
  963. def _clean_url(self, url):
  964. url = re_slashes.sub('/', url)
  965. ridx = url.rfind('?')
  966. if ridx != -1:
  967. url = url[:ridx]
  968. return url
  969. def open(self, event_id, *args, **kwargs):
  970. try:
  971. self.uuid = self.get_argument('uuid')
  972. except:
  973. self.uuid = None
  974. url = self._clean_url(self.request.uri)
  975. logging.debug('WebSocketEventUpdatesHandler.on_open event_id:%s url:%s' % (event_id, url))
  976. _ws_clients.setdefault(url, {})
  977. if self.uuid and self.uuid not in _ws_clients[url]:
  978. _ws_clients[url][self.uuid] = self
  979. logging.debug('WebSocketEventUpdatesHandler.on_open %s clients connected' % len(_ws_clients[url]))
  980. def on_message(self, message):
  981. url = self._clean_url(self.request.uri)
  982. logging.debug('WebSocketEventUpdatesHandler.on_message url:%s' % url)
  983. count = 0
  984. _to_delete = set()
  985. for uuid, client in _ws_clients.get(url, {}).items():
  986. try:
  987. client.write_message(message)
  988. except:
  989. _to_delete.add(uuid)
  990. continue
  991. count += 1
  992. for uuid in _to_delete:
  993. try:
  994. del _ws_clients[url][uuid]
  995. except KeyError:
  996. pass
  997. logging.debug('WebSocketEventUpdatesHandler.on_message sent message to %d clients' % count)
  998. class LoginHandler(RootHandler):
  999. """Handle user authentication requests."""
  1000. @gen.coroutine
  1001. def get(self, **kwargs):
  1002. # show the login page
  1003. if self.is_api():
  1004. self.set_status(401)
  1005. self.write({'error': True,
  1006. 'message': 'authentication required'})
  1007. @gen.coroutine
  1008. def post(self, *args, **kwargs):
  1009. # authenticate a user
  1010. try:
  1011. password = self.get_body_argument('password')
  1012. username = self.get_body_argument('username')
  1013. except tornado.web.MissingArgumentError:
  1014. data = escape.json_decode(self.request.body or '{}')
  1015. username = data.get('username')
  1016. password = data.get('password')
  1017. if not (username and password):
  1018. self.set_status(401)
  1019. self.write({'error': True, 'message': 'missing username or password'})
  1020. return
  1021. authorized, user = self.user_authorized(username, password)
  1022. if authorized and 'username' in user and '_id' in user:
  1023. id_ = str(user['_id'])
  1024. username = user['username']
  1025. logging.info('successful login for user %s (id: %s)' % (username, id_))
  1026. self.set_secure_cookie("user", id_)
  1027. self.write({'error': False, 'message': 'successful login'})
  1028. return
  1029. logging.info('login failed for user %s' % username)
  1030. self.set_status(401)
  1031. self.write({'error': True, 'message': 'wrong username and password'})
  1032. class LogoutHandler(BaseHandler):
  1033. """Handle user logout requests."""
  1034. @gen.coroutine
  1035. def get(self, **kwargs):
  1036. # log the user out
  1037. logging.info('logout')
  1038. self.logout()
  1039. self.write({'error': False, 'message': 'logged out'})
  1040. def run():
  1041. """Run the Tornado web application."""
  1042. # command line arguments; can also be written in a configuration file,
  1043. # specified with the --config argument.
  1044. define("port", default=5242, help="run on the given port", type=int)
  1045. define("address", default='', help="bind the server at the given address", type=str)
  1046. define("data_dir", default=os.path.join(os.path.dirname(__file__), "data"),
  1047. help="specify the directory used to store the data")
  1048. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_cert.pem'),
  1049. help="specify the SSL certificate to use for secure connections")
  1050. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_key.pem'),
  1051. help="specify the SSL private key to use for secure connections")
  1052. define("mongo_url", default=None,
  1053. help="URL to MongoDB server", type=str)
  1054. define("db_name", default='eventman',
  1055. help="Name of the MongoDB database to use", type=str)
  1056. define("authentication", default=False, help="if set to true, authentication is required")
  1057. define("debug", default=False, help="run in debug mode")
  1058. define("config", help="read configuration file",
  1059. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  1060. tornado.options.parse_command_line()
  1061. logger = logging.getLogger()
  1062. logger.setLevel(logging.INFO)
  1063. if options.debug:
  1064. logger.setLevel(logging.DEBUG)
  1065. ssl_options = {}
  1066. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  1067. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  1068. # database backend connector
  1069. db_connector = monco.Monco(url=options.mongo_url, dbName=options.db_name)
  1070. init_params = dict(db=db_connector, data_dir=options.data_dir, listen_port=options.port,
  1071. authentication=options.authentication, logger=logger, ssl_options=ssl_options)
  1072. # If not present, we store a user 'admin' with password 'eventman' into the database.
  1073. if not db_connector.query('users', {'username': 'admin'}):
  1074. db_connector.add('users',
  1075. {'username': 'admin', 'password': utils.hash_password('eventman'),
  1076. 'permissions': ['admin|all']})
  1077. # If present, use the cookie_secret stored into the database.
  1078. cookie_secret = db_connector.query('settings', {'setting': 'server_cookie_secret'})
  1079. if cookie_secret:
  1080. cookie_secret = cookie_secret[0]['cookie_secret']
  1081. else:
  1082. # the salt guarantees its uniqueness
  1083. cookie_secret = utils.hash_password('__COOKIE_SECRET__')
  1084. db_connector.add('settings',
  1085. {'setting': 'server_cookie_secret', 'cookie_secret': cookie_secret})
  1086. _ws_handler = (r"/ws/+event/+(?P<event_id>[\w\d_-]+)/+tickets/+updates/?", WebSocketEventUpdatesHandler)
  1087. _events_path = r"/events/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  1088. _users_path = r"/users/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  1089. application = tornado.web.Application([
  1090. (_events_path, EventsHandler, init_params),
  1091. (r'/v%s%s' % (API_VERSION, _events_path), EventsHandler, init_params),
  1092. (_users_path, UsersHandler, init_params),
  1093. (r'/v%s%s' % (API_VERSION, _users_path), UsersHandler, init_params),
  1094. (r"/(?:index.html)?", RootHandler, init_params),
  1095. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  1096. (r"/settings", SettingsHandler, init_params),
  1097. (r"/info", InfoHandler, init_params),
  1098. _ws_handler,
  1099. (r'/login', LoginHandler, init_params),
  1100. (r'/v%s/login' % API_VERSION, LoginHandler, init_params),
  1101. (r'/logout', LogoutHandler),
  1102. (r'/v%s/logout' % API_VERSION, LogoutHandler),
  1103. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  1104. ],
  1105. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  1106. static_path=os.path.join(os.path.dirname(__file__), "static"),
  1107. cookie_secret=cookie_secret,
  1108. login_url='/login',
  1109. debug=options.debug)
  1110. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  1111. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  1112. options.address if options.address else '127.0.0.1',
  1113. options.port)
  1114. http_server.listen(options.port, options.address)
  1115. # Also listen on options.port+1 for our local ws connection.
  1116. ws_application = tornado.web.Application([_ws_handler], debug=options.debug)
  1117. ws_http_server = tornado.httpserver.HTTPServer(ws_application)
  1118. ws_http_server.listen(options.port+1, address='127.0.0.1')
  1119. logger.debug('Starting WebSocket on ws://127.0.0.1:%d', options.port+1)
  1120. tornado.ioloop.IOLoop.instance().start()
  1121. if __name__ == '__main__':
  1122. try:
  1123. run()
  1124. except KeyboardInterrupt:
  1125. print('Stop server')