# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.http import HttpResponseBadRequest

import oauth2 as oauth

from oauth_provider.utils import send_oauth_error

INVALID_PARAMS_RESPONSE = send_oauth_error(
    oauth.Error(_('Invalid request parameters.')))
INVALID_CONSUMER_RESPONSE = HttpResponseBadRequest('Invalid Consumer.')
INVALID_SCOPE_RESPONSE = send_oauth_error(
    oauth.Error(_('You are not allowed to access this resource.')))
COULD_NOT_VERIFY_OAUTH_REQUEST_RESPONSE = send_oauth_error(
    oauth.Error(_('Could not verify OAuth request.')))
Пример #2
0
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.utils.translation import ugettext as _
from django.core.urlresolvers import get_callable
from django.views.generic.simple import direct_to_template

from decorators import oauth_required
from forms import AuthorizeRequestTokenForm
from store import store, InvalidConsumerError, InvalidTokenError
from utils import verify_oauth_request, get_oauth_request, require_params, send_oauth_error
from consts import OUT_OF_BAND

OAUTH_AUTHORIZE_VIEW = 'OAUTH_AUTHORIZE_VIEW'
OAUTH_CALLBACK_VIEW = 'OAUTH_CALLBACK_VIEW'
INVALID_PARAMS_RESPONSE = send_oauth_error(
    oauth.Error(_('Invalid request parameters.')))


@csrf_exempt
def request_token(request):
    oauth_request = get_oauth_request(request)
    if oauth_request is None:
        return INVALID_PARAMS_RESPONSE

    missing_params = require_params(oauth_request, ('oauth_callback', ))
    if missing_params is not None:
        return missing_params

    try:
        consumer = store.get_consumer(request, oauth_request,
                                      oauth_request['oauth_consumer_key'])
Пример #3
0
def user_authorization(request, form_class=AuthorizeRequestTokenForm):
    if request.method.lower() == 'get':
        if 'oauth_token' not in request.GET:
            return HttpResponseBadRequest('No request token specified.')
        incoming_token = request.GET['oauth_token']
    elif request.method.lower() == 'post':
        if 'oauth_token' not in request.POST:
            return HttpResponseBadRequest('No request token specified.')
        incoming_token = request.POST['oauth_token']

    oauth_request = get_oauth_request(request)

    try:
        request_token = store.get_request_token(request, oauth_request,
                                                incoming_token)
    except InvalidTokenError:
        return HttpResponse('Invalid request token: %s' % incoming_token,
                            status=401)

    consumer = store.get_consumer_for_request_token(request, oauth_request,
                                                    request_token)

    # LRS CHANGE - MAKE SURE LOGGED IN USER OWNS THIS CONSUMER
    if request.user != consumer.user:
        return HttpResponseForbidden('Invalid user for this client.')

    if request.method == 'POST':
        form = form_class(request.POST)
        if request.session.get('oauth',
                               '') == request_token.key and form.is_valid():
            request.session['oauth'] = ''
            if form.cleaned_data['authorize_access']:
                request_token = store.authorize_request_token(
                    request, oauth_request, request_token)
                args = {'oauth_token': request_token.key}
            else:
                args = {'error': _('Access not granted by user.')}
            if request_token.callback is not None and request_token.callback != OUT_OF_BAND:
                callback_url = request_token.get_callback_url(args)
                if UNSAFE_REDIRECTS:
                    response = UnsafeRedirect(callback_url)
                else:
                    response = HttpResponseRedirect(callback_url)
            else:
                # try to get custom callback view
                callback_view_str = getattr(
                    settings, OAUTH_CALLBACK_VIEW,
                    'oauth_provider.views.fake_callback_view')
                try:
                    view_callable = get_callable(callback_view_str)
                except AttributeError:
                    raise Exception, "%s view doesn't exist." % callback_view_str

                # try to treat it as Class Based View (CBV)
                try:
                    callback_view = view_callable.as_view()
                except AttributeError:
                    # if it appears not to be CBV treat it like FBV
                    callback_view = view_callable

                response = callback_view(request, **args)
        else:
            response = send_oauth_error(oauth.Error(_('Action not allowed.')))
    else:
        # try to get custom authorize view
        authorize_view_str = getattr(
            settings, OAUTH_AUTHORIZE_VIEW,
            'oauth_provider.views.fake_authorize_view')
        try:
            view_callable = get_callable(authorize_view_str)
        except AttributeError:
            raise Exception, "%s view doesn't exist." % authorize_view_str

        # try to treat it as Class Based View (CBV)
        try:
            authorize_view = view_callable.as_view()
        except AttributeError:
            # if it appears not to be CBV treat it like FBV
            authorize_view = view_callable

        params = oauth_request.get_normalized_parameters()
        # set the oauth flag
        request.session['oauth'] = request_token.key
        response = authorize_view(request, request_token,
                                  request_token.get_callback_url(), params)

    return response
