eventman_server.py 41 KB

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