diff --git a/.gitignore b/.gitignore index e3f3570..24a8fff 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ dist/ *.egg-info .tox/ .cache/ +*.swp diff --git a/README.md b/README.md index c4a7549..46d8577 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,9 @@ Step 6: Set up all the correct options (see below for available options) * OAUTHADMIN_GET_USER: This is function that is given the oauth token and returns a django.auth.models.User model corresponding to the currently logged-in user. You can set permissions on this user object and stuff. + * OAUTHADMIN_GET_USER_EXCEPTION_HANDLER: Callable that receives request object, OAuth token + and exception to handle business logics such as unauthorized users. This callable should + return proper response object. * OAUTHADMIN_CLIENT_ID: Your oAuth client ID * OAUTHADMIN_CLIENT_SECRET: oAuth client secret * OAUTHADMIN_BASE_URL: The landing point for all oAuth related queries. diff --git a/oauthadmin/errors.py b/oauthadmin/errors.py new file mode 100644 index 0000000..3509aef --- /dev/null +++ b/oauthadmin/errors.py @@ -0,0 +1,6 @@ +class OAuthAdminException(Exception): + pass + + +class GetUserException(OAuthAdminException): + pass diff --git a/oauthadmin/views.py b/oauthadmin/views.py index 8a22bd5..2887c26 100644 --- a/oauthadmin/views.py +++ b/oauthadmin/views.py @@ -11,12 +11,14 @@ from urllib.parse import quote_plus from django.shortcuts import redirect -from django.http import HttpResponseRedirect +from django.http import HttpResponse, HttpResponseRedirect -from oauthadmin.utils import import_by_path -from oauthadmin.settings import app_setting import oauthadmin.views +from oauthadmin.errors import GetUserException +from oauthadmin.settings import app_setting +from oauthadmin.utils import import_by_path + try: from django.urls import reverse, NoReverseMatch except ImportError: @@ -82,7 +84,15 @@ def callback(request): except (MismatchingStateError, InvalidGrantError): return HttpResponseRedirect(request.build_absolute_uri(reverse(oauthadmin.views.login))) - user = import_by_path(app_setting('GET_USER'))(token) + user_getter = import_by_path(app_setting('GET_USER')) + try: + user = user_getter(token) + except GetUserException as e: + get_user_exception_handler_module = app_setting('GET_USER_EXCEPTION_HANDLER') + if get_user_exception_handler_module: + get_user_exception_handler = import_by_path(get_user_exception_handler_module) + return get_user_exception_handler(request, token, e) + raise request.session['last_verified_at'] = int(time()) request.session['oauth_token'] = token