ibt2.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """I'll Be There, 2 (ibt2) - an oversimplified attendees registration system.
  4. Copyright 2016-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 logging
  18. import datetime
  19. from operator import itemgetter
  20. import itertools
  21. import tornado.httpserver
  22. import tornado.ioloop
  23. import tornado.options
  24. from tornado.options import define, options
  25. import tornado.web
  26. from tornado import gen, escape
  27. import utils
  28. import monco
  29. API_VERSION = '1.1'
  30. class BaseException(Exception):
  31. """Base class for ibt2 custom exceptions.
  32. :param message: text message
  33. :type message: str
  34. :param status: numeric http status code
  35. :type status: int"""
  36. def __init__(self, message, status=400):
  37. super(BaseException, self).__init__(message)
  38. self.message = message
  39. self.status = status
  40. class InputException(BaseException):
  41. """Exception raised by errors in input handling."""
  42. pass
  43. class BaseHandler(tornado.web.RequestHandler):
  44. """Base class for request handlers."""
  45. # Cache currently connected users.
  46. _users_cache = {}
  47. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  48. document = None
  49. collection = None
  50. # A property to access the first value of each argument.
  51. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  52. for k, v in self.request.arguments.items()]))
  53. # Arguments suitable for a query on MongoDB.
  54. clean_arguments = property(lambda self: self._clean_dict(self.arguments))
  55. _re_split_salt = re.compile(r'\$(?P<salt>.+)\$(?P<hash>.+)')
  56. @property
  57. def clean_body(self):
  58. """Return a clean dictionary from a JSON body, suitable for a query on MongoDB.
  59. :returns: a clean copy of the body arguments
  60. :rtype: dict"""
  61. data = escape.json_decode(self.request.body or '{}')
  62. return self._clean_dict(data)
  63. def _clean_dict(self, data):
  64. """Filter a dictionary (in place) to remove unwanted keywords in db queries.
  65. :param data: dictionary to clean
  66. :type data: dict"""
  67. if isinstance(data, dict):
  68. for key in list(data.keys()):
  69. if (isinstance(key, str) and key.startswith('$')) or key in ('_id', 'created_by', 'created_at',
  70. 'updated_by', 'updated_at', 'isRegistered'):
  71. del data[key]
  72. return data
  73. def write_error(self, status_code, **kwargs):
  74. """Default error handler."""
  75. if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
  76. exc = kwargs['exc_info'][1]
  77. status_code = exc.status
  78. message = exc.message
  79. else:
  80. message = 'internal error'
  81. self.build_error(message, status=status_code)
  82. def is_api(self):
  83. """Return True if the path is from an API call."""
  84. return self.request.path.startswith('/v%s' % API_VERSION)
  85. def initialize(self, **kwargs):
  86. """Add every passed (key, value) as attributes of the instance."""
  87. for key, value in kwargs.items():
  88. setattr(self, key, value)
  89. @property
  90. def current_user(self):
  91. """Retrieve current user ID from the secure cookie."""
  92. current_user = self.get_secure_cookie("user")
  93. if isinstance(current_user, bytes):
  94. current_user = current_user.decode('utf-8')
  95. return current_user
  96. @property
  97. def current_user_info(self):
  98. """Information about the current user.
  99. :returns: full information about the current user
  100. :rtype: dict"""
  101. current_user = self.current_user
  102. if current_user in self._users_cache:
  103. return self._users_cache[current_user]
  104. user_info = {}
  105. if current_user:
  106. user_info['_id'] = current_user
  107. user = self.db.getOne('users', {'_id': user_info['_id']})
  108. if user:
  109. user_info = user
  110. user_info['isRegistered'] = True
  111. self._users_cache[current_user] = user_info
  112. return user_info
  113. def is_registered(self):
  114. """Check if the current user is registered.
  115. :returns: True if a registered user is logged in
  116. :rtype: bool"""
  117. return self.current_user_info.get('isRegistered')
  118. def is_admin(self):
  119. """Check if the current user is an admin.
  120. :returns: True if the logged in user is an admin
  121. :rtype: bool"""
  122. return self.current_user_info.get('isAdmin')
  123. def user_authorized(self, username, password):
  124. """Check if a combination of username/password is valid.
  125. :param username: username or email
  126. :type username: str
  127. :param password: password
  128. :type password: str
  129. :returns: tuple like (bool_user_is_authorized, dict_user_info)
  130. :rtype: dict"""
  131. query = [{'username': username}, {'email': username}]
  132. res = self.db.query('users', query)
  133. if not res:
  134. return (False, {})
  135. user = res[0]
  136. db_password = user.get('password') or ''
  137. if not db_password:
  138. return (False, {})
  139. match = self._re_split_salt.match(db_password)
  140. if not match:
  141. return (False, {})
  142. salt = match.group('salt')
  143. if utils.hash_password(password, salt=salt) == db_password:
  144. return (True, user)
  145. return (False, {})
  146. def build_error(self, message='', status=400):
  147. """Build and write an error message.
  148. :param message: textual message
  149. :type message: str
  150. :param status: HTTP status code
  151. :type status: int
  152. """
  153. self.set_status(status)
  154. self.write({'error': True, 'message': message})
  155. def has_permission(self, owner_id):
  156. """Check if the given owner_id matches with the current user or the logged in user is an admin; if not,
  157. build an error reply.
  158. :param owner_id: owner ID to check against
  159. :type owner_id: str, ObjectId, None
  160. :returns: if the logged in user has the permission
  161. :rtype: bool"""
  162. if (owner_id and str(self.current_user) != str(owner_id) and not
  163. self.is_admin()):
  164. self.build_error(status=401, message='insufficient permissions: must be the owner or admin')
  165. return False
  166. return True
  167. def logout(self):
  168. """Remove the secure cookie used fro authentication."""
  169. if self.current_user in self._users_cache:
  170. del self._users_cache[self.current_user]
  171. self.clear_cookie("user")
  172. def add_access_info(self, doc):
  173. """Add created/updated by/at to a document (modified in place and returned).
  174. :param doc: the doc to be updated
  175. :type doc: dict
  176. :returns: the updated document
  177. :rtype: dict"""
  178. user_id = self.current_user
  179. now = datetime.datetime.utcnow()
  180. if 'created_by' not in doc:
  181. doc['created_by'] = user_id
  182. if 'created_at' not in doc:
  183. doc['created_at'] = now
  184. doc['updated_by'] = user_id
  185. doc['updated_at'] = now
  186. return doc
  187. @staticmethod
  188. def update_global_settings(db_connector, settings=None):
  189. """Update global settings from the db.
  190. :param db_connector: database connector
  191. :type db_connector: Monco instance
  192. :param settings: the dict to update (in place, and returned)
  193. :type settings: dict
  194. :returns: the updated dictionary, also modified in place
  195. :rtype: dict"""
  196. if settings is None:
  197. settings = {}
  198. settings.clear()
  199. for setting in db_connector.query('settings'):
  200. if not ('_id' in setting and 'value' in setting):
  201. continue
  202. settings[setting['_id']] = setting['value']
  203. return settings
  204. class RootHandler(BaseHandler):
  205. """Handler for the / path."""
  206. app_path = os.path.join(os.path.dirname(__file__), "dist")
  207. @gen.coroutine
  208. def get(self, *args, **kwargs):
  209. # serve the ./app/index.html file
  210. with open(self.app_path + "/index.html", 'r') as fd:
  211. self.write(fd.read())
  212. class AttendeesHandler(BaseHandler):
  213. document = 'attendee'
  214. collection = 'attendees'
  215. @gen.coroutine
  216. def get(self, id_=None, **kwargs):
  217. if id_:
  218. output = self.db.getOne(self.collection, {'_id': id_})
  219. else:
  220. output = {self.collection: self.db.query(self.collection, self.clean_arguments)}
  221. self.write(output)
  222. @gen.coroutine
  223. def post(self, **kwargs):
  224. data = self.clean_body
  225. for key in 'name', 'group', 'day':
  226. value = (data.get(key) or '').strip()
  227. if not value:
  228. return self.build_error(status=404, message="%s can't be empty" % key)
  229. data[key] = value
  230. self.add_access_info(data)
  231. doc = self.db.add(self.collection, data)
  232. self.write(doc)
  233. @gen.coroutine
  234. def put(self, id_, **kwargs):
  235. data = self.clean_body
  236. doc = self.db.getOne(self.collection, {'_id': id_}) or {}
  237. if not doc:
  238. return self.build_error(status=404, message='unable to access the resource')
  239. if not self.has_permission(doc.get('created_by')):
  240. return
  241. if self.global_settings.get('protectUnregistered') and not self.is_admin():
  242. return self.build_error(status=401, message='insufficient permissions: must be admin')
  243. self.add_access_info(data)
  244. merged, doc = self.db.update(self.collection, {'_id': id_}, data)
  245. self.write(doc)
  246. @gen.coroutine
  247. def delete(self, id_=None, **kwargs):
  248. if id_ is None:
  249. return self.build_error(status=404, message='unable to access the resource')
  250. doc = self.db.getOne(self.collection, {'_id': id_}) or {}
  251. if not doc:
  252. return self.build_error(status=404, message='unable to access the resource')
  253. if not self.has_permission(doc.get('created_by')):
  254. return
  255. if self.global_settings.get('protectUnregistered') and not self.is_admin():
  256. return self.build_error(status=401, message='insufficient permissions: must be admin')
  257. howMany = self.db.delete(self.collection, id_)
  258. self.write({'success': True, 'deleted entries': howMany.get('n')})
  259. class DaysHandler(BaseHandler):
  260. """Handle requests for Days."""
  261. def _summarize(self, days):
  262. res = []
  263. for day in days:
  264. res.append({'day': day['day'], 'groups_count': len(day.get('groups', []))})
  265. return res
  266. @gen.coroutine
  267. def get(self, day=None, **kwargs):
  268. params = self.clean_arguments
  269. summary = params.get('summary', False)
  270. if summary:
  271. del params['summary']
  272. start = params.get('start')
  273. if start:
  274. del params['start']
  275. end = params.get('end')
  276. if end:
  277. del params['end']
  278. base = {}
  279. groupsDetails = {}
  280. if day:
  281. params['day'] = day
  282. base = self.db.getOne('days', {'day': day})
  283. groupsDetails = dict([(x['group'], x) for x in self.db.query('groups', {'day': day})])
  284. else:
  285. if start:
  286. params['day'] = {'$gte': start}
  287. if end:
  288. if 'day' not in params:
  289. params['day'] = {}
  290. if end.count('-') == 0:
  291. end += '-13'
  292. elif end.count('-') == 1:
  293. end += '-31'
  294. params['day'].update({'$lte': end})
  295. results = self.db.query('attendees', params)
  296. days = []
  297. dayData = {}
  298. try:
  299. sortedDays = []
  300. for result in results:
  301. if not ('day' in result and 'group' in result and 'name' in result):
  302. self.logger.warn('unable to parse entry; dayData: %s', dayData)
  303. continue
  304. sortedDays.append(result)
  305. sortedDays = sorted(sortedDays, key=itemgetter('day'))
  306. for d, dayItems in itertools.groupby(sortedDays, key=itemgetter('day')):
  307. dayData = {'day': d, 'groups': []}
  308. for group, attendees in itertools.groupby(sorted(dayItems, key=itemgetter('group')),
  309. key=itemgetter('group')):
  310. attendees = sorted(attendees, key=itemgetter('_id'))
  311. groupData = groupsDetails.get(group) or {}
  312. groupData.update({'group': group, 'attendees': attendees})
  313. dayData['groups'].append(groupData)
  314. days.append(dayData)
  315. except Exception as e:
  316. self.logger.warn('unable to parse entry; dayData: %s error: %s', dayData, e)
  317. if summary:
  318. days = self._summarize(days)
  319. if not day:
  320. self.write({'days': days})
  321. elif days:
  322. base.update(days[0])
  323. self.write(base)
  324. else:
  325. self.write(base)
  326. class DaysInfoHandler(BaseHandler):
  327. """Handle requests for Days info."""
  328. @gen.coroutine
  329. def put(self, day='', **kwargs):
  330. day = day.strip()
  331. if not day:
  332. return self.build_error(status=404, message='unable to access the resource')
  333. data = self.clean_body
  334. if 'notes' in data and self.global_settings.get('protectDayNotes') and not self.is_admin():
  335. return self.build_error(status=401, message='insufficient permissions: must be admin')
  336. data['day'] = day
  337. self.add_access_info(data)
  338. merged, doc = self.db.update('days', {'day': day}, data)
  339. self.write(doc)
  340. class GroupsHandler(BaseHandler):
  341. """Handle requests for Groups."""
  342. @gen.coroutine
  343. def put(self, day='', group='', **kwargs):
  344. day = day.strip()
  345. group = group.strip()
  346. if not (day and group):
  347. return self.build_error(status=404, message='unable to access the resource')
  348. data = self.clean_body
  349. newName = (data.get('newName') or '').strip()
  350. if newName:
  351. if self.global_settings.get('protectGroupName') and not self.is_admin():
  352. return self.build_error(status=401, message='insufficient permissions: must be admin')
  353. query = {'day': day, 'group': group}
  354. data = {'group': newName}
  355. self.db.updateMany('attendees', query, data)
  356. self.db.updateMany('groups', query, data)
  357. self.write({'success': True})
  358. else:
  359. self.write({'success': False})
  360. @gen.coroutine
  361. def delete(self, day='', group='', **kwargs):
  362. day = day.strip()
  363. group = group.strip()
  364. if not (day and group):
  365. return self.build_error(status=404, message='unable to access the resource')
  366. if not self.is_admin():
  367. return self.build_error(status=401, message='insufficient permissions: must be admin')
  368. query = {'day': day, 'group': group}
  369. howMany = self.db.delete('attendees', query)
  370. self.db.delete('groups', query)
  371. self.write({'success': True, 'deleted entries': howMany.get('n')})
  372. class GroupsInfoHandler(BaseHandler):
  373. """Handle requests for Groups Info."""
  374. @gen.coroutine
  375. def put(self, day='', group='', **kwargs):
  376. day = day.strip()
  377. group = group.strip()
  378. if not (day and group):
  379. return self.build_error(status=404, message='unable to access the resource')
  380. data = self.clean_body
  381. if 'notes' in data and self.global_settings.get('protectGroupNotes') and not self.is_admin():
  382. return self.build_error(status=401, message='insufficient permissions: must be admin')
  383. data['day'] = day
  384. data['group'] = group
  385. self.add_access_info(data)
  386. merged, doc = self.db.update('groups', {'day': day, 'group': group}, data)
  387. self.write(doc)
  388. class UsersHandler(BaseHandler):
  389. """Handle requests for Users."""
  390. document = 'user'
  391. collection = 'users'
  392. @gen.coroutine
  393. def get(self, id_=None, **kwargs):
  394. if id_:
  395. if not self.has_permission(id_):
  396. return
  397. output = self.db.getOne(self.collection, {'_id': id_})
  398. if 'password' in output:
  399. del output['password']
  400. else:
  401. if not self.is_admin():
  402. return self.build_error(status=401, message='insufficient permissions: must be an admin')
  403. output = {self.collection: self.db.query(self.collection, self.clean_arguments)}
  404. for user in output['users']:
  405. if 'password' in user:
  406. del user['password']
  407. self.write(output)
  408. @gen.coroutine
  409. def post(self, **kwargs):
  410. data = self.clean_body
  411. username = (data.get('username') or '').strip()
  412. password = (data.get('password') or '').strip()
  413. email = (data.get('email') or '').strip()
  414. if not (username and password):
  415. raise InputException('missing username or password')
  416. res = self.db.query('users', {'username': username})
  417. if res:
  418. raise InputException('username already exists')
  419. data['username'] = username
  420. data['password'] = utils.hash_password(password)
  421. data['email'] = email
  422. self.add_access_info(data)
  423. if 'isAdmin' in data and not self.is_admin():
  424. del data['isAdmin']
  425. doc = self.db.add(self.collection, data)
  426. if 'password' in doc:
  427. del doc['password']
  428. self.write(doc)
  429. @gen.coroutine
  430. def put(self, id_=None, **kwargs):
  431. data = self.clean_body
  432. if id_ is None:
  433. return self.build_error(status=404, message='unable to access the resource')
  434. if not self.has_permission(id_):
  435. return
  436. if 'username' in data:
  437. del data['username']
  438. if 'isAdmin' in data and (str(self.current_user) == id_ or not self.is_admin()):
  439. del data['isAdmin']
  440. if 'password' in data:
  441. password = (data['password'] or '').strip()
  442. if password:
  443. data['password'] = utils.hash_password(password)
  444. else:
  445. del data['password']
  446. self.add_access_info(data)
  447. merged, doc = self.db.update(self.collection, {'_id': id_}, data)
  448. if 'password' in doc:
  449. del doc['password']
  450. self.write(doc)
  451. @gen.coroutine
  452. def delete(self, id_=None, **kwargs):
  453. if id_ is None:
  454. return self.build_error(status=404, message='unable to access the resource')
  455. if not self.has_permission(id_):
  456. return self.build_error(status=401, message='insufficient permissions: must be admin')
  457. if id_ == self.current_user:
  458. return self.build_error(status=401, message='unable to delete the current user; ask an admin')
  459. doc = self.db.getOne(self.collection, {'_id': id_})
  460. if not doc:
  461. return self.build_error(status=404, message='unable to access the resource')
  462. if doc.get('username') == 'admin':
  463. return self.build_error(status=401, message='unable to delete the admin user')
  464. howMany = self.db.delete(self.collection, id_)
  465. if id_ in self._users_cache:
  466. del self._users_cache[id_]
  467. self.write({'success': True, 'deleted entries': howMany.get('n')})
  468. class CurrentUserHandler(BaseHandler):
  469. """Handle requests for information about the logged in user."""
  470. @gen.coroutine
  471. def get(self, **kwargs):
  472. user_info = self.current_user_info or {}
  473. if 'password' in user_info:
  474. del user_info['password']
  475. self.write(user_info)
  476. class SettingsHandler(BaseHandler):
  477. """Handle global settings."""
  478. collection = 'settings'
  479. def get(self, id_=None):
  480. query = {}
  481. if id_ is not None:
  482. query['_id'] = id_
  483. res = self.db.query(self.collection, query)
  484. res = dict((i.get('_id'), i.get('value')) for i in res if '_id' in i and isinstance(i.get('_id'), str))
  485. if id_ is not None:
  486. res = {id_: res.get(id_)}
  487. self.write(res)
  488. def post(self, id_=None):
  489. if not self.is_admin():
  490. return self.build_error(status=401, message='insufficient permissions: must be an admin')
  491. data = self.clean_body
  492. if id_ is not None:
  493. # if we access a specific resource, we assume the data is in {_id: value} format
  494. if id_ not in data:
  495. return self.build_error(status=404, message='incomplete data')
  496. return
  497. data = {id_: data[id_]}
  498. for key, value in data.items():
  499. if self.db.get(self.collection, key):
  500. self.db.update(self.collection, {'_id': key}, {'value': value})
  501. else:
  502. self.db.add(self.collection, {'_id': key, 'value': value})
  503. settings = SettingsHandler.update_global_settings(self.db, self.global_settings)
  504. self.write(settings)
  505. put = post
  506. class LoginHandler(RootHandler):
  507. """Handle user authentication requests."""
  508. @gen.coroutine
  509. def get(self, **kwargs):
  510. # show the login page
  511. if self.is_api():
  512. self.set_status(401)
  513. self.write({'error': True,
  514. 'message': 'authentication required'})
  515. @gen.coroutine
  516. def post(self, *args, **kwargs):
  517. # authenticate a user
  518. try:
  519. password = self.get_body_argument('password')
  520. username = self.get_body_argument('username')
  521. except tornado.web.MissingArgumentError:
  522. data = self.clean_body
  523. username = data.get('username')
  524. password = data.get('password')
  525. if not (username and password):
  526. self.set_status(401)
  527. self.write({'error': True, 'message': 'missing username or password'})
  528. return
  529. authorized, user = self.user_authorized(username, password)
  530. if authorized and 'username' in user and '_id' in user:
  531. id_ = str(user['_id'])
  532. username = user['username']
  533. logging.info('successful login for user %s (id: %s)' % (username, id_))
  534. self.set_secure_cookie("user", id_)
  535. user_info = self.current_user_info
  536. if 'password' in user_info:
  537. del user_info['password']
  538. self.write(user_info)
  539. return
  540. logging.info('login failed for user %s' % username)
  541. self.set_status(401)
  542. self.write({'error': True, 'message': 'wrong username and password'})
  543. class LogoutHandler(BaseHandler):
  544. """Handle user logout requests."""
  545. @gen.coroutine
  546. def get(self, **kwargs):
  547. # log the user out
  548. logging.info('logout')
  549. self.logout()
  550. self.write({'error': False, 'message': 'logged out'})
  551. def run():
  552. """Run the Tornado web application."""
  553. # command line arguments; can also be written in a configuration file,
  554. # specified with the --config argument.
  555. define("port", default=3000, help="run on the given port", type=int)
  556. define("address", default='', help="bind the server at the given address", type=str)
  557. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'ibt2_cert.pem'),
  558. help="specify the SSL certificate to use for secure connections")
  559. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'ibt2_key.pem'),
  560. help="specify the SSL private key to use for secure connections")
  561. define("mongo_url", default=None,
  562. help="URL to MongoDB server", type=str)
  563. define("db_name", default='ibt2',
  564. help="Name of the MongoDB database to use", type=str)
  565. define("debug", default=False, help="run in debug mode")
  566. define("config", help="read configuration file",
  567. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  568. tornado.options.parse_command_line()
  569. logger = logging.getLogger()
  570. logger.setLevel(logging.INFO)
  571. if options.debug:
  572. logger.setLevel(logging.DEBUG)
  573. ssl_options = {}
  574. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  575. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  576. # database backend connector
  577. db_connector = monco.Monco(url=options.mongo_url, dbName=options.db_name)
  578. # global settings stored in the db
  579. global_settings = {}
  580. BaseHandler.update_global_settings(db_connector, global_settings)
  581. init_params = dict(db=db_connector, listen_port=options.port, logger=logger,
  582. ssl_options=ssl_options, global_settings=global_settings)
  583. # If not present, we store a user 'admin' with password 'ibt2' into the database.
  584. if not db_connector.query('users', {'username': 'admin'}):
  585. db_connector.add('users',
  586. {'username': 'admin', 'password': utils.hash_password('ibt2'),
  587. 'isAdmin': True})
  588. # If present, use the cookie_secret stored into the database.
  589. cookie_secret = db_connector.get('server_settings', 'server_cookie_secret')
  590. if cookie_secret:
  591. cookie_secret = cookie_secret['value']
  592. else:
  593. # the salt guarantees its uniqueness
  594. cookie_secret = utils.hash_password('__COOKIE_SECRET__')
  595. db_connector.add('server_settings',
  596. {'_id': 'server_cookie_secret', 'value': cookie_secret})
  597. _days_path = r"/days/?(?P<day>[\d_-]+)?"
  598. _days_info_path = r"/days/(?P<day>[\d_-]+)/info"
  599. _groups_path = r"/days/(?P<day>[\d_-]+)/groups/(?P<group>.+?)"
  600. _groups_info_path = r"/days/(?P<day>[\d_-]+)/groups/(?P<group>.+?)/info"
  601. _attendees_path = r"/attendees/?(?P<id_>[\w\d_-]+)?"
  602. _current_user_path = r"/users/current/?"
  603. _users_path = r"/users/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  604. _settings_path = r"/settings/?(?P<id_>[\w\d_ -]+)?/?"
  605. application = tornado.web.Application([
  606. (_attendees_path, AttendeesHandler, init_params),
  607. (r'/v%s%s' % (API_VERSION, _attendees_path), AttendeesHandler, init_params),
  608. (_groups_info_path, GroupsInfoHandler, init_params),
  609. (r'/v%s%s' % (API_VERSION, _groups_info_path), GroupsInfoHandler, init_params),
  610. (_groups_path, GroupsHandler, init_params),
  611. (r'/v%s%s' % (API_VERSION, _groups_path), GroupsHandler, init_params),
  612. (_days_path, DaysHandler, init_params),
  613. (r'/v%s%s' % (API_VERSION, _days_path), DaysHandler, init_params),
  614. (_days_info_path, DaysInfoHandler, init_params),
  615. (r'/v%s%s' % (API_VERSION, _days_info_path), DaysInfoHandler, init_params),
  616. (_current_user_path, CurrentUserHandler, init_params),
  617. (r'/v%s%s' % (API_VERSION, _current_user_path), CurrentUserHandler, init_params),
  618. (_users_path, UsersHandler, init_params),
  619. (r'/v%s%s' % (API_VERSION, _users_path), UsersHandler, init_params),
  620. (_settings_path, SettingsHandler, init_params),
  621. (r'/v%s%s' % (API_VERSION, _settings_path), SettingsHandler, init_params),
  622. (r"/(?:index.html)?", RootHandler, init_params),
  623. (r'/login', LoginHandler, init_params),
  624. (r'/v%s/login' % API_VERSION, LoginHandler, init_params),
  625. (r'/logout', LogoutHandler),
  626. (r'/v%s/logout' % API_VERSION, LogoutHandler),
  627. (r'/?(.*)', tornado.web.StaticFileHandler, {"path": "dist"})
  628. ],
  629. static_path=os.path.join(os.path.dirname(__file__), "dist/static"),
  630. cookie_secret=cookie_secret,
  631. login_url='/login',
  632. debug=options.debug)
  633. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  634. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  635. options.address if options.address else '127.0.0.1',
  636. options.port)
  637. http_server.listen(options.port, options.address)
  638. tornado.ioloop.IOLoop.instance().start()
  639. if __name__ == '__main__':
  640. try:
  641. run()
  642. except KeyboardInterrupt:
  643. print('Stop server')