简体   繁体   中英

Django - Authenticate against existing DB

Apologies if this is simple or my terminology is off, this is my first django project. I haven't been able to find a similar solution for this online.

I have an existing application, with a postgres DB where I authenticate my users. I have wrote an application in Django to interact with some tables and display info to the user. I would like to use Django to login and track User sessions against this DB. so I can use the features like

{% if user.is_authenticated %}

but I don't want to use the migrate command so I don't want to change the existing DB. I can access the table where the account info is as I created a model for it.

I see you can use remote user logon param but I cant find any sample or guide on how to use it and am completely lost.

Right now I create a login form in the views page. Then get the username and password that is entered, but I don't know what to do next. Also would need to hash the password. Is there a libray in djano that will do that for the app.

Any pointers or online guides for this would be appreciated.

Here is the views for login

if request.method == "POST":
    form = LoginForm(request.POST)
    if form.is_valid():
        email = form.data['account_email']
        password = form.data['account_password']

        user = authenticate(username=email)

        if user.check_password(password):
            login(request, user)
            return redirect('myapp:cust_select')
        else:
            # Username and password did not match
            raise ValidationError('Invalid Username/Password')

return render(request, 'myapp/login.html', {'form' : form}

backends.py

from django.conf import settings
from django.contrib.auth import get_user_model


class UserAuthBackend(object):    
    def authenticate(self, username=None, password=None):
        try:
            account = get_user_model()

            user = account.objects.get(account_email=username)
            if user:
                return user
        except account.DoesNotExist:
            print "account not found"
        return None 

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

models.py

class Accounts(AbstractUser):
    account_id = models.AutoField(primary_key=True)
    account_email = models.CharField(max_length=100)
    account_password = models.CharField(max_length=20)

    def __str__(self):
         return self.account_email 

    class Meta:
        managed = False
        db_table = 'accounts'

settings.py

 AUTHENTICATION_BACKENDS = ( 'myapp.backends.UserAuthBackend', )

Its keeps exiting with the same error in the sql query. column accounts.password does not exist LINE 1: SELECT "accounts"."password", "accounts"."last_login", "acco...

It doesnt appear to be using my Account model. It does select it from that table but how can i get it to stop requesting accounts.password and accounts.last_login as they dont exist in y Accounts model

For reference Note: You need to do try, catch to get this code working

def login(request):
    form = LoginForm()

    if request.method == "POST":
    form = LoginForm(request.POST)
        if form.is_valid():
            username = form.data['account_email']
            password = form.data['account_password']

            # First authenticate
            user = authenticate(request, username=username, password=password)

            if user is not None  :
                # Succeed, now log user in
                login(request,user)
                return redirect('myapp:select')
            else:
                # Username and password did not match
                raise ValidationError('Invalid Username/Password')

     return render(request, 'myapp/login.html', {'form' : form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM