eventman_server.py 51 KB

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