How to use django login_required decorator for custom authentication backend?

675 views
Skip to first unread message

reasm

unread,
Jun 7, 2020, 9:49:33 AM6/7/20
to Django users
Hi,

I have created an authentication backend that allows users to login using their username, password and institute id. Although the user can login but it doesn’t get access to the view with login_required decor. When I login to the site it redirects to this url: 'http://xxx.xx.xx.x:xxxx/accounts/login/?next=/accounts/rhome/'. How can I set authentication restriction (or login_requied decor) on specific view in this case? Any suggestions will be greatly appreciated. 
Here is what I tried. 

backends.py:
class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

def get_user(self, user_id):
   try:
      return User.objects.get(pk=user_id)
   except User.DoesNotExist:
      return None

def authenticate(self, username=None, password=None, institute_id=None):
User = get_user_model()
    try:
        userid = User.objects.get(username=username)
        profile = Profile.objects.get(
            Q(user_id=userid.id) & Q(institute_id=institute_id)
        )
        user = User.objects.get(id = profile.user_id)
        if user.check_password(password):
            return user
    except ObjectDoesNotExist:
        return None

reasm

unread,
Jun 7, 2020, 9:50:00 AM6/7/20
to Django users
Hi,

I have created an authentication backend that allows users to login using their username, password and institute id. Although the user can login but it doesn’t get access to the view with login_required decor. When I login to the site it redirects to this url: 'http://xxx.xx.xx.x:xxxx/accounts/login/?next=/accounts/rhome/'. How can I set authentication restriction (or login_requied decor) on specific view in this case? Any suggestions will be greatly appreciated.


Thanks in advance.

- Ruba


Here is what I tried. 


backends.py:

class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

def get_user(self, user_id):
   try:
      return User.objects.get(pk=user_id)
   except User.DoesNotExist:
      return None

def authenticate(self, username=None, password=None, institute_id=None): 
    User = get_user_model()
    try:
        userid = User.objects.get(username=username)
        profile = Profile.objects.get(
            Q(user_id=userid.id) & Q(institute_id=institute_id)
        )
        user = User.objects.get(id = profile.user_id)
        if user.check_password(password):
            return user
    except ObjectDoesNotExist:
        return None
View.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login as auth_login, logout, authenticate
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from .backends import AuthBackend


def user_login_view(request):
    if request.method == 'POST':
        institute_id = request.POST.get('institute_id')
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = AuthBackend.authenticate(request, username=username, password=password, institute_id=institute_id)
        if user:
            if user.is_active:
                auth_login(request, user, backend='fileupload_project.accounts.backends.AuthBackend')
                return redirect("accounts:rhome")

            else:
                return HttpResponse("Your account is disabled.")
        else:
            messages.error(request, 'Invalid login details supplied')
            return HttpResponseRedirect(reverse('accounts:login'))
    else:
        return render(request, 'accounts/login.html', {}) 

@login_required
def home(request):
    return render(request, 'accounts/index.html')
urls.py:
app_name = 'accounts'
urlpatterns = [
    url(r'^login/$', views.user_login_view, name='login'),
    url(r'^rhome/$', views.home, name='rhome'),]
settings.py:
LOGIN_URL  = '/accounts/login'
LOGIN_REDIRECT_URL = '/accounts/rhome/'
LOGOUT_REDIRECT_URL = '/accounts/logout/'

#Authentication backends
AUTHENTICATION_BACKENDS = (
        'accounts.backends.AuthBackend',
        'django.contrib.auth.backends.ModelBackend',)
login.html:
<form id="login_form" method="post" action="{% url 'accounts:login' %}">
            {% csrf_token %}
        <br><br>
        <div class="avatar">
            <img alt="Avatar" height="180" src="{% static 'accounts/images/avatar.jpg' %}" width="180">
        </div>
        <h2 class="text-center">User Login</h2>
        <div class="form-group">
            <input id="institute_id" type="text" class="form-control" name="institute_id" placeholder="Center ID" required="required">
        </div>
        <div class="form-group ">
            <input id="username" type="text" class="form-control" name="username" placeholder="Username" required="required">
        </div>
        <div class="form-group">
            <input id="password" type="password" class="form-control" name="password" placeholder="Password" required="required">
        </div>

        <div class="form-group">
            <button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
            {% if messages %}
                {% for message in messages %}
                    <p class="alert alert-warning" >{{ message }}</p>
                {% endfor %}
            {% endif %}
        </div>
        <div class="clearfix">
            <label class="pull-left checkbox-inline"><input type="checkbox"> Remember me</label>
            <a href="#" class="pull-right">Forgot Password?</a>
        </div>
      </form>
Reply all
Reply to author
Forward
0 new messages