Commits

Evgeniy Kirov committed c191bbb

Штука для авторизации через OpenAPI. Пока без документации. Проверял на виджете для авторизации http://vk.com/developers.php?oid=-1&p=Auth

Comments (0)

Files changed (2)

vk_iframe/backends.py

 from django.contrib.auth.models import User
 from vk_iframe.models import City, Country
 
+
 class VkontakteUserBackend(ModelBackend):
     """ Использовать вместе с vk.middleware.AuthenticationMiddleware """
 
             return
 
         defaults = {}
-        username = str(vk_form.cleaned_data['viewer_id'])
+        username = str(vk_form.vk_user_id())
         vk_profile = vk_form.profile_api_result()
         if vk_profile:
             defaults = dict(
-                first_name = vk_profile['first_name'],
-                last_name = vk_profile['last_name'],
+                first_name=vk_profile['first_name'],
+                last_name=vk_profile['last_name'],
             )
 
         user, created = User.objects.get_or_create(username=username, defaults=defaults)

vk_iframe/forms.py

     (0, u'пользователь не состоит в группе'),
 )
 
+
 class VkontakteIframeForm(forms.Form):
     LANGUAGE_CHOICES = [(i[0], i[1][0]) for i in LANGUAGES]
 
     language = forms.ChoiceField(LANGUAGE_CHOICES)
 
     # результат первого API-запроса, который выполняется при загрузке приложения
-    api_result = forms.CharField(required = False)
+    api_result = forms.CharField(required=False)
 
     # битовая маска настроек текущего пользователя в данном приложении
     # TODO: подробнее см. в описании метода getUserSettings
             raise forms.ValidationError(u'Неверный ключ авторизации: %s != %s' % (key, correct_key,))
         return self.cleaned_data['auth_key']
 
+    def vk_user_id(self):
+        return self.cleaned_data['viewer_id']
+
     def profile_api_result(self):
         # в настройках нужно указать "Первый запрос к API":
         # method=getProfiles&uids={viewer_id}&format=json&v=3.0&fields=uid,first_name,last_name,nickname,domain,sex,bdate,city,country,timezone,photo,photo_medium,photo_big,has_mobile,rate,contacts,education
         if check_for_language(lang_code):
             return lang_code
         return None
+
+
+class VkontakteOpenAPIForm(forms.Form):
+
+    # id залогиненного в контакте пользователя, аналог viewer_id из предыдущей формы
+    uid = forms.IntegerField()
+
+    # защитный хэш, аналог auth_key
+    hash = forms.CharField()
+
+    # имя и фамилия
+    first_name = forms.CharField()
+    last_name = forms.CharField()
+
+    def get_auth_key(self):
+        api_id = settings.VK_APP_ID
+        viewer_id = self.cleaned_data['uid']
+        api_secret = settings.VK_APP_SECRET
+        return md5(str(api_id) + str(viewer_id) + str(api_secret)).hexdigest()
+
+    def clean_hash(self):
+        correct_key = self.get_auth_key().lower()
+        key = self.cleaned_data['hash'].lower()
+        print key
+        print correct_key
+        if correct_key != key:
+            raise forms.ValidationError(u'Неверный ключ авторизации: %s != %s' % (key, correct_key,))
+        return self.cleaned_data['hash']
+
+    def vk_user_id(self):
+        return self.cleaned_data['uid']
+
+    def profile_api_result(self):
+        return {'first_name': self.cleaned_data['first_name'],
+                'last_name': self.cleaned_data['last_name']}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.