Commit dc0168e00d898e340021fe873876b73f69c70664

Authored by Sergio Oliveira
1 parent 904e05d4

Validating facebook and twitter accounts.

closes #28
src/accounts/forms.py
... ... @@ -5,11 +5,24 @@ from django.contrib.auth import get_user_model
5 5 from django.utils.translation import ugettext_lazy as _
6 6  
7 7 from super_archives.models import MailingList
8   -
  8 +from .utils.validators import validate_social_account
9 9  
10 10 User = get_user_model()
11 11  
12 12  
  13 +class SocialAccountField(forms.Field):
  14 + def __init__(self, *args, **kwargs):
  15 + self.url = kwargs.pop('url', None)
  16 + super(SocialAccountField, self).__init__(*args, **kwargs)
  17 +
  18 + def validate(self, value):
  19 + super(SocialAccountField, self).validate(value)
  20 +
  21 + if value and not validate_social_account(value, self.url):
  22 + raise forms.ValidationError(_('Social account does not exist'),
  23 + code='social-account-doesnot-exist')
  24 +
  25 +
13 26 class UserForm(forms.ModelForm):
14 27 required = ('first_name', 'last_name', 'email', 'username')
15 28  
... ... @@ -34,12 +47,16 @@ class UserCreationForm(UserForm):
34 47  
35 48  
36 49 class UserUpdateForm(UserForm):
  50 +
37 51 class Meta:
38 52 model = User
39 53 fields = ('username', 'first_name', 'last_name',
40 54 'institution', 'role', 'twitter', 'facebook',
41 55 'google_talk', 'webpage')
42 56  
  57 + twitter = SocialAccountField(url='https://twitter.com/', required=False)
  58 + facebook = SocialAccountField(url='https://graph.facebook.com/', required=False)
  59 +
43 60  
44 61 class ListsForm(forms.Form):
45 62 LISTS_NAMES = ((list.name, list.name) for list in MailingList.objects.all())
... ...
src/accounts/utils/__init__.py 0 → 100644
src/accounts/utils/validators.py 0 → 100644
... ... @@ -0,0 +1,26 @@
  1 +
  2 +import urllib2
  3 +import urlparse
  4 +
  5 +
  6 +def validate_social_account(account, url):
  7 + """Verifies if a social account is valid.
  8 +
  9 + Examples:
  10 +
  11 + >>> validate_social_account('seocam', 'http://twitter.com')
  12 + True
  13 +
  14 + >>> validate_social_account('seocam-fake-should-fail', 'http://twitter.com')
  15 + False
  16 + """
  17 +
  18 + request = urllib2.Request(urlparse.urljoin(url, account))
  19 + request.get_method = lambda: 'HEAD'
  20 +
  21 + try:
  22 + response = urllib2.urlopen(request)
  23 + except urllib2.HTTPError:
  24 + return False
  25 +
  26 + return response.code == 200
... ...