Answer the question
In order to leave comments, you need to log in
How to make custom authentication backend work in django?
I am writing a custom authorization backend. I wrote it myself and also wrote a custom madel user. The content of models.py of my app is:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.utils.encoding import python_2_unicode_compatible
import hashlib
from django.conf import settings
# Create your models here.
@python_2_unicode_compatible
class VK_User(AbstractBaseUser):
uid = models.IntegerField(primary_key=True, unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
photo_rec_url = models.CharField(max_length=200)
have_active_post = models.BooleanField(default=False)
last_point = models.CharField(max_length=100, default="")
USERNAME_FIELD = 'uid'
def __str__(self):
return "%s %s %d" % (self.first_name, self.last_name, self.uid)
class HashBackend(object):
def authenticate(self, first_name=None, last_name=None, photo_rec=None, uid=None, hash=None):
md5 = hashlib.md5()
md5.update(settings.VK_APP_ID + uid + settings.VK_API_SECRET)
if md5.digest() == hash:
try:
vk_user = VK_User.objects.get(uid=uid)
except VK_User.DoesNotExist:
vk_user = VK_User(uid=uid, first_name=first_name, last_name=last_name, photo_rec=photo_rec)
vk_user.save()
return vk_user
return None
def get_user(self, user_id):
try:
return VK_User.objects.get(pk=uid)
except VK_User.DoesNotExist:
return None
AUTH_USER_MODEL = 'posts.VK_User'
AUTHENTICATION_BACKENDS = ['posts.models.HashBackend',]
from django.shortcuts import render
from django.http import HttpResponse
from posts.models import VK_User, HashBackend
# Create your views here.
def index(request):
return render(request, 'posts/auth.html', {})
def registration(request):
vk_user = authenticate(request.GET.get('first_name'), request.GET.get('last_name'), request.GET.get('photo_rec'), request.GET.get('uid'), request.GET.get('hash'))
if vk_user is not None:
redirect("specify_point", foo='bar')
else:
return HttpResponse("fail")
def spicify_point(request):
if request.vk_user.is_authenticated():
return HttpResponse(request.vk_user.first_name + ", " + "specify your city.")
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question