Пример #4
0
def user_authorization(request, form_class=AuthorizeRequestTokenForm):
    if request.method.lower() == 'get':
        if 'oauth_token' not in request.GET:
            return HttpResponseBadRequest('No request token specified.')
        incoming_token = request.GET['oauth_token']
    elif request.method.lower() == 'post':
        if 'oauth_token' not in request.POST:
            return HttpResponseBadRequest('No request token specified.')
        incoming_token = request.POST['oauth_token']

    oauth_request = get_oauth_request(request)

    try:
        request_token = store.get_request_token(request, oauth_request,
                                                incoming_token)
    except InvalidTokenError:
        return HttpResponse('Invalid request token: %s' % incoming_token,
                            status=401)

    consumer = store.get_consumer_for_request_token(request, oauth_request,
                                                    request_token)

    # LRS CHANGE - MAKE SURE LOGGED IN USER OWNS THIS CONSUMER
    # CLATOOLKIT CHANGE - MULTIPLE USERS CAN HAVE MULTIPLE CONSUMERS
    if not consumer.attached_to_user(request.user):
        return HttpResponseForbidden('Invalid user for this client.')

    if request.method == 'POST':
        form = form_class(request.POST)
        print 'request.session.oauth == request_token.key? %s' % (
            request.session.get('oauth', '') == request_token.key)

        print 'session: %s and request_token: %s' % (request.session.get(
            'oauth', ''), request_token.key)

        print 'form valid? %s' % form.is_valid()

        if not form.is_valid():
            print 'form errors: %s' % form.errors

        if request.session.get('oauth',
                               '') == request_token.key and form.is_valid():
            request.session['oauth'] = ''
            if form.cleaned_data['authorize_access']:
                request_token = store.authorize_request_token(
                    request, oauth_request, request_token)
                args = {
                    'oauth_token': request_token.key,
                    'user': request.GET.get('clau', None)
                }
            else:
                args = {'error': _('Access not granted by user.')}

            print 'callback url: %s' % (request_token.callback)

            #            print 'new callback url: %s' % (request_token.callback)
            if request_token.callback is not None and request_token.callback != OUT_OF_BAND:
                callback_url = request_token.get_callback_url(args)
                #cla-user = request.GET.get('clau', None)
                #print 'got CLA user: %s' % (cla-user)
                if UNSAFE_REDIRECTS:
                    response = UnsafeRedirect(
                        callback_url)  #+'?user=%s' % cla-user)
                else:
                    response = HttpResponseRedirect(
                        callback_url)  #+'?user=%s' % cla-user)
            else:
                print "We're in here..."
                # try to get custom callback view
                callback_view_str = getattr(
                    settings, OAUTH_CALLBACK_VIEW,
                    'oauth_provider.views.fake_callback_view')
                try:
                    view_callable = get_callable(callback_view_str)
                except AttributeError:
                    raise Exception("%s view doesn't exist." %
                                    callback_view_str)

            # try to treat it as Class Based View (CBV)
                try:
                    callback_view = view_callable.as_view()
                except AttributeError:
                    # if it appears not to be CBV treat it like FBV
                    callback_view = view_callable

                response = callback_view(request, **args)
        else:
            response = send_oauth_error(
                'https' if request.is_secure() else 'http',
                get_current_site(request).domain,
                oauth.Error(_('Action not allowed.')))
    else:
        # try to get custom authorize view
        authorize_view_str = getattr(
            settings, OAUTH_AUTHORIZE_VIEW,
            'oauth_provider.views.fake_authorize_view')
        try:
            view_callable = get_callable(authorize_view_str)
        except AttributeError:
            raise Exception("%s view doesn't exist." % authorize_view_str)

        # try to treat it as Class Based View (CBV)
        try:
            authorize_view = view_callable.as_view()
        except AttributeError:
            # if it appears not to be CBV treat it like FBV
            authorize_view = view_callable

        params = oauth_request.get_normalized_parameters()
        # set the oauth flag
        request.session['oauth'] = request_token.key
        response = authorize_view(request, request_token,
                                  request_token.get_callback_url(), params)

    return response
