eventman_server.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  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, _rawData=None, **kwargs):
  371. if _rawData:
  372. data = _rawData
  373. else:
  374. data = escape.json_decode(self.request.body or '{}')
  375. self._clean_dict(data)
  376. method = self.request.method.lower()
  377. crud_method = 'create' if method == 'post' else 'update'
  378. env = {}
  379. if id_ is not None:
  380. env['%s_ID' % self.document.upper()] = id_
  381. self.add_access_info(data)
  382. if resource:
  383. permission = '%s:%s%s|%s' % (self.document, resource, '-all' if resource_id is None else '', crud_method)
  384. if not self.has_permission(permission):
  385. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  386. # Handle access to sub-resources.
  387. handler = getattr(self, 'handle_%s_%s' % (method, resource), None)
  388. if handler and isinstance(handler, collections.Callable):
  389. data = self.apply_filter(data, 'input_%s_%s' % (method, resource))
  390. output = handler(id_, resource_id, data, **kwargs)
  391. output = self.apply_filter(output, 'get_%s' % resource)
  392. env['RESOURCE'] = resource
  393. if resource_id:
  394. env['%s_ID' % resource] = resource_id
  395. self.run_triggers('%s_%s_%s' % ('create' if resource_id is None else 'update', self.document, resource),
  396. stdin_data=output, env=env)
  397. self.write(output)
  398. return
  399. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  400. if id_ is not None:
  401. permission = '%s|%s' % (self.document, crud_method)
  402. if not self.has_permission(permission):
  403. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  404. data = self.apply_filter(data, 'input_%s' % method)
  405. merged, newData = self.db.update(self.collection, id_, data)
  406. newData = self.apply_filter(newData, method)
  407. self.run_triggers('update_%s' % self.document, stdin_data=newData, env=env)
  408. else:
  409. permission = '%s|%s' % (self.collection, crud_method)
  410. if not self.has_permission(permission):
  411. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  412. data = self.apply_filter(data, 'input_%s_all' % method)
  413. newData = self.db.add(self.collection, data, _id=self.gen_id())
  414. newData = self.apply_filter(newData, '%s_all' % method)
  415. self.run_triggers('create_%s' % self.document, stdin_data=newData, env=env)
  416. self.write(newData)
  417. # PUT (update an existing document) is handled by the POST (create a new document) method;
  418. # in subclasses you can always separate sub-resources handlers like handle_post_tickets and handle_put_tickets
  419. put = post
  420. @gen.coroutine
  421. @authenticated
  422. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  423. env = {}
  424. if id_ is not None:
  425. env['%s_ID' % self.document.upper()] = id_
  426. if resource:
  427. # Handle access to sub-resources.
  428. permission = '%s:%s%s|delete' % (self.document, resource, '-all' if resource_id is None else '')
  429. if not self.has_permission(permission):
  430. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  431. method = getattr(self, 'handle_delete_%s' % resource, None)
  432. if method and isinstance(method, collections.Callable):
  433. output = method(id_, resource_id, **kwargs)
  434. env['RESOURCE'] = resource
  435. if resource_id:
  436. env['%s_ID' % resource] = resource_id
  437. self.run_triggers('delete_%s_%s' % (self.document, resource), stdin_data=env, env=env)
  438. self.write(output)
  439. return
  440. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  441. if id_ is not None:
  442. permission = '%s|delete' % self.document
  443. if not self.has_permission(permission):
  444. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  445. howMany = self.db.delete(self.collection, id_)
  446. env['DELETED_ITEMS'] = howMany
  447. self.run_triggers('delete_%s' % self.document, stdin_data=env, env=env)
  448. else:
  449. self.write({'success': False})
  450. self.write({'success': True})
  451. def on_timeout(self, cmd, pipe):
  452. """Kill a process that is taking too long to complete."""
  453. logging.debug('the trigger %s is taking too long: killing it' % ' '.join(cmd))
  454. try:
  455. pipe.proc.kill()
  456. except:
  457. pass
  458. def on_exit(self, returncode, cmd, pipe):
  459. """Callback executed when a subprocess execution is over."""
  460. self.ioloop.remove_timeout(self.timeout)
  461. logging.debug('trigger: %s returncode: %d' % (' '.join(cmd), returncode))
  462. @gen.coroutine
  463. def run_subprocess(self, cmd, stdin_data=None, env=None):
  464. """Execute the given action.
  465. :param cmd: the command to be run with its command line arguments
  466. :type cmd: list
  467. :param stdin_data: data to be sent over stdin
  468. :type stdin_data: str
  469. :param env: environment of the process
  470. :type env: dict
  471. """
  472. self.ioloop = tornado.ioloop.IOLoop.instance()
  473. processed_env = self._dict2env(env)
  474. p = process.Subprocess(cmd, close_fds=True, stdin=process.Subprocess.STREAM,
  475. stdout=process.Subprocess.STREAM, stderr=process.Subprocess.STREAM, env=processed_env)
  476. p.set_exit_callback(lambda returncode: self.on_exit(returncode, cmd, p))
  477. self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
  478. lambda: self.on_timeout(cmd, p))
  479. yield gen.Task(p.stdin.write, stdin_data.encode(ENCODING) or b'')
  480. p.stdin.close()
  481. out, err = yield [gen.Task(p.stdout.read_until_close),
  482. gen.Task(p.stderr.read_until_close)]
  483. logging.debug('trigger: %s' % ' '.join(cmd))
  484. if out:
  485. logging.debug('trigger stdout: %s' % out.decode(ENCODING))
  486. if err:
  487. logging.debug('trigger strerr: %s' % err.decode(ENCODING))
  488. raise gen.Return((out, err))
  489. @gen.coroutine
  490. def run_triggers(self, action, stdin_data=None, env=None):
  491. """Asynchronously execute triggers for the given action.
  492. :param action: action name; scripts in directory ./data/triggers/{action}.d will be run
  493. :type action: str
  494. :param stdin_data: a python dictionary that will be serialized in JSON and sent to the process over stdin
  495. :type stdin_data: dict
  496. :param env: environment of the process
  497. :type stdin_data: dict
  498. """
  499. if not hasattr(self, 'data_dir'):
  500. return
  501. logging.debug('running triggers for action "%s"' % action)
  502. stdin_data = stdin_data or {}
  503. try:
  504. stdin_data = json.dumps(stdin_data)
  505. except:
  506. stdin_data = '{}'
  507. for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
  508. if not (os.path.isfile(script) and os.access(script, os.X_OK)):
  509. continue
  510. out, err = yield gen.Task(self.run_subprocess, [script], stdin_data, env)
  511. def build_ws_url(self, path, proto='ws', host=None):
  512. """Return a WebSocket url from a path."""
  513. try:
  514. args = '?uuid=%s' % self.get_argument('uuid')
  515. except:
  516. args = ''
  517. if not hasattr(self, 'listen_port'):
  518. return None
  519. return 'ws://127.0.0.1:%s/ws/%s%s' % (self.listen_port + 1, path, args)
  520. @gen.coroutine
  521. def send_ws_message(self, path, message):
  522. """Send a WebSocket message to all the connected clients.
  523. :param path: partial path used to build the WebSocket url
  524. :type path: str
  525. :param message: message to send
  526. :type message: str
  527. """
  528. try:
  529. url = self.build_ws_url(path)
  530. if not url:
  531. return
  532. ws = yield tornado.websocket.websocket_connect(url)
  533. ws.write_message(message)
  534. ws.close()
  535. except Exception as e:
  536. self.logger.error('Error yielding WebSocket message: %s', e)
  537. class EventsHandler(CollectionHandler):
  538. """Handle requests for Events."""
  539. document = 'event'
  540. collection = 'events'
  541. def _mangle_event(self, event):
  542. # Some in-place changes to an event
  543. if 'tickets' in event:
  544. event['tickets_sold'] = len([t for t in event['tickets'] if not t.get('cancelled')])
  545. event['no_tickets_for_sale'] = False
  546. try:
  547. self._check_sales_datetime(event)
  548. self._check_number_of_tickets(event)
  549. except InputException:
  550. event['no_tickets_for_sale'] = True
  551. if not self.has_permission('tickets-all|read'):
  552. event['tickets'] = []
  553. return event
  554. def filter_get(self, output):
  555. return self._mangle_event(output)
  556. def filter_get_all(self, output):
  557. for event in output.get('events') or []:
  558. self._mangle_event(event)
  559. return output
  560. def filter_input_post(self, data):
  561. # Auto-generate the group_id, if missing.
  562. if 'group_id' not in data:
  563. data['group_id'] = self.gen_id()
  564. return data
  565. filter_input_post_all = filter_input_post
  566. filter_input_put = filter_input_post
  567. def filter_input_post_tickets(self, data):
  568. # Avoid users to be able to auto-update their 'attendee' status.
  569. if not self.has_permission('event|update'):
  570. if 'attended' in data:
  571. del data['attended']
  572. self.add_access_info(data)
  573. return data
  574. filter_input_put_tickets = filter_input_post_tickets
  575. def handle_get_group_persons(self, id_, resource_id=None):
  576. persons = []
  577. this_query = {'_id': id_}
  578. this_event = self.db.query('events', this_query)[0]
  579. group_id = this_event.get('group_id')
  580. if group_id is None:
  581. return {'persons': persons}
  582. this_persons = [p for p in (this_event.get('tickets') or []) if not p.get('cancelled')]
  583. this_emails = [_f for _f in [p.get('email') for p in this_persons] if _f]
  584. all_query = {'group_id': group_id}
  585. events = self.db.query('events', all_query)
  586. for event in events:
  587. if id_ is not None and str(event.get('_id')) == id_:
  588. continue
  589. persons += [p for p in (event.get('tickets') or []) if p.get('email') and p.get('email') not in this_emails]
  590. return {'persons': persons}
  591. def _get_ticket_data(self, ticket_id_or_query, tickets, only_one=True):
  592. """Filter a list of tickets returning the first item with a given _id
  593. or which set of keys specified in a dictionary match their respective values."""
  594. matches = []
  595. for ticket in tickets:
  596. if isinstance(ticket_id_or_query, dict):
  597. if all(ticket.get(k) == v for k, v in ticket_id_or_query.items()):
  598. matches.append(ticket)
  599. if only_one:
  600. break
  601. else:
  602. if str(ticket.get('_id')) == ticket_id_or_query:
  603. matches.append(ticket)
  604. if only_one:
  605. break
  606. if only_one:
  607. if matches:
  608. return matches[0]
  609. return {}
  610. return matches
  611. def handle_get_tickets(self, id_, resource_id=None):
  612. # Return every ticket registered at this event, or the information
  613. # about a specific ticket.
  614. query = {'_id': id_}
  615. event = self.db.query('events', query)[0]
  616. if resource_id:
  617. return {'ticket': self._get_ticket_data(resource_id, event.get('tickets') or [])}
  618. tickets = self._filter_results(event.get('tickets') or [], self.arguments)
  619. return {'tickets': tickets}
  620. def _check_number_of_tickets(self, event):
  621. if self.has_permission('admin|all'):
  622. return
  623. number_of_tickets = event.get('number_of_tickets')
  624. if number_of_tickets is None:
  625. return
  626. try:
  627. number_of_tickets = int(number_of_tickets)
  628. except ValueError:
  629. return
  630. tickets = event.get('tickets') or []
  631. tickets = [t for t in tickets if not t.get('cancelled')]
  632. if len(tickets) >= event['number_of_tickets']:
  633. raise InputException('no more tickets available')
  634. def _check_sales_datetime(self, event):
  635. if self.has_permission('admin|all'):
  636. return
  637. begin_date = event.get('ticket_sales_begin_date')
  638. begin_time = event.get('ticket_sales_begin_time')
  639. end_date = event.get('ticket_sales_end_date')
  640. end_time = event.get('ticket_sales_end_time')
  641. utc = dateutil.tz.tzutc()
  642. is_dst = time.daylight and time.localtime().tm_isdst > 0
  643. utc_offset = - (time.altzone if is_dst else time.timezone)
  644. if begin_date is None:
  645. begin_date = datetime.datetime.now(tz=utc).replace(hour=0, minute=0, second=0, microsecond=0)
  646. else:
  647. begin_date = dateutil.parser.parse(begin_date)
  648. # Compensate UTC and DST offset, that otherwise would be added 2 times (one for date, one for time)
  649. begin_date = begin_date + datetime.timedelta(seconds=utc_offset)
  650. if begin_time is None:
  651. begin_time_h = 0
  652. begin_time_m = 0
  653. else:
  654. begin_time = dateutil.parser.parse(begin_time)
  655. begin_time_h = begin_time.hour
  656. begin_time_m = begin_time.minute
  657. now = datetime.datetime.now(tz=utc)
  658. begin_datetime = begin_date + datetime.timedelta(hours=begin_time_h, minutes=begin_time_m)
  659. if now < begin_datetime:
  660. raise InputException('ticket sales not yet started')
  661. if end_date is None:
  662. end_date = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=utc)
  663. else:
  664. end_date = dateutil.parser.parse(end_date)
  665. end_date = end_date + datetime.timedelta(seconds=utc_offset)
  666. if end_time is None:
  667. end_time = end_date
  668. end_time_h = 23
  669. end_time_m = 59
  670. else:
  671. end_time = dateutil.parser.parse(end_time, yearfirst=True)
  672. end_time_h = end_time.hour
  673. end_time_m = end_time.minute
  674. end_datetime = end_date + datetime.timedelta(hours=end_time_h, minutes=end_time_m+1)
  675. if now > end_datetime:
  676. raise InputException('ticket sales has ended')
  677. def handle_post_tickets(self, id_, resource_id, data, _skipTriggers=False):
  678. event = self.db.query('events', {'_id': id_})[0]
  679. self._check_sales_datetime(event)
  680. self._check_number_of_tickets(event)
  681. uuid, arguments = self.uuid_arguments
  682. self._clean_dict(data)
  683. data['seq'] = self.get_next_seq('event_%s_tickets' % id_)
  684. data['seq_hex'] = '%06X' % data['seq']
  685. data['_id'] = ticket_id = self.gen_id()
  686. self.add_access_info(data)
  687. ret = {'action': 'add', 'ticket': data, 'uuid': uuid}
  688. merged, doc = self.db.update('events',
  689. {'_id': id_},
  690. {'tickets': data},
  691. operation='appendUnique',
  692. create=False)
  693. if doc and not _skipTriggers:
  694. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  695. ticket = self._get_ticket_data(ticket_id, doc.get('tickets') or [])
  696. env = dict(ticket)
  697. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  698. 'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
  699. 'WEB_REMOTE_IP': self.request.remote_ip})
  700. stdin_data = {'new': ticket,
  701. 'event': doc,
  702. 'merged': merged
  703. }
  704. self.run_triggers('create_ticket_in_event', stdin_data=stdin_data, env=env)
  705. return ret
  706. def handle_put_tickets(self, id_, ticket_id, data):
  707. # Update an existing entry for a ticket registered at this event.
  708. self._clean_dict(data)
  709. uuid, arguments = self.uuid_arguments
  710. _errorMessage = ''
  711. if '_errorMessage' in arguments:
  712. _errorMessage = arguments['_errorMessage']
  713. del arguments['_errorMessage']
  714. _searchFor = False
  715. if '_searchFor' in arguments:
  716. _searchFor = arguments['_searchFor']
  717. del arguments['_searchFor']
  718. query = dict([('tickets.%s' % k, v) for k, v in arguments.items()])
  719. query['_id'] = id_
  720. if ticket_id is not None:
  721. query['tickets._id'] = ticket_id
  722. ticket_query = {'_id': ticket_id}
  723. else:
  724. ticket_query = arguments
  725. old_ticket_data = {}
  726. current_event = self.db.query(self.collection, query)
  727. if current_event:
  728. current_event = current_event[0]
  729. else:
  730. current_event = {}
  731. self._check_sales_datetime(current_event)
  732. tickets = current_event.get('tickets') or []
  733. matching_tickets = self._get_ticket_data(ticket_query, tickets, only_one=False)
  734. nr_matches = len(matching_tickets)
  735. if nr_matches > 1:
  736. ret = {'error': True, 'message': 'more than one ticket matched. %s' % _errorMessage, 'query': query,
  737. 'searchFor': _searchFor, 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
  738. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  739. self.set_status(400)
  740. return ret
  741. elif nr_matches == 0:
  742. ret = {'error': True, 'message': 'no ticket matched. %s' % _errorMessage, 'query': query,
  743. 'searchFor': _searchFor, 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
  744. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  745. self.set_status(400)
  746. return ret
  747. else:
  748. old_ticket_data = matching_tickets[0]
  749. # We have changed the "cancelled" status of a ticket to False; check if we still have a ticket available
  750. if 'number_of_tickets' in current_event and old_ticket_data.get('cancelled') and not data.get('cancelled'):
  751. self._check_number_of_tickets(current_event)
  752. self.add_access_info(data)
  753. merged, doc = self.db.update('events', query,
  754. data, updateList='tickets', create=False)
  755. new_ticket_data = self._get_ticket_data(ticket_query,
  756. doc.get('tickets') or [])
  757. env = dict(new_ticket_data)
  758. # always takes the ticket_id from the new ticket
  759. ticket_id = str(new_ticket_data.get('_id'))
  760. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  761. 'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
  762. 'WEB_REMOTE_IP': self.request.remote_ip})
  763. stdin_data = {'old': old_ticket_data,
  764. 'new': new_ticket_data,
  765. 'event': doc,
  766. 'merged': merged
  767. }
  768. self.run_triggers('update_ticket_in_event', stdin_data=stdin_data, env=env)
  769. if old_ticket_data and old_ticket_data.get('attended') != new_ticket_data.get('attended'):
  770. if new_ticket_data.get('attended'):
  771. self.run_triggers('attends', stdin_data=stdin_data, env=env)
  772. ret = {'action': 'update', '_id': ticket_id, 'ticket': new_ticket_data,
  773. 'uuid': uuid, 'username': self.current_user_info.get('username', '')}
  774. if old_ticket_data != new_ticket_data:
  775. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  776. return ret
  777. def handle_delete_tickets(self, id_, ticket_id):
  778. # Remove a ticket (or all tickets) from the list of tickets registered at this event.
  779. uuid, arguments = self.uuid_arguments
  780. doc = self.db.query('events', {'_id': id_})
  781. ret = {'action': 'delete', '_id': ticket_id, 'uuid': uuid}
  782. if doc:
  783. ticket = self._get_ticket_data(ticket_id, doc[0].get('tickets') or [])
  784. ticket_query = {}
  785. if ticket:
  786. ticket_query['_id'] = ticket_id
  787. merged, rdoc = self.db.update('events',
  788. {'_id': id_},
  789. {'tickets': ticket_query},
  790. operation='delete',
  791. create=False)
  792. if ticket:
  793. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  794. env = dict(ticket)
  795. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  796. 'EVENT_TITLE': rdoc.get('title', ''), 'WEB_USER': self.current_user_info.get('username', ''),
  797. 'WEB_REMOTE_IP': self.request.remote_ip})
  798. stdin_data = {'old': ticket,
  799. 'event': rdoc,
  800. 'merged': merged
  801. }
  802. self.run_triggers('delete_ticket_in_event', stdin_data=stdin_data, env=env)
  803. return ret
  804. class UsersHandler(CollectionHandler):
  805. """Handle requests for Users."""
  806. document = 'user'
  807. collection = 'users'
  808. def filter_get(self, data):
  809. if 'password' in data:
  810. del data['password']
  811. if '_id' in data:
  812. # Also add a 'tickets' list with all the tickets created by this user
  813. tickets = []
  814. events = self.db.query('events', {'tickets.created_by': data['_id']})
  815. for event in events:
  816. event_title = event.get('title') or ''
  817. event_id = str(event.get('_id'))
  818. evt_tickets = self._filter_results(event.get('tickets') or [], {'created_by': data['_id']})
  819. for evt_ticket in evt_tickets:
  820. evt_ticket['event_title'] = event_title
  821. evt_ticket['event_id'] = event_id
  822. tickets.extend(evt_tickets)
  823. data['tickets'] = tickets
  824. return data
  825. def filter_get_all(self, data):
  826. if 'users' not in data:
  827. return data
  828. for user in data['users']:
  829. if 'password' in user:
  830. del user['password']
  831. return data
  832. @gen.coroutine
  833. @authenticated
  834. def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
  835. if id_ is not None:
  836. if (self.has_permission('user|read') or self.current_user == id_):
  837. acl = False
  838. super(UsersHandler, self).get(id_, resource, resource_id, acl=acl, **kwargs)
  839. def filter_input_post_all(self, data):
  840. username = (data.get('username') or '').strip()
  841. password = (data.get('password') or '').strip()
  842. email = (data.get('email') or '').strip()
  843. if not (username and password):
  844. raise InputException('missing username or password')
  845. res = self.db.query('users', {'username': username})
  846. if res:
  847. raise InputException('username already exists')
  848. return {'username': username, 'password': utils.hash_password(password),
  849. 'email': email, '_id': self.gen_id()}
  850. def filter_input_put(self, data):
  851. old_pwd = data.get('old_password')
  852. new_pwd = data.get('new_password')
  853. if old_pwd is not None:
  854. del data['old_password']
  855. if new_pwd is not None:
  856. del data['new_password']
  857. authorized, user = self.user_authorized(data['username'], old_pwd)
  858. if not (self.has_permission('user|update') or (authorized and
  859. self.current_user_info.get('username') == data['username'])):
  860. raise InputException('not authorized to change password')
  861. data['password'] = utils.hash_password(new_pwd)
  862. if '_id' in data:
  863. del data['_id']
  864. if 'username' in data:
  865. del data['username']
  866. if 'tickets' in data:
  867. del data['tickets']
  868. if not self.has_permission('admin|all'):
  869. if 'permissions' in data:
  870. del data['permissions']
  871. else:
  872. if 'isAdmin' in data:
  873. if not 'permissions' in data:
  874. data['permissions'] = []
  875. if 'admin|all' in data['permissions'] and not data['isAdmin']:
  876. data['permissions'].remove('admin|all')
  877. elif 'admin|all' not in data['permissions'] and data['isAdmin']:
  878. data['permissions'].append('admin|all')
  879. del data['isAdmin']
  880. return data
  881. @gen.coroutine
  882. @authenticated
  883. def put(self, id_=None, resource=None, resource_id=None, **kwargs):
  884. if id_ is None:
  885. return self.build_error(status=404, message='unable to access the resource')
  886. if not (self.has_permission('user|update') or self.current_user == id_):
  887. return self.build_error(status=401, message='insufficient permissions: user|update or current user')
  888. super(UsersHandler, self).put(id_, resource, resource_id, **kwargs)
  889. class EbAPIImportHandler(BaseHandler):
  890. """Import events and attendees using Eventbrite API."""
  891. @gen.coroutine
  892. @authenticated
  893. def post(self, *args, **kwargs):
  894. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  895. data = escape.json_decode(self.request.body or '{}')
  896. oauthToken = data.get('oauthToken')
  897. eventID = data.get('eventID')
  898. targetEventID = data.get('targetEvent')
  899. create = True
  900. try:
  901. create = self.tobool(data.get('create'))
  902. except:
  903. pass
  904. try:
  905. eb_info = utils.ebAPIFetch(oauthToken=oauthToken, eventID=eventID)
  906. except Exception as e:
  907. return self.build_error('Error using Eventbrite API: %s' % e)
  908. if 'event' not in eb_info or 'attendees' not in eb_info:
  909. return self.build_error('Missing information from Eventbrite API')
  910. event_handler = EventsHandler(self.application, self.request)
  911. event_handler.db = self.db
  912. event_handler.logger = self.logger
  913. event_handler.authentication = self.authentication
  914. if create:
  915. event_handler.post(_rawData=eb_info['event'])
  916. event_in_db = self.db.query('events', {'eb_event_id': eb_info['event']['eb_event_id']})
  917. if not event_in_db:
  918. return self.build_error('Unable to create a new event')
  919. targetEventID = event_in_db[0]['_id']
  920. for ticket in eb_info.get('attendees') or []:
  921. reply['total'] += 1
  922. ticket['event_id'] = targetEventID
  923. try:
  924. event_handler.handle_post_tickets(targetEventID, None, ticket, _skipTriggers=True)
  925. except Exception as e:
  926. self.logger.warn('failed to add a ticket: ' % e)
  927. reply['new_in_event'] += 1
  928. reply['valid'] += 1
  929. self.write(reply)
  930. class EbCSVImportPersonsHandler(BaseHandler):
  931. """Importer for CSV files exported from Eventbrite."""
  932. csvRemap = {
  933. 'Nome evento': 'event_title',
  934. 'ID evento': 'event_id',
  935. 'N. codice a barre': 'ebqrcode',
  936. 'Cognome acquirente': 'surname',
  937. 'Nome acquirente': 'name',
  938. 'E-mail acquirente': 'email',
  939. 'Cognome': 'surname',
  940. 'Nome': 'name',
  941. 'E-mail': 'email',
  942. 'Indirizzo e-mail': 'email',
  943. 'Tipologia biglietto': 'ticket_kind',
  944. 'Data partecipazione': 'attending_datetime',
  945. 'Data check-in': 'checkin_datetime',
  946. 'Ordine n.': 'order_nr',
  947. 'ID ordine': 'order_nr',
  948. 'Titolo professionale': 'job title',
  949. 'Azienda': 'company',
  950. 'Prefisso': 'name_title',
  951. 'Prefisso (Sig., Sig.ra, ecc.)': 'name title',
  952. 'Order #': 'order_nr',
  953. 'Prefix': 'name title',
  954. 'First Name': 'name',
  955. 'Last Name': 'surname',
  956. 'Suffix': 'name suffix',
  957. 'Email': 'email',
  958. 'Attendee #': 'attendee_nr',
  959. 'Barcode #': 'ebqrcode',
  960. 'Company': 'company'
  961. }
  962. @gen.coroutine
  963. @authenticated
  964. def post(self, **kwargs):
  965. # import a CSV list of persons
  966. event_handler = EventsHandler(self.application, self.request)
  967. event_handler.db = self.db
  968. event_handler.logger = self.logger
  969. event_id = None
  970. deduplicate = False
  971. try:
  972. event_id = self.get_body_argument('targetEvent')
  973. except:
  974. pass
  975. try:
  976. deduplicate = self.tobool(self.get_body_argument('deduplicate'))
  977. except:
  978. pass
  979. if event_id is None:
  980. return self.build_error('invalid event')
  981. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  982. event_details = event_handler.db.query('events', {'_id': event_id})
  983. if not event_details:
  984. return self.build_error('invalid event')
  985. all_persons = set()
  986. for ticket in (event_details[0].get('tickets') or []):
  987. all_persons.add('%s_%s_%s' % (ticket.get('name'), ticket.get('surname'), ticket.get('email')))
  988. for fieldname, contents in self.request.files.items():
  989. for content in contents:
  990. filename = content['filename']
  991. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  992. reply['total'] += parseStats['total']
  993. for person in persons:
  994. if not person:
  995. continue
  996. reply['valid'] += 1
  997. person['attended'] = False
  998. person['from_file'] = filename
  999. self.add_access_info(person)
  1000. if deduplicate:
  1001. duplicate_check = '%s_%s_%s_%s' % (person.get('name'), person.get('surname'),
  1002. person.get('email'), person.get('order_nr'))
  1003. if duplicate_check in all_persons:
  1004. continue
  1005. all_persons.add(duplicate_check)
  1006. event_handler.handle_post_tickets(event_id, None, person, _skipTriggers=True)
  1007. reply['new_in_event'] += 1
  1008. self.write(reply)
  1009. class SettingsHandler(BaseHandler):
  1010. """Handle requests for Settings."""
  1011. @gen.coroutine
  1012. @authenticated
  1013. def get(self, **kwargs):
  1014. query = self.arguments_tobool()
  1015. settings = self.db.query('settings', query)
  1016. self.write({'settings': settings})
  1017. class InfoHandler(BaseHandler):
  1018. """Handle requests for information about the logged in user."""
  1019. @gen.coroutine
  1020. def get(self, **kwargs):
  1021. info = {}
  1022. user_info = self.current_user_info
  1023. if user_info:
  1024. info['user'] = user_info
  1025. info['authentication_required'] = self.authentication
  1026. self.write({'info': info})
  1027. class WebSocketEventUpdatesHandler(tornado.websocket.WebSocketHandler):
  1028. """Manage WebSockets."""
  1029. def _clean_url(self, url):
  1030. url = re_slashes.sub('/', url)
  1031. ridx = url.rfind('?')
  1032. if ridx != -1:
  1033. url = url[:ridx]
  1034. return url
  1035. def open(self, event_id, *args, **kwargs):
  1036. try:
  1037. self.uuid = self.get_argument('uuid')
  1038. except:
  1039. self.uuid = None
  1040. url = self._clean_url(self.request.uri)
  1041. logging.debug('WebSocketEventUpdatesHandler.on_open event_id:%s url:%s' % (event_id, url))
  1042. _ws_clients.setdefault(url, {})
  1043. if self.uuid and self.uuid not in _ws_clients[url]:
  1044. _ws_clients[url][self.uuid] = self
  1045. logging.debug('WebSocketEventUpdatesHandler.on_open %s clients connected' % len(_ws_clients[url]))
  1046. def on_message(self, message):
  1047. url = self._clean_url(self.request.uri)
  1048. logging.debug('WebSocketEventUpdatesHandler.on_message url:%s' % url)
  1049. count = 0
  1050. _to_delete = set()
  1051. current_uuid = None
  1052. try:
  1053. current_uuid = self.get_argument('uuid')
  1054. except:
  1055. pass
  1056. for uuid, client in _ws_clients.get(url, {}).items():
  1057. if uuid and uuid == current_uuid:
  1058. continue
  1059. try:
  1060. client.write_message(message)
  1061. except:
  1062. _to_delete.add(uuid)
  1063. continue
  1064. count += 1
  1065. for uuid in _to_delete:
  1066. try:
  1067. del _ws_clients[url][uuid]
  1068. except KeyError:
  1069. pass
  1070. logging.debug('WebSocketEventUpdatesHandler.on_message sent message to %d clients' % count)
  1071. class LoginHandler(RootHandler):
  1072. """Handle user authentication requests."""
  1073. @gen.coroutine
  1074. def get(self, **kwargs):
  1075. # show the login page
  1076. if self.is_api():
  1077. self.set_status(401)
  1078. self.write({'error': True,
  1079. 'message': 'authentication required'})
  1080. @gen.coroutine
  1081. def post(self, *args, **kwargs):
  1082. # authenticate a user
  1083. try:
  1084. password = self.get_body_argument('password')
  1085. username = self.get_body_argument('username')
  1086. except tornado.web.MissingArgumentError:
  1087. data = escape.json_decode(self.request.body or '{}')
  1088. username = data.get('username')
  1089. password = data.get('password')
  1090. if not (username and password):
  1091. self.set_status(401)
  1092. self.write({'error': True, 'message': 'missing username or password'})
  1093. return
  1094. authorized, user = self.user_authorized(username, password)
  1095. if authorized and 'username' in user and '_id' in user:
  1096. id_ = str(user['_id'])
  1097. username = user['username']
  1098. logging.info('successful login for user %s (id: %s)' % (username, id_))
  1099. self.set_secure_cookie("user", id_)
  1100. self.write({'error': False, 'message': 'successful login'})
  1101. return
  1102. logging.info('login failed for user %s' % username)
  1103. self.set_status(401)
  1104. self.write({'error': True, 'message': 'wrong username and password'})
  1105. class LogoutHandler(BaseHandler):
  1106. """Handle user logout requests."""
  1107. @gen.coroutine
  1108. def get(self, **kwargs):
  1109. # log the user out
  1110. logging.info('logout')
  1111. self.logout()
  1112. self.write({'error': False, 'message': 'logged out'})
  1113. def run():
  1114. """Run the Tornado web application."""
  1115. # command line arguments; can also be written in a configuration file,
  1116. # specified with the --config argument.
  1117. define("port", default=5242, help="run on the given port", type=int)
  1118. define("address", default='', help="bind the server at the given address", type=str)
  1119. define("data_dir", default=os.path.join(os.path.dirname(__file__), "data"),
  1120. help="specify the directory used to store the data")
  1121. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_cert.pem'),
  1122. help="specify the SSL certificate to use for secure connections")
  1123. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_key.pem'),
  1124. help="specify the SSL private key to use for secure connections")
  1125. define("mongo_url", default=None,
  1126. help="URL to MongoDB server", type=str)
  1127. define("db_name", default='eventman',
  1128. help="Name of the MongoDB database to use", type=str)
  1129. define("authentication", default=False, help="if set to true, authentication is required")
  1130. define("debug", default=False, help="run in debug mode")
  1131. define("config", help="read configuration file",
  1132. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  1133. tornado.options.parse_command_line()
  1134. logger = logging.getLogger()
  1135. logger.setLevel(logging.INFO)
  1136. if options.debug:
  1137. logger.setLevel(logging.DEBUG)
  1138. ssl_options = {}
  1139. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  1140. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  1141. # database backend connector
  1142. db_connector = monco.Monco(url=options.mongo_url, dbName=options.db_name)
  1143. init_params = dict(db=db_connector, data_dir=options.data_dir, listen_port=options.port,
  1144. authentication=options.authentication, logger=logger, ssl_options=ssl_options)
  1145. # If not present, we store a user 'admin' with password 'eventman' into the database.
  1146. if not db_connector.query('users', {'username': 'admin'}):
  1147. db_connector.add('users',
  1148. {'username': 'admin', 'password': utils.hash_password('eventman'),
  1149. 'permissions': ['admin|all']})
  1150. # If present, use the cookie_secret stored into the database.
  1151. cookie_secret = db_connector.query('settings', {'setting': 'server_cookie_secret'})
  1152. if cookie_secret:
  1153. cookie_secret = cookie_secret[0]['cookie_secret']
  1154. else:
  1155. # the salt guarantees its uniqueness
  1156. cookie_secret = utils.hash_password('__COOKIE_SECRET__')
  1157. db_connector.add('settings',
  1158. {'setting': 'server_cookie_secret', 'cookie_secret': cookie_secret})
  1159. _ws_handler = (r"/ws/+event/+(?P<event_id>[\w\d_-]+)/+tickets/+updates/?", WebSocketEventUpdatesHandler)
  1160. _events_path = r"/events/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  1161. _users_path = r"/users/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  1162. application = tornado.web.Application([
  1163. (_events_path, EventsHandler, init_params),
  1164. (r'/v%s%s' % (API_VERSION, _events_path), EventsHandler, init_params),
  1165. (_users_path, UsersHandler, init_params),
  1166. (r'/v%s%s' % (API_VERSION, _users_path), UsersHandler, init_params),
  1167. (r"/(?:index.html)?", RootHandler, init_params),
  1168. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  1169. (r"/v%s/ebcsvpersons" % API_VERSION, EbCSVImportPersonsHandler, init_params),
  1170. (r"/ebapi", EbAPIImportHandler, init_params),
  1171. (r"/v%s/ebapi" % API_VERSION, EbAPIImportHandler, init_params),
  1172. (r"/settings", SettingsHandler, init_params),
  1173. (r"/v%s/settings" % API_VERSION, SettingsHandler, init_params),
  1174. (r"/info", InfoHandler, init_params),
  1175. (r"/v%s/info" % API_VERSION, InfoHandler, init_params),
  1176. _ws_handler,
  1177. (r'/login', LoginHandler, init_params),
  1178. (r'/v%s/login' % API_VERSION, LoginHandler, init_params),
  1179. (r'/logout', LogoutHandler),
  1180. (r'/v%s/logout' % API_VERSION, LogoutHandler),
  1181. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  1182. ],
  1183. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  1184. static_path=os.path.join(os.path.dirname(__file__), "static"),
  1185. cookie_secret=cookie_secret,
  1186. login_url='/login',
  1187. debug=options.debug)
  1188. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  1189. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  1190. options.address if options.address else '127.0.0.1',
  1191. options.port)
  1192. http_server.listen(options.port, options.address)
  1193. # Also listen on options.port+1 for our local ws connection.
  1194. ws_application = tornado.web.Application([_ws_handler], debug=options.debug)
  1195. ws_http_server = tornado.httpserver.HTTPServer(ws_application)
  1196. ws_http_server.listen(options.port+1, address='127.0.0.1')
  1197. logger.debug('Starting WebSocket on ws://127.0.0.1:%d', options.port+1)
  1198. tornado.ioloop.IOLoop.instance().start()
  1199. if __name__ == '__main__':
  1200. try:
  1201. run()
  1202. except KeyboardInterrupt:
  1203. print('Stop server')