PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/apps/openidconsumer/forms.py

https://bitbucket.org/resplin/byteflow
Python | 113 lines | 106 code | 7 blank | 0 comment | 6 complexity | af83caf4907c1e3200db2992ff147bad MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import re
  2. from django import forms
  3. from django.utils.translation import ugettext_lazy as _
  4. from django.conf import settings
  5. from django.contrib.auth.models import User
  6. from django.contrib.auth import authenticate
  7. from openid.yadis import xri
  8. from accounts.models import ActionRecord
  9. from openidconsumer.models import UserAssociation
  10. class OpenidSigninForm(forms.Form):
  11. openid_url = forms.CharField(max_length=255, widget=forms.widgets.TextInput(attrs={'class': 'required openid'}))
  12. next = forms.CharField(max_length=255,widget=forms.HiddenInput(), required=False)
  13. def clean_openid_url(self):
  14. if 'openid_url' in self.cleaned_data:
  15. openid_url = self.cleaned_data['openid_url']
  16. if xri.identifierScheme(openid_url) == 'XRI' and getattr(
  17. settings, 'OPENID_DISALLOW_INAMES', False
  18. ):
  19. raise forms.ValidationError(_('i-names are not supported'))
  20. return self.cleaned_data['openid_url']
  21. def clean_next(self):
  22. if 'next' in self.cleaned_data and self.cleaned_data['next'] != "":
  23. next_url_re = re.compile('^/[-\w/]+$')
  24. if not next_url_re.match(self.cleaned_data['next']):
  25. raise forms.ValidationError(_('next url "%s" is invalid' % self.cleaned_data['next']))
  26. return self.cleaned_data['next']
  27. attrs_dict = { 'class': 'required' }
  28. class OpenidRegistrationForm(forms.Form):
  29. name = User._meta.get_field('first_name').formfield(required=False)
  30. email = User._meta.get_field('email').formfield(required=False)
  31. def __init__(self, openid, *args, **kwargs):
  32. super(OpenidRegistrationForm, self).__init__(*args, **kwargs)
  33. self.openid = openid
  34. def clean_email(self):
  35. """For security reason one unique email in database"""
  36. if self.cleaned_data.get('email'):
  37. try:
  38. user = User.objects.get(email__exact=self.cleaned_data['email'])
  39. except User.DoesNotExist:
  40. return self.cleaned_data['email']
  41. else:
  42. raise forms.ValidationError(_(u"This email is already in database. Please choose another."))
  43. else:
  44. return ''
  45. def save(self):
  46. tmp_pwd = User.objects.make_random_password()
  47. user = ActionRecord.registrations.create_user(
  48. self.cleaned_data['name'],
  49. self.cleaned_data['email'],
  50. tmp_pwd,
  51. send_email=False,
  52. openid=self.openid)
  53. # make association with openid
  54. ua = UserAssociation.objects.create(openid_url=self.openid, user=user)
  55. return user
  56. class OpenidVerifyForm(forms.Form):
  57. email = User._meta.get_field('email').formfield(required=True)
  58. password = forms.CharField(max_length=128, widget=forms.widgets.PasswordInput(attrs=attrs_dict))
  59. def clean_email(self):
  60. try:
  61. user = User.objects.get(email=self.cleaned_data['email'])
  62. except User.DoesNotExist:
  63. raise forms.ValidationError(_(u"This email doesn't exist. Please choose another."))
  64. return self.cleaned_data['email']
  65. def clean_password(self):
  66. if 'email' in self.cleaned_data and 'password' in self.cleaned_data:
  67. self.user = authenticate(email=self.cleaned_data['email'], password=self.cleaned_data['password'])
  68. if self.user is None:
  69. raise forms.ValidationError(_(u"Please enter a correct email and password. Note that both fields are case-sensitive."))
  70. elif self.user.is_active == False:
  71. raise forms.ValidationError(_(u"This account is inactive."))
  72. return self.cleaned_data['password']
  73. def get_user(self):
  74. return self.user
  75. class OpenidAssociateForm(forms.Form):
  76. openid = UserAssociation._meta.get_field('openid_url').formfield(required=True)
  77. def __init__(self, user, *args, **kwargs):
  78. super(OpenidAssociateForm, self).__init__(*args, **kwargs)
  79. self.user = user
  80. def clean_openid(self):
  81. try:
  82. UserAssociation.objects.get(openid_url=self.cleaned_data['openid'])
  83. except UserAssociation.DoesNotExist:
  84. return self.cleaned_data['openid']
  85. else:
  86. raise forms.ValidationError('OpenID is already associated with some user.')
  87. def save(self):
  88. ua = UserAssociation.objects.create(openid_url=self.cleaned_data['openid'], user=self.user)
  89. return ua