forms.py 7.92 KB
Newer Older
Valentin Samir's avatar
Valentin Samir committed
1 2 3 4 5 6 7 8 9
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
Valentin Samir's avatar
Valentin Samir committed
10
# (c) 2015-2016 Valentin Samir
Valentin Samir's avatar
Valentin Samir committed
11
"""forms for the app"""
12
from .default_settings import settings
Valentin Samir's avatar
Valentin Samir committed
13

Valentin Samir's avatar
Valentin Samir committed
14
from django import forms
Valentin Samir's avatar
Valentin Samir committed
15
from django.utils.translation import ugettext_lazy as _
Valentin Samir's avatar
Valentin Samir committed
16

Valentin Samir's avatar
Valentin Samir committed
17 18
import cas_server.utils as utils
import cas_server.models as models
Valentin Samir's avatar
Valentin Samir committed
19

Valentin Samir's avatar
style  
Valentin Samir committed
20

21
class WarnForm(forms.Form):
22 23 24 25 26 27 28
    """
        Bases: :class:`django.forms.Form`

        Form used on warn page before emiting a ticket
    """

    #: The service url for which the user want a ticket
29
    service = forms.CharField(widget=forms.HiddenInput(), required=False)
30
    #: Is the service asking the authentication renewal ?
31
    renew = forms.BooleanField(widget=forms.HiddenInput(), required=False)
32
    #: Url to redirect to if the authentication fail (user not authenticated or bad service)
33 34
    gateway = forms.CharField(widget=forms.HiddenInput(), required=False)
    method = forms.CharField(widget=forms.HiddenInput(), required=False)
35
    #: ``True`` if the user has been warned of the ticket emission
36
    warned = forms.BooleanField(widget=forms.HiddenInput(), required=False)
37
    #: A valid LoginTicket to prevent POST replay
38
    lt = forms.CharField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
PEP8  
Valentin Samir committed
39

Valentin Samir's avatar
style  
Valentin Samir committed
40

Valentin Samir's avatar
Valentin Samir committed
41
class FederateSelect(forms.Form):
Valentin Samir's avatar
Valentin Samir committed
42
    """
43 44 45 46
        Bases: :class:`django.forms.Form`

        Form used on the login page when ``settings.CAS_FEDERATE`` is ``True``
        allowing the user to choose an identity provider.
Valentin Samir's avatar
Valentin Samir committed
47
    """
48
    #: The providers the user can choose to be used as authentication backend
49
    provider = forms.ModelChoiceField(
50
        queryset=models.FederatedIendityProvider.objects.filter(display=True).order_by(
51 52 53 54 55
            "pos",
            "verbose_name",
            "suffix"
        ),
        to_field_name="suffix",
Valentin Samir's avatar
Valentin Samir committed
56 57
        label=_('Identity provider'),
    )
58
    #: The service url for which the user want a ticket
Valentin Samir's avatar
Valentin Samir committed
59 60
    service = forms.CharField(label=_('service'), widget=forms.HiddenInput(), required=False)
    method = forms.CharField(widget=forms.HiddenInput(), required=False)
61
    #: A checkbox to remember the user choices of :attr:`provider<FederateSelect.provider>`
Valentin Samir's avatar
Valentin Samir committed
62
    remember = forms.BooleanField(label=_('Remember the identity provider'), required=False)
63
    #: A checkbox to ask to be warn before emiting a ticket for another service
Valentin Samir's avatar
Valentin Samir committed
64
    warn = forms.BooleanField(label=_('warn'), required=False)
65
    #: Is the service asking the authentication renewal ?
66
    renew = forms.BooleanField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
Valentin Samir committed
67 68


Valentin Samir's avatar
Valentin Samir committed
69
class UserCredential(forms.Form):
70 71 72 73 74 75
    """
         Bases: :class:`django.forms.Form`

         Form used on the login page to retrive user credentials
     """
    #: The user username
Valentin Samir's avatar
Valentin Samir committed
76
    username = forms.CharField(label=_('login'))
77
    #: The service url for which the user want a ticket
78
    service = forms.CharField(label=_('service'), widget=forms.HiddenInput(), required=False)
79
    #: The user password
Valentin Samir's avatar
Valentin Samir committed
80
    password = forms.CharField(label=_('password'), widget=forms.PasswordInput)
81
    #: A valid LoginTicket to prevent POST replay
Valentin Samir's avatar
Valentin Samir committed
82
    lt = forms.CharField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
Valentin Samir committed
83
    method = forms.CharField(widget=forms.HiddenInput(), required=False)
84
    #: A checkbox to ask to be warn before emiting a ticket for another service
Valentin Samir's avatar
Valentin Samir committed
85
    warn = forms.BooleanField(label=_('warn'), required=False)
86
    #: Is the service asking the authentication renewal ?
87
    renew = forms.BooleanField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
Valentin Samir committed
88

Valentin Samir's avatar
Valentin Samir committed
89
    def __init__(self, *args, **kwargs):
