<commit_before>import logging

from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.http import urlquote_plus
from django.utils.translation import ugettext as _
from django.views.generic import FormView
from django.views.generic import TemplateView
from django.views.generic import View

from mama_cas.forms import LoginForm
from mama_cas.forms import WarnForm
from mama_cas.mixins import CustomAttributesMixin
from mama_cas.mixins import LoginRequiredMixin
from mama_cas.mixins import LogoutUserMixin
from mama_cas.mixins import NeverCacheMixin
from mama_cas.mixins import ValidateTicketMixin
from mama_cas.models import ProxyTicket
from mama_cas.models import ServiceTicket
from mama_cas.utils import add_query_params
from mama_cas.utils import is_valid_service_url


logger = logging.getLogger(__name__)


class LoginView(NeverCacheMixin, LogoutUserMixin, FormView):
    """
    (2.1 and 2.2) Credential requestor and acceptor.

    This view operates as a credential requestor when a GET request
    is received, and a credential acceptor for POST requests.
    """
    template_name = 'mama_cas/login.html'
    form_class = LoginForm

    def get(self, request, *args, **kwargs):
        """
        (2.1) As a credential requestor, /login accepts three optional
        parameters:

        1. ``service``: the identifier of the application the client is
           accessing. We assume this identifier to be a URL.
        2. ``renew``: requires a client to present credentials
           regardless of any existing single sign-on session. If set,
           its value should be ``true``.
        3. ``gateway``: causes the client to not be prompted for
           credentials. If a single sign-on session already exists, the
           user will be logged in. Otherwise, the user is simply
           forwarded to the service, if specified. If set, its value
           should be ``true``.
        """
        service = request.GET.get('service')
        renew = request.GET.get('renew')
        gateway = request.GET.get('gateway')
        warned = request.GET.get('warned')

        if renew:
            logger.debug("Renew request received by credential requestor")
            self.logout_user(request)
            login_url = add_query_params(reverse('cas_login'),
                                         {'service': service})
            logger.debug("Redirecting to %s" % login_url)
            return redirect(login_url)
        elif gateway and service:
            logger.debug("Gateway request received by credential requestor")
            if request.user.is_authenticated():
                if self.warn_user() and not warned:
                    warn_url = add_query_params(reverse('cas_warn'),
                                                {'service': service,
                                                 'gateway': gateway})
                    return redirect(warn_url)

                st = ServiceTicket.objects.create_ticket(service=service,
                                                         user=request.user)
                service_url = add_query_params(service, {'ticket': st.ticket})
            else:
                service_url = service
            logger.debug("Redirecting to %s" % service_url)
            return redirect(service_url)
        elif request.user.is_authenticated():
            if service:
                logger.debug("Service ticket request received "
                             "by credential requestor")
                if self.warn_user() and not warned:
                    warn_url = add_query_params(reverse('cas_warn'),
                                                {'service': service})
                    return redirect(warn_url)

                st = ServiceTicket.objects.create_ticket(service=service,
                                                         user=request.user)
                service_url = add_query_params(service, {'ticket': st.ticket})
                logger.debug("Redirecting to %s" % service_url)
                return redirect(service_url)
            else:
                msg = _("You are logged in as %s") % request.user
                messages.success(request, msg)
        return super(LoginView, self).get(request, *args, **kwargs)

    def warn_user(self):
        """
        Returns ``True`` if the ``warn`` parameter is set in the
        current session. Otherwise, returns ``False``.
        """
        return self.request.session.get('warn', False)

    def form_valid(self, form):
        """
        (2.2) As a credential acceptor, /login requires two parameters:

        1. ``username``: the username provided by the client
        2. ``password``: the password provided by the client

        If authentication is successful, the single sign-on session is
        created. If a service is provided, a ``ServiceTicket`` is
        created and the client is redirected to the service URL with
        the ``ServiceTicket`` included. If no service is provided, the
        login page is redisplayed with a message indicating a
        successful login.

        If authentication fails, the login form is redisplayed with an
        error message describing the reason for failure.

        The credential acceptor accepts one optional parameter:
<commit_msg>Set the login form label_suffix to an empty string<commit_after>import logging

from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.http import urlquote_plus
from django.utils.translation import ugettext as _
from django.views.generic import FormView
from django.views.generic import TemplateView
from django.views.generic import View

from mama_cas.forms import LoginForm
from mama_cas.forms import WarnForm
from mama_cas.mixins import CustomAttributesMixin
from mama_cas.mixins import LoginRequiredMixin
from mama_cas.mixins import LogoutUserMixin
from mama_cas.mixins import NeverCacheMixin
from mama_cas.mixins import ValidateTicketMixin
from mama_cas.models import ProxyTicket
from mama_cas.models import ServiceTicket
from mama_cas.utils import add_query_params
from mama_cas.utils import is_valid_service_url


logger = logging.getLogger(__name__)


class LoginView(NeverCacheMixin, LogoutUserMixin, FormView):
    """
    (2.1 and 2.2) Credential requestor and acceptor.

    This view operates as a credential requestor when a GET request
    is received, and a credential acceptor for POST requests.
    """
    template_name = 'mama_cas/login.html'
    form_class = LoginForm

    def get(self, request, *args, **kwargs):
        """
        (2.1) As a credential requestor, /login accepts three optional
        parameters:

        1. ``service``: the identifier of the application the client is
           accessing. We assume this identifier to be a URL.
        2. ``renew``: requires a client to present credentials
           regardless of any existing single sign-on session. If set,
           its value should be ``true``.
        3. ``gateway``: causes the client to not be prompted for
           credentials. If a single sign-on session already exists, the
           user will be logged in. Otherwise, the user is simply
           forwarded to the service, if specified. If set, its value
           should be ``true``.
        """
        service = request.GET.get('service')
        renew = request.GET.get('renew')
        gateway = request.GET.get('gateway')
        warned = request.GET.get('warned')

        if renew:
            logger.debug("Renew request received by credential requestor")
            self.logout_user(request)
            login_url = add_query_params(reverse('cas_login'),
                                         {'service': service})
            logger.debug("Redirecting to %s" % login_url)
            return redirect(login_url)
        elif gateway and service:
            logger.debug("Gateway request received by credential requestor")
            if request.user.is_authenticated():
                if self.warn_user() and not warned:
                    warn_url = add_query_params(reverse('cas_warn'),
                                                {'service': service,
                                                 'gateway': gateway})
                    return redirect(warn_url)

                st = ServiceTicket.objects.create_ticket(service=service,
                                                         user=request.user)
                service_url = add_query_params(service, {'ticket': st.ticket})
            else:
                service_url = service
            logger.debug("Redirecting to %s" % service_url)
            return redirect(service_url)
        elif request.user.is_authenticated():
            if service:
                logger.debug("Service ticket request received "
                             "by credential requestor")
                if self.warn_user() and not warned:
                    warn_url = add_query_params(reverse('cas_warn'),
                                                {'service': service})
                    return redirect(warn_url)

                st = ServiceTicket.objects.create_ticket(service=service,
                                                         user=request.user)
                service_url = add_query_params(service, {'ticket': st.ticket})
                logger.debug("Redirecting to %s" % service_url)
                return redirect(service_url)
            else:
                msg = _("You are logged in as %s") % request.user
                messages.success(request, msg)
        return super(LoginView, self).get(request, *args, **kwargs)

    def warn_user(self):
        """
        Returns ``True`` if the ``warn`` parameter is set in the
        current session. Otherwise, returns ``False``.
        """
        return self.request.session.get('warn', False)

    def get_form_kwargs(self):
        """
        Set the form's label suffix to an empty string. Django 1.6
        defaults to a ':' suffix for a label_tag.
        """
        form_kwargs = super(LoginView, self).get_form_kwargs()
        form_kwargs['label_suffix'] = ''
        return form_kwargs

    def form_valid(self, form):
        """
        (2.2) As a credential acceptor, /login requires two parameters:

        1. ``username``: the username provided by the client
        2. ``password``: the password provided by the client

        If authentication is successful, the single sign-on session is
        created. If a service is provided, a ``ServiceTicket`` is
        created and the client is redirected to the service URL with
        the ``ServiceTicket`` included. If no service is provided, the
        login page is redisplayed with a message indicating a
        successful login.

        If authentication fails, the login form is redisplayed with an
        error message describing the reason for failure.

        The credential acceptor accepts one optional parameter:

{'fraction_non_alphanumeric': 0.07408717177968349, 'fraction_numerical': 0.0024754663601803555, 'mean_word_length': 2.161542761319173, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3466542', 'n_tokens_mistral': 2816, 'n_tokens_neox': 2717, 'n_words': 966}