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