eventman_server.py 43 KB

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