ibt2.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. #!/usr/bin/env python
  2. """I'll Be There, 2 (ibt2) - an oversimplified attendees registration system.
  3. Copyright 2016-2017 Davide Alberani <da@erlug.linux.it>
  4. RaspiBO <info@raspibo.org>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. """
  14. import os
  15. import re
  16. import logging
  17. import datetime
  18. from operator import itemgetter
  19. import itertools
  20. import tornado.httpserver
  21. import tornado.ioloop
  22. import tornado.options
  23. from tornado.options import define, options
  24. import tornado.web
  25. from tornado import gen, escape
  26. import utils
  27. import monco
  28. API_VERSION = '1.0'
  29. class BaseException(Exception):
  30. """Base class for ibt2 custom exceptions.
  31. :param message: text message
  32. :type message: str
  33. :param status: numeric http status code
  34. :type status: int"""
  35. def __init__(self, message, status=400):
  36. super(BaseException, self).__init__(message)
  37. self.message = message
  38. self.status = status
  39. class InputException(BaseException):
  40. """Exception raised by errors in input handling."""
  41. pass
  42. class BaseHandler(tornado.web.RequestHandler):
  43. """Base class for request handlers."""
  44. # Cache currently connected users.
  45. _users_cache = {}
  46. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  47. document = None
  48. collection = None
  49. # A property to access the first value of each argument.
  50. arguments = property(lambda self: dict([(k, v[0])
  51. for k, v in self.request.arguments.iteritems()]))
  52. _re_split_salt = re.compile(r'\$(?P<salt>.+)\$(?P<hash>.+)')
  53. @property
  54. def clean_body(self):
  55. """Return a clean dictionary from a JSON body, suitable for a query on MongoDB.
  56. :returns: a clean copy of the body arguments
  57. :rtype: dict"""
  58. data = escape.json_decode(self.request.body or '{}')
  59. return self._clean_dict(data)
  60. def _clean_dict(self, data):
  61. """Filter a dictionary (in place) to remove unwanted keywords in db queries.
  62. :param data: dictionary to clean
  63. :type data: dict"""
  64. if isinstance(data, dict):
  65. for key in data.keys():
  66. if isinstance(key, (str, unicode)) and key.startswith('$'):
  67. del data[key]
  68. return data
  69. def write_error(self, status_code, **kwargs):
  70. """Default error handler."""
  71. if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
  72. exc = kwargs['exc_info'][1]
  73. status_code = exc.status
  74. message = exc.message
  75. else:
  76. message = 'internal error'
  77. self.build_error(message, status=status_code)
  78. def is_api(self):
  79. """Return True if the path is from an API call."""
  80. return self.request.path.startswith('/v%s' % API_VERSION)
  81. def initialize(self, **kwargs):
  82. """Add every passed (key, value) as attributes of the instance."""
  83. for key, value in kwargs.iteritems():
  84. setattr(self, key, value)
  85. @property
  86. def current_user(self):
  87. """Retrieve current user ID from the secure cookie."""
  88. return self.get_secure_cookie("user")
  89. @property
  90. def current_user_info(self):
  91. """Information about the current user.
  92. :returns: full information about the current user
  93. :rtype: dict"""
  94. current_user = self.current_user
  95. if current_user in self._users_cache:
  96. return self._users_cache[current_user]
  97. user_info = {}
  98. if current_user:
  99. user_info['_id'] = current_user
  100. user = self.db.getOne('users', {'_id': user_info['_id']})
  101. if user:
  102. user_info = user
  103. self._users_cache[current_user] = user_info
  104. return user_info
  105. def user_authorized(self, username, password):
  106. """Check if a combination of username/password is valid.
  107. :param username: username or email
  108. :type username: str
  109. :param password: password
  110. :type password: str
  111. :returns: tuple like (bool_user_is_authorized, dict_user_info)
  112. :rtype: dict"""
  113. query = [{'username': username}, {'email': username}]
  114. res = self.db.query('users', query)
  115. if not res:
  116. return (False, {})
  117. user = res[0]
  118. db_password = user.get('password') or ''
  119. if not db_password:
  120. return (False, {})
  121. match = self._re_split_salt.match(db_password)
  122. if not match:
  123. return (False, {})
  124. salt = match.group('salt')
  125. if utils.hash_password(password, salt=salt) == db_password:
  126. return (True, user)
  127. return (False, {})
  128. def build_error(self, message='', status=400):
  129. """Build and write an error message.
  130. :param message: textual message
  131. :type message: str
  132. :param status: HTTP status code
  133. :type status: int
  134. """
  135. self.set_status(status)
  136. self.write({'error': True, 'message': message})
  137. def has_permission(self, owner_id):
  138. if (owner_id and str(self.current_user_info.get('_id')) != str(owner_id) and not
  139. self.current_user_info.get('isAdmin')):
  140. self.build_error(status=401, message='insufficient permissions: must be the owner or admin')
  141. return False
  142. return True
  143. def logout(self):
  144. """Remove the secure cookie used fro authentication."""
  145. if self.current_user in self._users_cache:
  146. del self._users_cache[self.current_user]
  147. self.clear_cookie("user")
  148. class RootHandler(BaseHandler):
  149. """Handler for the / path."""
  150. app_path = os.path.join(os.path.dirname(__file__), "dist")
  151. @gen.coroutine
  152. def get(self, *args, **kwargs):
  153. # serve the ./app/index.html file
  154. with open(self.app_path + "/index.html", 'r') as fd:
  155. self.write(fd.read())
  156. class AttendeesHandler(BaseHandler):
  157. document = 'attendee'
  158. collection = 'attendees'
  159. @gen.coroutine
  160. def get(self, id_=None, **kwargs):
  161. if id_:
  162. output = self.db.getOne(self.collection, {'_id': id_})
  163. else:
  164. output = {self.collection: self.db.query(self.collection, self.arguments)}
  165. self.write(output)
  166. @gen.coroutine
  167. def post(self, **kwargs):
  168. data = self.clean_body
  169. user_id = self.current_user_info.get('_id')
  170. now = datetime.datetime.now()
  171. data['created_by'] = user_id
  172. data['created_at'] = now
  173. data['updated_by'] = user_id
  174. data['updated_at'] = now
  175. doc = self.db.add(self.collection, data)
  176. self.write(doc)
  177. @gen.coroutine
  178. def put(self, id_, **kwargs):
  179. data = self.clean_body
  180. if '_id' in data:
  181. del data['_id']
  182. doc = self.db.getOne(self.collection, {'_id': id_}) or {}
  183. if not doc:
  184. return self.build_error(status=404, message='unable to access the resource')
  185. owner_id = doc.get('created_by')
  186. if not self.has_permission(owner_id):
  187. return
  188. user_id = self.current_user_info.get('_id')
  189. now = datetime.datetime.now()
  190. data['updated_by'] = user_id
  191. data['updated_at'] = now
  192. merged, doc = self.db.update(self.collection, {'_id': id_}, data)
  193. self.write(doc)
  194. @gen.coroutine
  195. def delete(self, id_=None, **kwargs):
  196. if id_ is None:
  197. self.write({'success': False})
  198. return
  199. doc = self.db.getOne(self.collection, {'_id': id_}) or {}
  200. if not doc:
  201. return self.build_error(status=404, message='unable to access the resource')
  202. owner_id = doc.get('created_by')
  203. if not self.has_permission(owner_id):
  204. return
  205. howMany = self.db.delete(self.collection, id_)
  206. self.write({'success': True, 'deleted entries': howMany.get('n')})
  207. class DaysHandler(BaseHandler):
  208. """Handle requests for Days."""
  209. def _summarize(self, days):
  210. res = []
  211. for day in days:
  212. res.append({'day': day['day'], 'groups_count': len(day.get('groups', []))})
  213. return res
  214. @gen.coroutine
  215. def get(self, day=None, **kwargs):
  216. params = self.arguments
  217. summary = params.get('summary', False)
  218. if summary:
  219. del params['summary']
  220. start = params.get('start')
  221. if start:
  222. del params['start']
  223. end = params.get('end')
  224. if end:
  225. del params['end']
  226. if day:
  227. params['day'] = day
  228. else:
  229. if start:
  230. params['day'] = {'$gte': start}
  231. if end:
  232. if 'day' not in params:
  233. params['day'] = {}
  234. if end.count('-') == 0:
  235. end += '-13'
  236. elif end.count('-') == 1:
  237. end += '-31'
  238. params['day'].update({'$lte': end})
  239. results = self.db.query('attendees', params)
  240. days = []
  241. dayData = {}
  242. try:
  243. sortedDays = []
  244. for result in results:
  245. if not ('day' in result and 'group' in result and 'name' in result):
  246. self.logger.warn('unable to parse entry; dayData: %s', dayData)
  247. continue
  248. sortedDays.append(result)
  249. sortedDays = sorted(sortedDays, key=itemgetter('day'))
  250. for d, dayItems in itertools.groupby(sortedDays, key=itemgetter('day')):
  251. dayData = {'day': d, 'groups': []}
  252. for group, attendees in itertools.groupby(sorted(dayItems, key=itemgetter('group')),
  253. key=itemgetter('group')):
  254. attendees = sorted(attendees, key=itemgetter('_id'))
  255. dayData['groups'].append({'group': group, 'attendees': attendees})
  256. days.append(dayData)
  257. except Exception as e:
  258. self.logger.warn('unable to parse entry; dayData: %s', dayData)
  259. if summary:
  260. days = self._summarize(days)
  261. if not day:
  262. self.write({'days': days})
  263. elif days:
  264. self.write(days[0])
  265. else:
  266. self.write({})
  267. class UsersHandler(BaseHandler):
  268. """Handle requests for Users."""
  269. document = 'user'
  270. collection = 'users'
  271. @gen.coroutine
  272. def get(self, id_=None, **kwargs):
  273. if id_:
  274. if not self.has_permission(id_):
  275. return
  276. output = self.db.getOne(self.collection, {'_id': id_})
  277. if 'password' in output:
  278. del output['password']
  279. else:
  280. if not self.current_user_info.get('isAdmin'):
  281. return self.build_error(status=401, message='insufficient permissions: must be an admin')
  282. output = {self.collection: self.db.query(self.collection, self.arguments)}
  283. for user in output['users']:
  284. if 'password' in user:
  285. del user['password']
  286. self.write(output)
  287. @gen.coroutine
  288. def post(self, **kwargs):
  289. data = self.clean_body
  290. if '_id' in data:
  291. del data['_id']
  292. username = (data.get('username') or '').strip()
  293. password = (data.get('password') or '').strip()
  294. email = (data.get('email') or '').strip()
  295. if not (username and password):
  296. raise InputException('missing username or password')
  297. res = self.db.query('users', {'username': username})
  298. if res:
  299. raise InputException('username already exists')
  300. data['username'] = username
  301. data['email'] = email
  302. data['password'] = utils.hash_password(password)
  303. if 'isAdmin' in data and not self.current_user_info.get('isAdmin'):
  304. del data['isAdmin']
  305. doc = self.db.add(self.collection, data)
  306. if 'password' in doc:
  307. del doc['password']
  308. self.write(doc)
  309. @gen.coroutine
  310. def put(self, id_=None, **kwargs):
  311. data = self.clean_body
  312. if id_ is None:
  313. return self.build_error(status=404, message='unable to access the resource')
  314. if not self.has_permission(id_):
  315. return
  316. if '_id' in data:
  317. del data['_id']
  318. if 'username' in data:
  319. del data['username']
  320. if 'isAdmin' in data and (str(self.current_user) == id_ or not self.current_user_info.get('isAdmin')):
  321. del data['isAdmin']
  322. if 'password' in data:
  323. password = (data['password'] or '').strip()
  324. if password:
  325. data['password'] = utils.hash_password(password)
  326. else:
  327. del data['password']
  328. merged, doc = self.db.update(self.collection, {'_id': id_}, data)
  329. if 'password' in doc:
  330. del doc['password']
  331. self.write(doc)
  332. @gen.coroutine
  333. def delete(self, id_=None, **kwargs):
  334. if id_ is None:
  335. return self.build_error(status=404, message='unable to access the resource')
  336. if not self.has_permission(id_):
  337. return
  338. howMany = self.db.delete(self.collection, id_)
  339. if id_ in self._users_cache:
  340. del self._users_cache[id_]
  341. self.write({'success': True, 'deleted entries': howMany.get('n')})
  342. class CurrentUserHandler(BaseHandler):
  343. """Handle requests for information about the logged in user."""
  344. @gen.coroutine
  345. def get(self, **kwargs):
  346. user_info = self.current_user_info or {}
  347. if 'password' in user_info:
  348. del user_info['password']
  349. self.write(user_info)
  350. class LoginHandler(RootHandler):
  351. """Handle user authentication requests."""
  352. @gen.coroutine
  353. def get(self, **kwargs):
  354. # show the login page
  355. if self.is_api():
  356. self.set_status(401)
  357. self.write({'error': True,
  358. 'message': 'authentication required'})
  359. @gen.coroutine
  360. def post(self, *args, **kwargs):
  361. # authenticate a user
  362. try:
  363. password = self.get_body_argument('password')
  364. username = self.get_body_argument('username')
  365. except tornado.web.MissingArgumentError:
  366. data = self.clean_body
  367. username = data.get('username')
  368. password = data.get('password')
  369. if not (username and password):
  370. self.set_status(401)
  371. self.write({'error': True, 'message': 'missing username or password'})
  372. return
  373. authorized, user = self.user_authorized(username, password)
  374. if authorized and 'username' in user and '_id' in user:
  375. id_ = str(user['_id'])
  376. username = user['username']
  377. logging.info('successful login for user %s (id: %s)' % (username, id_))
  378. self.set_secure_cookie("user", id_)
  379. user_info = self.current_user_info
  380. if 'password' in user_info:
  381. del user_info['password']
  382. self.write(user_info)
  383. return
  384. logging.info('login failed for user %s' % username)
  385. self.set_status(401)
  386. self.write({'error': True, 'message': 'wrong username and password'})
  387. class LogoutHandler(BaseHandler):
  388. """Handle user logout requests."""
  389. @gen.coroutine
  390. def get(self, **kwargs):
  391. # log the user out
  392. logging.info('logout')
  393. self.logout()
  394. self.write({'error': False, 'message': 'logged out'})
  395. def run():
  396. """Run the Tornado web application."""
  397. # command line arguments; can also be written in a configuration file,
  398. # specified with the --config argument.
  399. define("port", default=3000, help="run on the given port", type=int)
  400. define("address", default='', help="bind the server at the given address", type=str)
  401. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'ibt2_cert.pem'),
  402. help="specify the SSL certificate to use for secure connections")
  403. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'ibt2_key.pem'),
  404. help="specify the SSL private key to use for secure connections")
  405. define("mongo_url", default=None,
  406. help="URL to MongoDB server", type=str)
  407. define("db_name", default='ibt2',
  408. help="Name of the MongoDB database to use", type=str)
  409. define("debug", default=False, help="run in debug mode")
  410. define("config", help="read configuration file",
  411. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  412. tornado.options.parse_command_line()
  413. logger = logging.getLogger()
  414. logger.setLevel(logging.INFO)
  415. if options.debug:
  416. logger.setLevel(logging.DEBUG)
  417. ssl_options = {}
  418. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  419. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  420. # database backend connector
  421. db_connector = monco.Monco(url=options.mongo_url, dbName=options.db_name)
  422. init_params = dict(db=db_connector, listen_port=options.port, logger=logger, ssl_options=ssl_options)
  423. # If not present, we store a user 'admin' with password 'ibt2' into the database.
  424. if not db_connector.query('users', {'username': 'admin'}):
  425. db_connector.add('users',
  426. {'username': 'admin', 'password': utils.hash_password('ibt2'),
  427. 'isAdmin': True})
  428. # If present, use the cookie_secret stored into the database.
  429. cookie_secret = db_connector.query('settings', {'setting': 'server_cookie_secret'})
  430. if cookie_secret:
  431. cookie_secret = cookie_secret[0]['cookie_secret']
  432. else:
  433. # the salt guarantees its uniqueness
  434. cookie_secret = utils.hash_password('__COOKIE_SECRET__')
  435. db_connector.add('settings',
  436. {'setting': 'server_cookie_secret', 'cookie_secret': cookie_secret})
  437. _days_path = r"/days/?(?P<day>[\d_-]+)?"
  438. _attendees_path = r"/attendees/?(?P<id_>[\w\d_-]+)?"
  439. _current_user_path = r"/users/current/?"
  440. _users_path = r"/users/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  441. application = tornado.web.Application([
  442. (_attendees_path, AttendeesHandler, init_params),
  443. (r'/v%s%s' % (API_VERSION, _attendees_path), AttendeesHandler, init_params),
  444. (_days_path, DaysHandler, init_params),
  445. (r'/v%s%s' % (API_VERSION, _days_path), DaysHandler, init_params),
  446. (_current_user_path, CurrentUserHandler, init_params),
  447. (r'/v%s%s' % (API_VERSION, _current_user_path), CurrentUserHandler, init_params),
  448. (_users_path, UsersHandler, init_params),
  449. (r'/v%s%s' % (API_VERSION, _users_path), UsersHandler, init_params),
  450. (r"/(?:index.html)?", RootHandler, init_params),
  451. (r'/login', LoginHandler, init_params),
  452. (r'/v%s/login' % API_VERSION, LoginHandler, init_params),
  453. (r'/logout', LogoutHandler),
  454. (r'/v%s/logout' % API_VERSION, LogoutHandler),
  455. (r'/?(.*)', tornado.web.StaticFileHandler, {"path": "dist"})
  456. ],
  457. static_path=os.path.join(os.path.dirname(__file__), "dist/static"),
  458. cookie_secret='__COOKIE_SECRET__',
  459. login_url='/login',
  460. debug=options.debug)
  461. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  462. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  463. options.address if options.address else '127.0.0.1',
  464. options.port)
  465. http_server.listen(options.port, options.address)
  466. tornado.ioloop.IOLoop.instance().start()
  467. if __name__ == '__main__':
  468. try:
  469. run()
  470. except KeyboardInterrupt:
  471. print('Stop server')