eventman_server.py 55 KB

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