eventman_server.py 52 KB

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