Checking if admin is logged in - python

I am trying to check if current logged in user is admin then allow them to access admin page else return to homepage.
heres my view.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from teacher.models import users
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = password)
if user is not None:
login(request, user)
print (user)
messages.success(request, "You have successfully Logged In.")
return redirect('index')
else:
messages.error(request, "You have entered invalid credentials. Please try again")
return redirect('login')
else:
return render(request, 'main/login.html')
def admin(request):
user = users.objects.get(category = 'admin')
if user:
return render(request, 'main/admin.html')
elif Exception:
return render(request, 'main/home.html')
heres my models.py
class users(models.Model):
_id = models.AutoField
name = models.CharField(max_length = 100)
username = models.CharField(max_length = 100)
email = models.EmailField(max_length=254)
hpassword = models.CharField(max_length = 255)
category = models.CharField(max_length=50, default= "teacher")
I have tried using different method of query. But I end up getting error page as 'user matching query doesn't exist'. Also it doesn't check if user is logged in or not. Even if user is not logged in it returns to admin page.

did you search about decorators? have a look Check admin login on my django app
and for dashboard access check Django login Decorator you can redirect the user back to login pageif not logged in.
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
...
for 2nd 'user matching query doesn't exist'.
check if you have a database table. make sure have run migrations
and use Try Exception
try:
user = users.objects.get(category = 'admin')
if user:
return render(request, 'main/admin.html')
except Exception as e:
return render(request, 'main/home.html')

default User class in django have a boolean field called 'is_superuser' which define is user admin or not.

Related

How can i authenticate any user for login with an extra field (other then username/ email and password) in django

I am creating a user profile using django’s authentication system (from django.contrib.auth.models import User). Before this I am trying to extend the field of user using an extra field (i.e- userprofile= ceo/developer/marketinghead) in models.py. Here is my models.py file
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class extendeduser(models.Model):
userprofile_choice=(
('ceo', 'ceo'),
('developer', 'developer'),
('marketinghead', 'marketinghead'),
)
userprofile=models.CharField(choices= userprofile_choice, max_length=255, blank=False)
user=models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self) -> str:
return self.userprofile
now I am sucessfully registering the new user. Now I have created differrent html pages based on their profile. So at the time of login I take an extra input from user which is userprofile. And based on this I have created views.py for redirecting the user at correct place. Here is my views.py file :-
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
uf = request.POST['userprofile']
user = auth.authenticate(username=username, password=password)
user_profile = extendeduser.objects.filter(user = user)
# print(user_profile[0])
# print(uf)
# print(user.get_username)
# print(user.__dict__)
#print(user.get_userprofile)
if user is not None:
if uf==user_profile[0]:
if uf=='ceo':
auth.login(request, user)
messages.success(request, "You are logged-In")
return redirect('wtoday')
elif uf=='developer':
auth.login(request, user)
messages.success(request, "You are logged-In")
return redirect('swhome')
elif uf=='marketinghead':
auth.login(request, user)
messages.success(request, "You are logged-In")
return redirect('sswhome')
else:
messages.warning(request, 'Invalid Credentials!!')
return redirect('login')
else:
messages.warning(request, 'Invalid Credentials!')
return redirect('login')
else:
messages.warning(request, 'Invalid Credentials')
return redirect('login')
return render(request, 'accounts/login.html')
Everything is fine but this "if uf==user_profile[0]:" line of code is not working. basically it is checking that the "userprofile" field of any particular user which is store in database is same as at the time of login or not. I am saying this line of code is not working because when i comment that line and then without checking user profile from the databae i just redirecting them based on the data which he fiels at the time of login then it works. But I didn't want this.
Please help me out!!
You can't compare uf and userprofile[0], because uf is a string and userprofile[0] is an extendeduser object. Maybe if uf == str(userprofile[0]): is what you want.

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})

In Python/Django, when I click on a textfield box (like a login) it takes me to a certain page

