ibt2.py 28 KB

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