def ensure_oauth2(provider):
    """
    Decorator to ensure a user has been authenticated with the given oauth2 provider.

    Usage:

        from tethys_sdk.services import ensure_oauth2, get_dataset_engine

        @ensure_oauth2('hydroshare-oauth2')
        def controller(request):
            engine = get_dataset_engine('default_hydroshare', request=request)
            return render(request, 'my_template.html', {})

    Note that calling get_dataset_engine for a hydroshare dataset engine will throw an error 
    if it is not called in a function that is decorated with the ensure_oauth2 decorator.
    """
    def decorator(function):
        @wraps(function)
        def wrapper(request, *args, **kwargs):
            user = request.user

            # Assemble redirect response
            redirect_url = reverse('social:begin', args=[provider]) + '?next={0}'.format(request.path)
            redirect_response = redirect(redirect_url)

            try:
                user.social_auth.get(provider=provider)
            except ObjectDoesNotExist:
                # User is not associated with that provider
                return redirect_response
            except __HOLE__:
                # Anonymous User needs to be logged in and associated with that provider
                # return redirect('/login/{0}/?next={1}'.format(provider, request.path))
                return redirect_response
            except AuthAlreadyAssociated:
                # Another user has already used the account to associate...
                raise
            except:
                raise
            return function(request, *args, **kwargs)
        return wrapper
    return decorator
dataset/ETHPy150Open tethysplatform/tethys/tethys_services/utilities.py/ensure_oauth2