Пример #5
0
def lti_init(request, course_id=None, unit_id=None):
    """LTI init view

    Analyze LTI POST request to start LTI session.

    :param course_id: course id from launch url
    :param unit_id: unit id from lunch url
    """
    if settings.LTI_DEBUG:
        LOGGER.debug(request.META)
        LOGGER.debug(request.POST)
    session = request.session
    # Code from ims_lti_py_django example
    session.clear()

    short_term_lti = request.POST.get('custom_short_term')
    instance_guid = request.POST.get('tool_consumer_instance_guid')
    consumer_key = request.POST.get('oauth_consumer_key')

    if short_term_lti:
        lti_consumer = LtiConsumer.objects.filter(
            consumer_key=consumer_key).first()
    else:
        lti_consumer = LtiConsumer.get_or_combine(instance_guid, consumer_key)

    if not lti_consumer:
        LOGGER.error(
            'Consumer with key {} was not found.'.format(consumer_key))
        return render(request, 'lti/error.html',
                      {'message': 'LTI request is not valid'})

    try:
        if lti_consumer.expiration_date and lti_consumer.expiration_date < date.today(
        ):
            raise oauth2.Error('Consumer Key has expired.')
        if lti_consumer.consumer_key != consumer_key:
            raise oauth2.Error('Wrong Consumer Key: {}'.format(consumer_key))
        consumer_key = lti_consumer.consumer_key
        secret = lti_consumer.consumer_secret
        tool = DjangoToolProvider(consumer_key, secret, request.POST)
        is_valid = tool.is_valid_request(request)
        session['target'] = '_blank'
    except (oauth2.MissingSignature, oauth2.Error, KeyError,
            AttributeError) as err:
        is_valid = False
        session['message'] = "{}".format(err)
        LOGGER.error("Error during processing LTI request: {}".format(
            err.__str__()))

    session['is_valid'] = is_valid
    session['LTI_POST'] = {k: v for (k, v) in list(request.POST.items())}

    if settings.LTI_DEBUG:
        msg = 'session: is_valid = {}'.format(session.get('is_valid'))
        LOGGER.debug(msg)
        if session.get('message'):
            msg = 'session: message = {}'.format(session.get('message'))
            LOGGER.debug(msg)
    if not is_valid:
        return render(request, 'lti/error.html',
                      {'message': 'LTI request is not valid'})

    return lti_redirect(request, lti_consumer, course_id, unit_id)
Пример #6
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import

import oauth2 as oauth
from django.http import HttpResponseBadRequest
from django.utils.translation import ugettext as _

from oauth_provider.utils import send_oauth_error

INVALID_PARAMS_RESPONSE = send_oauth_error(oauth.Error(_('Invalid request parameters.')))
INVALID_CONSUMER_RESPONSE = HttpResponseBadRequest('Invalid Consumer.')
INVALID_SCOPE_RESPONSE = send_oauth_error(oauth.Error(_('You are not allowed to access this resource.')))
COULD_NOT_VERIFY_OAUTH_REQUEST_RESPONSE = send_oauth_error(oauth.Error(_('Could not verify OAuth request.')))