<commit_before># Copyright (C) 2014 Universidad Politecnica de Madrid
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from django import http
from django.contrib import auth
from django.core import exceptions as django_exceptions
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.views.generic.edit import FormView

from openstack_auth import views as auth_views
from openstack_dashboard import fiware_api
from openstack_dashboard.dashboards.idm import utils as idm_utils
from openstack_dashboard.fiware_oauth2 import forms
# from openstack_auth import forms
from openstack_dashboard.fiware_auth import forms as fiware_auth_forms

from horizon import messages


LOG = logging.getLogger('idm_logger')

class AuthorizeView(FormView):
    """ Shows the user info about the application requesting authorization. If its the first
    time (the user has never authorized this application before)
    """
    template_name = 'oauth2/authorize.html'
    form_class = forms.AuthorizeForm
    application_credentials = {}
    success_url = reverse_lazy('horizon:user_home')
    oauth_data = {}

    def dispatch(self, request, *args, **kwargs):
        try:
            self.application = fiware_api.keystone.application_get(
                request,
                request.GET.get('client_id'),
                use_idm_account=True)
        except Exception:
            msg = ('Unable to retrieve application.')
            LOG.error(msg)
            messages.error(request, (msg))
            return redirect('horizon:user_home')

        # Load credentials from the request
        self.application_credentials = self.load_credentials(request)

        if request.user.is_authenticated():
            # continue
            return super(AuthorizeView, self).dispatch(request, *args, **kwargs)
        else:
            # redirect to the login page showing some info about the application
            self.application.avatar = idm_utils.get_avatar(
                self.application, 
                'img_medium', idm_utils.DEFAULT_APP_MEDIUM_AVATAR)
            context = {
                'next':(reverse('fiware_oauth2_authorize') + '?' 
                    + self.request.GET.urlencode()),
                'redirect_field_name': auth.REDIRECT_FIELD_NAME,
                'show_application_details':True,
                'application':self.application,
            }
            LOG.debug('OAUTH2: Login page with consumer details')
        
            
            return auth_views.login(request, 
                                extra_context=context,
                                form_class=fiware_auth_forms.LoginWithEmailForm, 
                                **kwargs)

    def load_credentials(self, request):
        # TODO(garcianavalon) check it's set to code
        credentials = {     
            'response_type':request.GET.get('response_type'),
            'application_id':request.GET.get('client_id'),
            'redirect_uri':request.GET.get('redirect_uri'),
            'state':request.GET.get('state'),
        }
        return credentials

    def _request_authorization(self, request, credentials):
        # forward the request to the keystone server to store the credentials
        try:
            self.oauth_data = \
                fiware_api.keystone.request_authorization_for_application(
                    request,
                    credentials.get('application_id'),
                    credentials.get('redirect_uri'),
                    response_type=credentials.get('response_type'),
                    state=credentials.get('state', None))
        except Exception as e:
            LOG.warning(('OAUTH2: exception when requesting '
                         'authorization %s'), e)
            # TODO(garcianavalon) finner exception handling
            self.oauth_data = {
                'error': e
            }   

    def _already_authorized(self, request, credentials):
        # check if the user already authorized the app for that redirect uri
        app_id = credentials.get('application_id', None)
        if not app_id:
            LOG.debug('OAUTH2: no application_id in credentials')
            return False<commit_msg>better handling of missing client_id in oauth parameters<commit_after># Copyright (C) 2014 Universidad Politecnica de Madrid
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from django import http
from django.contrib import auth
from django.core import exceptions as django_exceptions
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.views.generic.edit import FormView

from openstack_auth import views as auth_views
from openstack_dashboard import fiware_api
from openstack_dashboard.dashboards.idm import utils as idm_utils
from openstack_dashboard.fiware_oauth2 import forms
# from openstack_auth import forms
from openstack_dashboard.fiware_auth import forms as fiware_auth_forms

from horizon import messages


LOG = logging.getLogger('idm_logger')

class AuthorizeView(FormView):
    """ Shows the user info about the application requesting authorization. If its the first
    time (the user has never authorized this application before)
    """
    template_name = 'oauth2/authorize.html'
    form_class = forms.AuthorizeForm
    application_credentials = {}
    success_url = reverse_lazy('horizon:user_home')
    oauth_data = {}

    def dispatch(self, request, *args, **kwargs):
        # Load credentials from the request
        self.application_credentials = self.load_credentials(request)

        if not self.application_credentials['application_id']:

            # if no client_id was found, notify and progress no further
            messages.error(request, 'OUATH2 ERROR: client_id is missing in query_string')
            context = {
                'next':(reverse('fiware_oauth2_authorize') + '?' 
                    + self.request.GET.urlencode()),
                'redirect_field_name': auth.REDIRECT_FIELD_NAME,
            }
            return auth_views.login(
                request, 
                extra_context=context,
                form_class=fiware_auth_forms.LoginWithEmailForm, 
                **kwargs)
            
        # Get the application details
        try:
            self.application = fiware_api.keystone.application_get(
                request,
                self.application_credentials['application_id'],
                use_idm_account=True)

        except Exception:
            msg = ('Unable to retrieve application.')
            LOG.exception(msg)
            messages.error(request, (msg))
            return redirect('horizon:user_home')

        if request.user.is_authenticated():
            # continue
            return super(AuthorizeView, self).dispatch(request, *args, **kwargs)
        else:
            # redirect to the login page showing some info about the application
            self.application.avatar = idm_utils.get_avatar(
                self.application, 
                'img_medium', idm_utils.DEFAULT_APP_MEDIUM_AVATAR)
            context = {
                'next':(reverse('fiware_oauth2_authorize') + '?' 
                    + self.request.GET.urlencode()),
                'redirect_field_name': auth.REDIRECT_FIELD_NAME,
                'show_application_details':True,
                'application':self.application,
            }

            LOG.debug('OAUTH2: Login page with consumer details')

            return auth_views.login(
                request, 
                extra_context=context,
                form_class=fiware_auth_forms.LoginWithEmailForm, 
                **kwargs)

    def load_credentials(self, request):
        # TODO(garcianavalon) check it's set to code
        credentials = {     
            'response_type': request.GET.get('response_type'),
            'application_id': request.GET.get('client_id'),
            'redirect_uri': request.GET.get('redirect_uri'),
            'state': request.GET.get('state'),
        }
        return credentials

    def _request_authorization(self, request, credentials):
        # forward the request to the keystone server to store the credentials
        try:
            self.oauth_data = \
                fiware_api.keystone.request_authorization_for_application(
                    request,
                    credentials.get('application_id'),
                    credentials.get('redirect_uri'),
                    response_type=credentials.get('response_type'),
                    state=credentials.get('state', None))
        except Exception as e:
            LOG.warning(('OAUTH2: exception when requesting '
                         'authorization %s'), e)
            # TODO(garcianavalon) finner exception handling
            self.oauth_data = {
                'error': e
            }   

    def _already_authorized(self, request, credentials):
        # check if the user already authorized the app for that redirect uri
        app_id = credentials.get('application_id', None)
        if not app_id:
            LOG.debug('OAUTH2: no application_id in credentials')
            return False
{'fraction_non_alphanumeric': 0.07636083862281208, 'fraction_numerical': 0.0028851702250432777, 'mean_word_length': 2.422975641869651, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2754892', 'n_tokens_mistral': 2688, 'n_tokens_neox': 2605, 'n_words': 749}