PageRenderTime 36ms CodeModel.GetById 27ms app.highlight 8ms RepoModel.GetById 0ms app.codeStats 0ms

/crauth/forms.py

https://github.com/ron-panduwana/test_gae
Python | 131 lines | 129 code | 2 blank | 0 comment | 3 complexity | a8873d85f6f3b3ae5472e9ec4afd252e MD5 | raw file
  1import logging
  2import re
  3from google.appengine.api import memcache
  4from django import forms
  5from django.utils.translation import ugettext_lazy as _
  6from gdata.apps import service
  7from gdata.service import CaptchaRequired, BadAuthentication
  8from crauth.users import SetupRequiredError, _SERVICE_MEMCACHE_TOKEN_KEY
  9from crauth.models import AppsDomain
 10from crlib import forms as crforms
 11from crlib import regexps
 12
 13
 14class VerbatimWidget(forms.Widget):
 15    def render(self, name, value, attrs=None):
 16        return value or ''
 17
 18
 19class DomainNameForm(forms.Form):
 20    domain = forms.RegexField(
 21        required=True, regex=regexps.RE_DOMAIN, label='www.',
 22        error_messages={'invalid': regexps.ERROR_DOMAIN})
 23
 24
 25class ChooseDomainForm(forms.Form):
 26    def __init__(self, *args, **kwargs):
 27        choices = kwargs.pop('choices', set())
 28        super(ChooseDomainForm, self).__init__(*args, **kwargs)
 29        self.fields['domain'] = crforms.ChoiceWithOtherField(
 30            required=True, choices=choices,
 31            label=_('Please select Google apps domain you want to log in to:'))
 32
 33    def clean_domain(self):
 34        main, other = self.cleaned_data['domain']
 35        if main == 'other':
 36            if not regexps.RE_DOMAIN.match(other):
 37                raise forms.ValidationError(regexps.ERROR_DOMAIN)
 38            return other
 39        return main
 40
 41
 42class CaptchaForm(forms.Form):
 43    captcha_token = forms.CharField(required=False, widget=forms.HiddenInput)
 44    captcha_url = forms.CharField(required=False, widget=VerbatimWidget)
 45    captcha = forms.CharField(required=False)
 46
 47    def __init__(self, user=None, service=None, *args, **kwargs):
 48        self.user = user
 49        self.service = service
 50        super(CaptchaForm, self).__init__(*args, **kwargs)
 51
 52    def clean_captcha(self):
 53        captcha = self.cleaned_data['captcha']
 54        if self.cleaned_data['captcha_token'] and not captcha:
 55            raise forms.ValidationError(_('You have to type captcha'))
 56        return captcha
 57
 58    def clean(self):
 59        from gdata.client import CaptchaChallenge
 60        if self._errors:
 61            return self.cleaned_data
 62        try:
 63            self.user.client_login(
 64                self.service, self.cleaned_data['captcha_token'],
 65                self.cleaned_data['captcha'])
 66        except CaptchaChallenge, challenge:
 67            self.data = self.data.copy()
 68            self.data['captcha_token'] = challenge.captcha_token
 69            self.data['captcha_url'] = challenge.captcha_url
 70            self.data['captcha'] = ''
 71            raise forms.ValidationError(_('Please enter the CAPTCHA'))
 72        return self.cleaned_data
 73
 74
 75class DomainSetupForm(CaptchaForm):
 76    account = forms.RegexField(
 77        regex=regexps.RE_USERNAME, label=_('Administrator account'),
 78        error_messages={'invalid': regexps.ERROR_USERNAME})
 79    password = forms.CharField(
 80        label=_('Administrator password'),
 81        required=True, widget=forms.PasswordInput, min_length=6)
 82    domain = forms.CharField(widget=forms.HiddenInput, required=True)
 83    callback = forms.URLField(required=False, widget=forms.HiddenInput)
 84
 85    def clean(self):
 86        if self._errors:
 87            return self.cleaned_data
 88
 89        account = self.cleaned_data['account']
 90        domain = self.cleaned_data['domain']
 91        password = self.cleaned_data['password']
 92        email = '%s@%s' % (account, domain)
 93
 94        apps_domain = AppsDomain.get_by_key_name(domain)
 95        if not apps_domain:
 96            old_credentials = {}
 97            apps_domain = AppsDomain(
 98                key_name=domain,
 99                domain=domain)
100        else:
101            old_credentials = {
102                'email': apps_domain.admin_email,
103                'password': apps_domain.admin_password,
104            }
105
106        def restore_credentials():
107            if old_credentials:
108                apps_domain.admin_email = old_credentials['email']
109                apps_domain.admin_password = old_credentials['password']
110                apps_domain.put()
111
112        memcache.delete(_SERVICE_MEMCACHE_TOKEN_KEY % (
113            domain, self.service.service))
114        apps_domain.admin_email = email
115        apps_domain.admin_password = password
116        apps_domain.put()
117
118        try:
119            cleaned_data = super(DomainSetupForm, self).clean()
120            self.service.RetrieveUser(account)
121            return cleaned_data
122        except service.AppsForYourDomainException:
123            restore_credentials()
124            raise forms.ValidationError(
125                _('Make sure to provide credentials for administrator of your '
126                  'domain'))
127        except SetupRequiredError:
128            restore_credentials()
129            raise forms.ValidationError(
130                _('Please provide correct authentication credentials'))
131