So yeah, when I click on any form, it takes me back to a certain page, specifically my account login page. It was working before, and it actually works fine in IE, but not in Firefox or Chrome. Here's the code for the actual account/login.py file, but there are 100s of files in the program, so it would be impractical for me to list them all here.
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from account import models as amod
from . import templater
from django.contrib.auth import login, authenticate
def process_request(request):
form = User_Auth_Form()
if request.method == 'POST':
form = User_Auth_Form(request.POST)
if form.is_valid():
user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password'])
if user.is_staff == True:
login(request, user)
return HttpResponseRedirect('/manager/dashboard')
if user is not None:
login(request, user)
return HttpResponseRedirect("homepage/index")
return HttpResponseRedirect('/homepage/index')
tvars = {
'form': form,
}
return templater.render_to_response(request, 'login.html', tvars)
class User_Auth_Form(forms.Form):
username = forms.CharField()
password = forms.CharField()
def clean(self):
user = authenticate(username = self.cleaned_data['username'], password = self.cleaned_data['password'])
if user == None:
raise forms.ValidationError("Bad password or username")
return self.cleaned_data
Please post the/a template page, and perhaps the/a url(s) file.
P.S. A simplification of your request.method/POST code is:
REPLACE
form = User_Auth_Form()
if request.method == 'POST':
form = User_Auth_Form(request.POST)
if form.is_valid():
WITH
form = User_Auth_Form(request.POST or None)
if form.is_valid():

Django automatic login after user registration (1.4)

I have an issue where I am successfully registering users - however, I want users to be logged in on registration. Here is the code that represents my registration view. Any thoughts on why the user is not auto-logged in?
Notes:
The user is being registered correctly, they can log in after this
authenticate(**kwargs) is returning the correct user
In settings.py I have:
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
Thanks!
def register(request):
user_creation_form = UserCreationForm(request.POST or None)
if request.method == 'POST' and user_creation_form.is_valid():
u_name = user_creation_form.cleaned_data.get('username')
u_pass = user_creation_form.cleaned_data.get('password2')
user_creation_form.save()
print u_name # Prints correct username
print u_pass # Prints correct password
user = authenticate(username=u_name,
password=u_pass)
print 'User: ', user # Prints correct user
login(request, user) # Seems to do nothing
return HttpResponseRedirect('/book/') # User is not logged in on this page
c = RequestContext(request, {'form': user_creation_form})
return render_to_response('register.html', c)
Ah! I figured it out. In case anyone has this issue, import login from django.contrib.auth if you are calling it manually - I was importing the view. Commented out code represents the bad import for my situation.
# from django.contrib.auth.views import login
from django.contrib.auth import authenticate, logout, login
I do it this way:
u.backend = "django.contrib.auth.backends.ModelBackend"
login(request, u)
for class based views here was the code that worked for me (django 1.7)
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.views.generic import FormView
class SignUp(FormView):
template_name = 'signup.html'
form_class = UserCreationForm
success_url='/account'
def form_valid(self, form):
#save the new user first
form.save()
#get the username and password
username = self.request.POST['username']
password = self.request.POST['password1']
#authenticate user then login
user = authenticate(username=username, password=password)
login(self.request, user)
return super(SignUp, self).form_valid(form)

How to block user login with certain status in Django

I'm using Django 1.11 and views based on classes.
My user model is customized and it has a status field where it has "enabled, blocked and disabled". I'd like to know how I can only allow users to log in and the others are barred.
Thanks!
you can override default form,
forms.py
from django.contrib.auth.forms import AuthenticationForm
class AuthenticationFormWithChekUsersStatus(AuthenticationForm):
def confirm_login_allowed(self, user):
if not user.status == 'enabled':
raise forms.ValidationError(
("Your account has disabled."),
code='inactive',
)
the docs: AuthenticationForm
And in your urls, it can be like:
from forms import AuthenticationFormWithChekUsersStatus
url(
r'^login/$', auth_views.LoginView.as_view(
authentication_form=AuthenticationFormWithChekUsersStatus
)
)
more details: all-authentication-views
You can do the following to check if user status is enabled
from django.views.generic import View
class LoginView(View):
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.status == 'enabled': # checking if user is "enabled"
login(request, user)
return HttpResponseRedirect('/form')
else:
return HttpResponse("Disabled user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index.html")

Categories