raise 403 on disallowed user, rather than redirect to login url

raise UserNotAllowed exception in generic `check_hub_user`
when a user or service is identified and not allowed.

turn it into `HTTPError(403)` in tornado `get_current_user` wrapper,
caching `None` so that subsequent calls don't re-trigger the same error.
This commit is contained in:
Min RK
2017-06-07 15:30:12 +02:00
parent ca4952a85d
commit dda3762b48
3 changed files with 34 additions and 8 deletions

View File

@@ -7,7 +7,6 @@ HubAuth can be used in any application, even outside tornado.
HubAuthenticated is a mixin class for tornado handlers that should authenticate with the Hub.
"""
import json
import os
import re
import socket
@@ -492,7 +491,19 @@ class HubOAuth(HubAuth):
def clear_cookie(self, handler):
"""Clear the OAuth cookie"""
handler.clear_cookie(self.cookie_name, path=self.base_url)
class UserNotAllowed(Exception):
"""Exception raised when a user is identified and not allowed"""
def __init__(self, model):
self.model = model
def __str__(self):
return '<{cls} {kind}={name}>'.format(
cls=self.__class__.__name__,
kind=self.model['kind'],
name=self.model['name'],
)
class HubAuthenticated(object):
@@ -568,7 +579,7 @@ class HubAuthenticated(object):
"""
name = model['name']
kind = model.get('kind', 'user')
kind = model.setdefault('kind', 'user')
if self.allow_all:
app_log.debug("Allowing Hub %s %s (all Hub users and services allowed)", kind, name)
return model
@@ -584,7 +595,7 @@ class HubAuthenticated(object):
return model
else:
app_log.warning("Not allowing Hub service %s", name)
return None
raise UserNotAllowed(model)
if self.hub_users and name in self.hub_users:
# user in whitelist
@@ -597,7 +608,7 @@ class HubAuthenticated(object):
return model
else:
app_log.warning("Not allowing Hub user %s", name)
return None
raise UserNotAllowed(model)
def get_current_user(self):
"""Tornado's authentication method
@@ -611,7 +622,15 @@ class HubAuthenticated(object):
if not user_model:
self._hub_auth_user_cache = None
return
self._hub_auth_user_cache = self.check_hub_user(user_model)
try:
self._hub_auth_user_cache = self.check_hub_user(user_model)
except UserNotAllowed as e:
# cache None, in case get_user is called again while processing the error
self._hub_auth_user_cache = None
raise HTTPError(403, "{kind} {name} is not allowed.".format(**e.model))
except Exception:
self._hub_auth_user_cache = None
raise
return self._hub_auth_user_cache