Valentin Samir's avatar
Valentin Samir committed
90 91 92
        super(UserCredential, self).__init__(*args, **kwargs)

    def clean(self):
93 94 95 96 97 98 99 100
        """
            Validate that the submited :attr:`username` and :attr:`password` are valid

            :raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`
                are not valid.
            :return: The cleaned POST data
            :rtype: dict
        """
Valentin Samir's avatar
Valentin Samir committed
101
        cleaned_data = super(UserCredential, self).clean()
102
        auth = utils.import_attr(settings.CAS_AUTH_CLASS)(cleaned_data.get("username"))
Valentin Samir's avatar
Valentin Samir committed
103
        if auth.test_password(cleaned_data.get("password")):
Valentin Samir's avatar
Valentin Samir committed
104
            cleaned_data["username"] = auth.username
Valentin Samir's avatar
Valentin Samir committed
105
        else:
Valentin Samir's avatar
Valentin Samir committed
106
            raise forms.ValidationError(_(u"Bad user"))
Valentin Samir's avatar
Valentin Samir committed
107 108 109 110
        return cleaned_data


class FederateUserCredential(UserCredential):
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    """
        Bases: :class:`UserCredential`

        Form used on a auto submited page for linking the views
        :class:`FederateAuth<cas_server.views.FederateAuth>` and
        :class:`LoginView<cas_server.views.LoginView>`.

        On successful authentication on a provider, in the view
        :class:`FederateAuth<cas_server.views.FederateAuth>` a
        :class:`FederatedUser<cas_server.models.FederatedUser>` is created by
        :meth:`cas_server.federate.CASFederateValidateUser.verify_ticket` and the user is redirected
        to :class:`LoginView<cas_server.views.LoginView>`. This form is then automatically filled
        with infos matching the created :class:`FederatedUser<cas_server.models.FederatedUser>`
        using the ``ticket`` as one time password and submited using javascript. If javascript is
        not enabled, a connect button is displayed.

        This stub authentication form, allow to implement the federated mode with very few
        modificatons to the :class:`LoginView<cas_server.views.LoginView>` view.
    """
    #: the user username with the ``@`` component
Valentin Samir's avatar
Valentin Samir committed
131
    username = forms.CharField(widget=forms.HiddenInput())
132
    #: The service url for which the user want a ticket
Valentin Samir's avatar
Valentin Samir committed
133
    service = forms.CharField(widget=forms.HiddenInput(), required=False)
134
    #: The ``ticket`` used to authenticate the user against a provider
Valentin Samir's avatar
Valentin Samir committed
135
    password = forms.CharField(widget=forms.HiddenInput())
136
    #: alias of :attr:`password`
Valentin Samir's avatar
Valentin Samir committed
137
    ticket = forms.CharField(widget=forms.HiddenInput())
138
    #: A valid LoginTicket to prevent POST replay
Valentin Samir's avatar
Valentin Samir committed
139 140
    lt = forms.CharField(widget=forms.HiddenInput(), required=False)
    method = forms.CharField(widget=forms.HiddenInput(), required=False)
141
    #: Has the user asked to be warn before emiting a ticket for another service
Valentin Samir's avatar
Valentin Samir committed
142
    warn = forms.BooleanField(widget=forms.HiddenInput(), required=False)
143
    #: Is the service asking the authentication renewal ?
144
    renew = forms.BooleanField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
Valentin Samir committed
145 146

    def clean(self):
147 148 149 150 151 152 153 154 155
        """
            Validate that the submited :attr:`username` and :attr:`password` are valid using
            the :class:`CASFederateAuth<cas_server.auth.CASFederateAuth>` auth class.

            :raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`
                do not correspond to a :class:`FederatedUser<cas_server.models.FederatedUser>`.
            :return: The cleaned POST data
            :rtype: dict
        """
Valentin Samir's avatar
Valentin Samir committed
156 157
        cleaned_data = super(FederateUserCredential, self).clean()
        try:
158
            user = models.FederatedUser.get_from_federated_username(cleaned_data["username"])
Valentin Samir's avatar
Valentin Samir committed
159 160
            user.ticket = ""
            user.save()
161
        # should not happed as if the FederatedUser do not exists, super should
162 163 164 165 166
        # raise before a ValidationError("bad user")
        except models.FederatedUser.DoesNotExist:  # pragma: no cover (should not happend)
            raise forms.ValidationError(
                _(u"User not found in the temporary database, please try to reconnect")
            )
Valentin Samir's avatar
Valentin Samir committed
167
        return cleaned_data
Valentin Samir's avatar
Valentin Samir committed
168 169 170


class TicketForm(forms.ModelForm):
171 172 173 174 175
    """
        Bases: :class:`django.forms.ModelForm`

        Form for Tickets in the admin interface
    """
Valentin Samir's avatar
Valentin Samir committed
176 177 178
    class Meta:
        model = models.Ticket
        exclude = []
179
    service = forms.CharField(label=_('service'), widget=forms.TextInput)