ibt2.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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('$')) or key in ('_id', 'created_by',
  67. 'created_at', 'updated_by',
  68. 'updated_at'):
  69. del data[key]
  70. return data
  71. def write_error(self, status_code, **kwargs):
  72. """Default error handler."""
  73. if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
  74. exc = kwargs['exc_info'][1]
  75. status_code = exc.status
  76. message = exc.message
  77. else:
  78. message = 'internal error'
  79. self.build_error(message, status=status_code)
  80. def is_api(self):
  81. """Return True if the path is from an API call."""
  82. return self.request.path.startswith('/v%s' % API_VERSION)
  83. def initialize(self, **kwargs):
  84. """Add every passed (key, value) as attributes of the instance."""
  85. for key, value in kwargs.iteritems():
  86. setattr(self, key, value)
  87. @property
  88. def current_user(self):
  89. """Retrieve current user ID from the secure cookie."""
  90. return self.get_secure_cookie("user")
  91. @property
  92. def current_user_info(self):
  93. """Information about the current user.
  94. :returns: full information about the current user
  95. :rtype: dict"""
  96. current_user = self.current_user
  97. if current_user in self._users_cache:
  98. return self._users_cache[current_user]
  99. user_info = {}
  100. if current_user:
  101. user_info['_id'] = current_user
  102. user = self.db.getOne('users', {'_id': user_info['_id']})
  103. if user:
  104. user_info = user
  105. self._users_cache[current_user] = user_info
  106. return user_info
  107. def user_authorized(self, username, password):
  108. """Check if a combination of username/password is valid.
  109. :param username: username or email
  110. :type username: str
  111. :param password: password
  112. :type password: str
  113. :returns: tuple like (bool_user_is_authorized, dict_user_info)
  114. :rtype: dict"""
  115. query = [{'username': username}, {'email': username}]
  116. res = self.db.query('users', query)
  117. if not res:
  118. return (False, {})
  119. user = res[0]
  120. db_password = user.get('password') or ''
  121. if not db_password:
  122. return (False, {})
  123. match = self._re_split_salt.match(db_password)
  124. if not match:
  125. return (False, {})
  126. salt = match.group('salt')
  127. if utils.hash_password(password, salt=salt) == db_password:
  128. return (True, user)
  129. return (False, {})
  130. def build_error(self, message='', status=400):
  131. """Build and write an error message.
  132. :param message: textual message
  133. :type message: str
  134. :param status: HTTP status code
  135. :type status: int
  136. """
  137. self.set_status(status)
  138. self.write({'error': True, 'message': message})
  139. def has_permission(self, owner_id):
  140. """Check if the given owner_id matches with the current user or the logged in user is an admin; if not,
  141. build an error reply.
  142. :param owner_id: owner ID to check against
  143. :type owner_id: str, ObjectId, None
  144. :returns: if the logged in user has the permission
  145. :rtype: bool"""
  146. if (owner_id and str(self.current_user) != str(owner_id) and not
  147. self.current_user_info.get('isAdmin')):
  148. self.build_error(status=401, message='insufficient permissions: must be the owner or admin')
  149. return False
  150. return True
  151. def logout(self):
  152. """Remove the secure cookie used fro authentication."""
  153. if self.current_user in self._users_cache:
  154. del self._users_cache[self.current_user]
  155. self.clear_cookie("user")
  156. def add_access_info(self, doc):
  157. """Add created/updated by/at to a document (modified in place and returned).
  158. :param doc: the doc to be updated
  159. :type doc: dict
  160. :returns: the updated document
  161. :rtype: dict"""
  162. user_id = self.current_user
  163. now = datetime.datetime.now()
  164. if 'created_by' not in doc:
  165. doc['created_by'] = user_id
  166. if 'created_at' not in doc:
  167. doc['created_at'] = now
  168. doc['updated_by'] = user_id
  169. doc['updated_at'] = now
  170. return doc
  171. class RootHandler(BaseHandler):
  172. """Handler for the / path."""
  173. app_path = os.path.join(os.path.dirname(__file__), "dist")
  174. @gen.coroutine
  175. def get(self, *args, **kwargs):
  176. # serve the ./app/index.html file
  177. with open(self.app_path + "/index.html", 'r') as fd:
  178. self.write(fd.read())
  179. class AttendeesHandler(BaseHandler):
  180. document = 'attendee'
  181. collection = 'attendees'
  182. @gen.coroutine
  183. def get(self, id_=None, **kwargs):
  184. if id_:
  185. output = self.db.getOne(self.collection, {'_id': id_})
  186. else:
  187. output = {self.collection: self.db.query(self.collection, self.arguments)}
  188. self.write(output)
  189. @gen.coroutine
  190. def post(self, **kwargs):
  191. data = self.clean_body
  192. for key in 'name', 'group', 'day':
  193. value = (data.get(key) or '').strip()
  194. if not value:
  195. return self.build_error(status=404, message="%s can't be empty" % key)
  196. data[key] = value
  197. self.add_access_info(data)
  198. doc = self.db.add(self.collection, data)
  199. self.write(doc)
  200. @gen.coroutine
  201. def put(self, id_, **kwargs):
  202. data = self.clean_body
  203. doc = self.db.getOne(self.collection, {'_id': id_}) or {}
  204. if not doc:
  205. return self.build_error(status=404, message='unable to access the resource')
  206. if not self.has_permission(doc.get('created_by')):
  207. return
  208. self.add_access_info(data)
  209. merged, doc = self.db.update(self.collection, {'_id': id_}, data)
  210. self.write(doc)
  211. @gen.coroutine
  212. def delete(self, id_=None, **kwargs):
  213. if id_ is None:
  214. self.write({'success': False})
  215. return
  216. doc = self.db.getOne(self.collection, {'_id': id_}) or {}
  217. if not doc:
  218. return self.build_error(status=404, message='unable to access the resource')
  219. if not self.has_permission(doc.get('created_by')):
  220. return
  221. howMany = self.db.delete(self.collection, id_)
  222. self.write({'success': True, 'deleted entries': howMany.get('n')})
  223. class DaysHandler(BaseHandler):
  224. """Handle requests for Days."""
  225. def _summarize(self, days):
  226. res = []
  227. for day in days:
  228. res.append({'day': day['day'], 'groups_count': len(day.get('groups', []))})
  229. return res
  230. @gen.coroutine
  231. def get(self, day=None, **kwargs):
  232. params = self.arguments
  233. summary = params.get('summary', False)
  234. if summary:
  235. del params['summary']
  236. start = params.get('start')
  237. if start:
  238. del params['start']
  239. end = params.get('end')
  240. if end:
  241. del params['end']
  242. base = {}
  243. groupsDetails = {}
  244. if day:
  245. params['day'] = day
  246. base = self.db.getOne('days', {'day': day})
  247. groupsDetails = dict([(x['group'], x) for x in self.db.query('groups', {'day': day})])
  248. else:
  249. if start:
  250. params['day'] = {'$gte': start}
  251. if end:
  252. if 'day' not in params:
  253. params['day'] = {}
  254. if end.count('-') == 0:
  255. end += '-13'
  256. elif end.count('-') == 1:
  257. end += '-31'
  258. params['day'].update({'$lte': end})
  259. results = self.db.query('attendees', params)
  260. days = []
  261. dayData = {}
  262. try:
  263. sortedDays = []
  264. for result in results:
  265. if not ('day' in result and 'group' in result and 'name' in result):
  266. self.logger.warn('unable to parse entry; dayData: %s', dayData)
  267. continue
  268. sortedDays.append(result)
  269. sortedDays = sorted(sortedDays, key=itemgetter('day'))
  270. for d, dayItems in itertools.groupby(sortedDays, key=itemgetter('day')):
  271. dayData = {'day': d, 'groups': []}
  272. for group, attendees in itertools.groupby(sorted(dayItems, key=itemgetter('group')),
  273. key=itemgetter('group')):
  274. attendees = sorted(attendees, key=itemgetter('_id'))
  275. groupData = groupsDetails.get(group) or {}
  276. groupData.update({'group': group, 'attendees': attendees})
  277. dayData['groups'].append(groupData)
  278. days.append(dayData)
  279. except Exception as e:
  280. self.logger.warn('unable to parse entry; dayData: %s error: %s', dayData, e)
  281. if summary:
  282. days = self._summarize(days)
  283. if not day:
  284. self.write({'days': days})
  285. elif days:
  286. base.update(days[0])
  287. self.write(base)
  288. else:
  289. self.write(base)
  290. @gen.coroutine
  291. def put(self, **kwargs):
  292. data = self.clean_body
  293. day = (data.get('day') or '').strip()
  294. if not day:
  295. return self.build_error(status=404, message='unable to access the resource')
  296. data['day'] = day
  297. self.add_access_info(data)
  298. merged, doc = self.db.update('days', {'day': day}, data)
  299. self.write(doc)
  300. class GroupsHandler(BaseHandler):
  301. """Handle requests for Groups."""
  302. @gen.coroutine
  303. def put(self, **kwargs):
  304. data = self.clean_body
  305. day = (data.get('day') or '').strip()
  306. group = (data.get('group') or '').strip()
  307. if not (day and group):
  308. return self.build_error(status=404, message='unable to access the resource')
  309. data['day'] = day
  310. data['group'] = group
  311. self.add_access_info(data)
  312. merged, doc = self.db.update('groups', {'day': day, 'group': group}, data)
  313. self.write(doc)
  314. class UsersHandler(BaseHandler):
  315. """Handle requests for Users."""
  316. document = 'user'
  317. collection = 'users'
  318. @gen.coroutine
  319. def get(self, id_=None, **kwargs):
  320. if id_:
  321. if not self.has_permission(id_):
  322. return
  323. output = self.db.getOne(self.collection, {'_id': id_})
  324. if 'password' in output:
  325. del output['password']
  326. else:
  327. if not self.current_user_info.get('isAdmin'):
  328. return self.build_error(status=401, message='insufficient permissions: must be an admin')
  329. output = {self.collection: self.db.query(self.collection, self.arguments)}
  330. for user in output['users']:
  331. if 'password' in user:
  332. del user['password']
  333. self.write(output)
  334. @gen.coroutine
  335. def post(self, **kwargs):
  336. data = self.clean_body
  337. username = (data.get('username') or '').strip()
  338. password = (data.get('password') or '').strip()
  339. email = (data.get('email') or '').strip()
  340. if not (username and password):
  341. raise InputException('missing username or password')
  342. res = self.db.query('users', {'username': username})
  343. if res:
  344. raise InputException('username already exists')
  345. data['username'] = username
  346. data['password'] = utils.hash_password(password)
  347. data['email'] = email
  348. self.add_access_info(data)
  349. if 'isAdmin' in data and not self.current_user_info.get('isAdmin'):
  350. del data['isAdmin']
  351. doc = self.db.add(self.collection, data)
  352. if 'password' in doc:
  353. del doc['password']
  354. self.write(doc)
  355. @gen.coroutine
  356. def put(self, id_=None, **kwargs):
  357. data = self.clean_body
  358. if id_ is None:
  359. return self.build_error(status=404, message='unable to access the resource')
  360. if not self.has_permission(id_):
  361. return
  362. if 'username' in data:
  363. del data['username']
  364. if 'isAdmin' in data and (str(self.current_user) == id_ or not self.current_user_info.get('isAdmin')):
  365. del data['isAdmin']
  366. if 'password' in data:
  367. password = (data['password'] or '').strip()
  368. if password:
  369. data['password'] = utils.hash_password(password)
  370. else:
  371. del data['password']
  372. self.add_access_info(data)
  373. merged, doc = self.db.update(self.collection, {'_id': id_}, data)
  374. if 'password' in doc:
  375. del doc['password']
  376. self.write(doc)
  377. @gen.coroutine
  378. def delete(self, id_=None, **kwargs):
  379. if id_ is None:
  380. return self.build_error(status=404, message='unable to access the resource')
  381. if not self.has_permission(id_):
  382. return
  383. howMany = self.db.delete(self.collection, id_)
  384. if id_ in self._users_cache:
  385. del self._users_cache[id_]
  386. self.write({'success': True, 'deleted entries': howMany.get('n')})
  387. class CurrentUserHandler(BaseHandler):
  388. """Handle requests for information about the logged in user."""
  389. @gen.coroutine
  390. def get(self, **kwargs):
  391. user_info = self.current_user_info or {}
  392. if 'password' in user_info:
  393. del user_info['password']
  394. self.write(user_info)
  395. class LoginHandler(RootHandler):
  396. """Handle user authentication requests."""
  397. @gen.coroutine
  398. def get(self, **kwargs):
  399. # show the login page
  400. if self.is_api():
  401. self.set_status(401)
  402. self.write({'error': True,
  403. 'message': 'authentication required'})
  404. @gen.coroutine
  405. def post(self, *args, **kwargs):
  406. # authenticate a user
  407. try:
  408. password = self.get_body_argument('password')
  409. username = self.get_body_argument('username')
  410. except tornado.web.MissingArgumentError:
  411. data = self.clean_body
  412. username = data.get('username')
  413. password = data.get('password')
  414. if not (username and password):
  415. self.set_status(401)
  416. self.write({'error': True, 'message': 'missing username or password'})
  417. return
  418. authorized, user = self.user_authorized(username, password)
  419. if authorized and 'username' in user and '_id' in user:
  420. id_ = str(user['_id'])
  421. username = user['username']
  422. logging.info('successful login for user %s (id: %s)' % (username, id_))
  423. self.set_secure_cookie("user", id_)
  424. user_info = self.current_user_info
  425. if 'password' in user_info:
  426. del user_info['password']
  427. self.write(user_info)
  428. return
  429. logging.info('login failed for user %s' % username)
  430. self.set_status(401)
  431. self.write({'error': True, 'message': 'wrong username and password'})
  432. class LogoutHandler(BaseHandler):
  433. """Handle user logout requests."""
  434. @gen.coroutine
  435. def get(self, **kwargs):
  436. # log the user out
  437. logging.info('logout')
  438. self.logout()
  439. self.write({'error': False, 'message': 'logged out'})
  440. def run():
  441. """Run the Tornado web application."""
  442. # command line arguments; can also be written in a configuration file,
  443. # specified with the --config argument.
  444. define("port", default=3000, help="run on the given port", type=int)
  445. define("address", default='', help="bind the server at the given address", type=str)
  446. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'ibt2_cert.pem'),
  447. help="specify the SSL certificate to use for secure connections")
  448. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'ibt2_key.pem'),
  449. help="specify the SSL private key to use for secure connections")
  450. define("mongo_url", default=None,
  451. help="URL to MongoDB server", type=str)
  452. define("db_name", default='ibt2',
  453. help="Name of the MongoDB database to use", type=str)
  454. define("debug", default=False, help="run in debug mode")
  455. define("config", help="read configuration file",
  456. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  457. tornado.options.parse_command_line()
  458. logger = logging.getLogger()
  459. logger.setLevel(logging.INFO)
  460. if options.debug:
  461. logger.setLevel(logging.DEBUG)
  462. ssl_options = {}
  463. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  464. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  465. # database backend connector
  466. db_connector = monco.Monco(url=options.mongo_url, dbName=options.db_name)
  467. init_params = dict(db=db_connector, listen_port=options.port, logger=logger, ssl_options=ssl_options)
  468. # If not present, we store a user 'admin' with password 'ibt2' into the database.
  469. if not db_connector.query('users', {'username': 'admin'}):
  470. db_connector.add('users',
  471. {'username': 'admin', 'password': utils.hash_password('ibt2'),
  472. 'isAdmin': True})
  473. # If present, use the cookie_secret stored into the database.
  474. cookie_secret = db_connector.query('settings', {'setting': 'server_cookie_secret'})
  475. if cookie_secret:
  476. cookie_secret = cookie_secret[0]['cookie_secret']
  477. else:
  478. # the salt guarantees its uniqueness
  479. cookie_secret = utils.hash_password('__COOKIE_SECRET__')
  480. db_connector.add('settings',
  481. {'setting': 'server_cookie_secret', 'cookie_secret': cookie_secret})
  482. _days_path = r"/days/?(?P<day>[\d_-]+)?"
  483. _groups_path = r"/groups/?"
  484. _attendees_path = r"/attendees/?(?P<id_>[\w\d_-]+)?"
  485. _current_user_path = r"/users/current/?"
  486. _users_path = r"/users/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  487. application = tornado.web.Application([
  488. (_attendees_path, AttendeesHandler, init_params),
  489. (r'/v%s%s' % (API_VERSION, _attendees_path), AttendeesHandler, init_params),
  490. (_days_path, DaysHandler, init_params),
  491. (r'/v%s%s' % (API_VERSION, _groups_path), GroupsHandler, init_params),
  492. (_groups_path, GroupsHandler, init_params),
  493. (r'/v%s%s' % (API_VERSION, _days_path), DaysHandler, init_params),
  494. (_current_user_path, CurrentUserHandler, init_params),
  495. (r'/v%s%s' % (API_VERSION, _current_user_path), CurrentUserHandler, init_params),
  496. (_users_path, UsersHandler, init_params),
  497. (r'/v%s%s' % (API_VERSION, _users_path), UsersHandler, init_params),
  498. (r"/(?:index.html)?", RootHandler, init_params),
  499. (r'/login', LoginHandler, init_params),
  500. (r'/v%s/login' % API_VERSION, LoginHandler, init_params),
  501. (r'/logout', LogoutHandler),
  502. (r'/v%s/logout' % API_VERSION, LogoutHandler),
  503. (r'/?(.*)', tornado.web.StaticFileHandler, {"path": "dist"})
  504. ],
  505. static_path=os.path.join(os.path.dirname(__file__), "dist/static"),
  506. cookie_secret='__COOKIE_SECRET__',
  507. login_url='/login',
  508. debug=options.debug)
  509. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  510. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  511. options.address if options.address else '127.0.0.1',
  512. options.port)
  513. http_server.listen(options.port, options.address)
  514. tornado.ioloop.IOLoop.instance().start()
  515. if __name__ == '__main__':
  516. try:
  517. run()
  518. except KeyboardInterrupt:
  519. print('Stop server')