0

I'm trying to authenticate a user with a username and face_image. I can't figure out where is the problem. I have read this article Authentication without a passwrod Django to solve my problem. Can anyone give me a hint or advice? Thank you

authenticate.py

from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend      
import face_recognition
from django.db.models import Q
from django_two_factor_face_auth.models import UserFaceImage

    class FaceIdAuthBackend(ModelBackend):
      def authenticate(self, username=None, face_id=None, **kwargs):
            try:
                user_T = User.objects.get(Q(username=username))
                if self.check_face_id(face_id=user_T.userfaceimage.image, uploaded_face_id=face_id):
                    return user_T
            except User.DoesNotExist:
                return None

 def check_face_id(self, face_id=None, uploaded_face_id=None):
        confirmed_image = face_recognition.load_image_file(face_id)
        uploaded_image = face_recognition.load_image_file(uploaded_face_id)

        face_locations = face_recognition.face_locations(uploaded_image)
        if len(face_locations) == 0:
            return False

        confirmed_encoding = face_recognition.face_encodings(confirmed_image)[0]
        unknown_encoding = face_recognition.face_encodings(uploaded_image)[0]

        results = face_recognition.compare_faces([confirmed_encoding], unknown_encoding)

        if results[0] == True:
            return True

        return False

view.py

def face_login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            face_image = prepare_image(form.cleaned_data['image'])

            face_ide = FaceIdAuthBackend()
            user = face_ide.authenticate(request,username=username,face_id=face_image)
            if user is not None:
                login(request, user)
                return redirect(settings.LOGIN_REDIRECT_URL)
            else:
                form.add_error(None, "Username, password or face id didn't match.")
    else:
        form = AuthenticationForm()

    context = {'form': form}
    return render(request, 'django_two_factor_face_auth/login.html', context)

model.py

class UserFaceImage(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=content_file_name, blank=False)
Gfgv Jjb
  • 1
  • 1
  • Do you have method get_user? Documaentations say it is required: `An authentication backend is a class that implements two required methods: get_user(user_id) and authenticate(request, **credentials)...` – igor Smirnov Feb 08 '22 at 13:18

0 Answers0