forms.py 7.63 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
15
from django.forms import widgets
Valentin Samir's avatar
Valentin Samir committed
16
from django.utils.translation import ugettext_lazy as _
Valentin Samir's avatar
Valentin Samir committed
17

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

Valentin Samir's avatar
Valentin Samir committed
21

22
class BootsrapForm(forms.Form):
Valentin Samir's avatar
Valentin Samir committed
23 24 25 26 27
    """
        Bases: :class:`django.forms.Form`

        Form base class to use boostrap then rendering the form fields
    """
28 29
    def __init__(self, *args, **kwargs):
        super(BootsrapForm, self).__init__(*args, **kwargs)
30
        for field in self.fields.values():
31 32
            # Only tweak the field if it will be displayed
            if not isinstance(field.widget, widgets.HiddenInput):
33
                attrs = {}
34
                if isinstance(field.widget, (widgets.Input, widgets.Select, widgets.Textarea)):
35
                    attrs['class'] = "form-control"
36 37
                if isinstance(field.widget, (widgets.Input, widgets.Textarea)) and field.label:
                    attrs["placeholder"] = field.label
38 39 40 41 42
                if field.required:
                    attrs["required"] = "required"
                field.widget.attrs.update(attrs)


Valentin Samir's avatar
Valentin Samir committed
43
class BaseLogin(BootsrapForm):
44
    """
Valentin Samir's avatar
Valentin Samir committed
45
        Bases: :class:`BootsrapForm`
46

Valentin Samir's avatar
Valentin Samir committed
47
        Base form with all field possibly hidden on the login pages
48 49
    """
    #: The service url for which the user want a ticket
50
    service = forms.CharField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
Valentin Samir committed
51 52
    #: A valid LoginTicket to prevent POST replay
    lt = forms.CharField(widget=forms.HiddenInput(), required=False)
53
    #: Is the service asking the authentication renewal ?
54
    renew = forms.BooleanField(widget=forms.HiddenInput(), required=False)
55
    #: Url to redirect to if the authentication fail (user not authenticated or bad service)
56 57
    gateway = forms.CharField(widget=forms.HiddenInput(), required=False)
    method = forms.CharField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
Valentin Samir committed
58 59 60 61 62 63 64 65


class WarnForm(BaseLogin):
    """
        Bases: :class:`BaseLogin`

        Form used on warn page before emiting a ticket
    """
66
    #: ``True`` if the user has been warned of the ticket emission
67
    warned = forms.BooleanField(widget=forms.HiddenInput(), required=False)
Valentin Samir's avatar
Valentin Samir committed
68

Valentin Samir's avatar
Valentin Samir committed
69

Valentin Samir's avatar
Valentin Samir committed
70
class FederateSelect(BaseLogin):
Valentin Samir's avatar
Valentin Samir committed
71
    """
Valentin Samir's avatar
Valentin Samir committed
72
        Bases: :class:`BaseLogin`
73 74 75

        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
76
    """
77
    #: The providers the user can choose to be used as authentication backend
78
    provider = forms.ModelChoiceField(
79
        queryset=models.FederatedIendityProvider.objects.filter(display=True).order_by(
80 81 82 83 84
            "pos",
            "verbose_name",
            "suffix"
        ),
        to_field_name="suffix",
Valentin Samir's avatar
Valentin Samir committed
85 86
        label=_('Identity provider'),
    )
87
    #: A checkbox to ask to be warn before emiting a ticket for another service
88 89 90 91
    warn = forms.BooleanField(
        label=_('Warn me before logging me into other sites.'),
        required=False
    )
92 93
    #: A checkbox to remember the user choices of :attr:`provider<FederateSelect.provider>`
    remember = forms.BooleanField(label=_('Remember the identity provider'), required=False)
Valentin Samir's avatar
Valentin Samir committed
94 95


Valentin Samir's avatar
Valentin Samir committed
96
class UserCredential(BaseLogin):
97
    """
Valentin Samir's avatar
Valentin Samir committed
98
         Bases: :class:`BaseLogin`
99 100 101 102

         Form used on the login page to retrive user credentials
     """
    #: The user username
103
    username = forms.CharField(label=_('username'))
104
    #: The user password
Valentin Samir's avatar
Valentin Samir committed
105
    password = forms.CharField(label=_('password'), widget=forms.PasswordInput)
106
    #: A checkbox to ask to be warn before emiting a ticket for another service
107 108 109 110
    warn = forms.BooleanField(
        label=_('Warn me before logging me into other sites.'),
        required=False
    )
Valentin Samir's avatar
Valentin Samir committed
111 112

    def clean(self):
113 114 115 116 117 118 119 120
        """
            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
121
        cleaned_data = super(UserCredential, self).clean()
122
        auth = utils.import_attr(settings.CAS_AUTH_CLASS)(cleaned_data.get("username"))
Valentin Samir's avatar
Valentin Samir committed
123
        if auth.test_password(cleaned_data.get("password")):
124
            cleaned_data["username"] = auth.username
Valentin Samir's avatar
Valentin Samir committed
125
        else:
126 127 128
            raise forms.ValidationError(
                _(u"The credentials you provided cannot be determined to be authentic.")
            )
Valentin Samir's avatar
Valentin Samir committed
129 130 131 132
        return cleaned_data


class FederateUserCredential(UserCredential):
133
    """
134
        Bases: :class:`UserCredential`
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

        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.
    """
Valentin Samir's avatar
Valentin Samir committed
152 153 154 155 156 157 158

    def __init__(self, *args, **kwargs):
        super(FederateUserCredential, self).__init__(*args, **kwargs)
        # All fields are hidden and auto filled by the /login view logic
        for name, field in self.fields.items():
            field.widget = forms.HiddenInput()
            self[name].display = False
Valentin Samir's avatar
Valentin Samir committed
159 160

    def clean(self):
161 162 163 164 165 166 167 168 169
        """
            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
170 171
        cleaned_data = super(FederateUserCredential, self).clean()
        try:
172
            user = models.FederatedUser.get_from_federated_username(cleaned_data["username"])
Valentin Samir's avatar
Valentin Samir committed
173 174
            user.ticket = ""
            user.save()
175
        # should not happed as if the FederatedUser do not exists, super should
176 177 178 179 180
        # 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
181
        return cleaned_data
Valentin Samir's avatar
Valentin Samir committed
182 183 184


class TicketForm(forms.ModelForm):
185 186 187 188 189
    """
        Bases: :class:`django.forms.ModelForm`

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