eventman_server.py 42 KB

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