Django rest framework keep user logged in - django

I have an APi that supports log-in functionality and whenever i switch page to index page, user is not logged in anymore at this point i have no idea what am i doing wrong tbh.
this is my views for logging in
#csrf_exempt
#api_view(["POST", "GET"])
#permission_classes((AllowAny,))
def login(request):
username = request.data.get("username")
password = request.data.get("password")
if username is None or password is None:
return Response({'error': 'Please provide both username and password'},
status=HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password)
if not user:
return Response({'error': 'Invalid Credentials'},
status=HTTP_404_NOT_FOUND)
request.session.save()
return Response({'Success': 'Logged in'},
status=HTTP_200_OK)
and this is a simple test view for index page, my session.items() is blank and request.user outputs AnonymousUser
def test_view(request):
print(request.session.items())
print(request.user)
return HttpResponse(request.COOKIES.keys())
and in my settings i have
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),

You have to login() your user after authenticate
user = authenticate(username=username, password=password)
if not user:
. . .
login(request, user)

Related

Django - authenticate always returns None

I'm trying to create a login form for my website, but I cannot log into any existing account.
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
try:
user = User.objects.get(username=username)
except:
messages.error(request, 'User does not exist')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, 'Invalid username/password')
context = {}
return render(request, 'base/login_register.html', context)
Even if I use the correct credentials, it will display:
User does not exist
Invalid username/password
I've also added this to my settings.py:
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
I've created those accounts manually from the Django admin account, not with a registration form, could this be the issue?
I found the problem. In the html login file, I was missing name="username" and name="password" in the corresponding inputs.

Django User Register, auto login & redirect

I collect two forms at signup - a register form and a user profile form.
The form submission works alright - I get to see the new user and their profile on the admin panel. The problem would be automatically logging them in and redirecting them to a specific page doesn't seem to work.
This is what my views.py file look like:
def registerView(request):
regForm = RegisterForm
proForm = UserProfileForm
if request.method == 'POST':
regForm = RegisterForm(request.POST)
proForm = UserProfileForm(request.POST)
if regForm.is_valid() and proForm.is_valid():
user = regForm.save(commit=True)
profile = proForm.save(commit=False)
profile.user = user
profile.save()
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return render (request, 'main/dashboard.html', {})
else:
return HttpResponse("There was a problem signing you up!")
regDic = {'regForm': regForm, 'proForm': proForm}
return render(request, 'person/register.html', context=regDic)
What would be the best way to automatically log in & redirect the registered user upon form submission?
Try using redirect instead of render.
from django.shortcuts import redirect
if user:
if user.is_active:
login(request, user)
return redirect('name of the url you want to redirect')
First use the cleaned_data from the valid form instead of getting the raw values and then instead of render the template redirect to some path after the successful login.
And also the authenticate function should have request as the first parameter.
username = regForm.cleaned_data.get('username')
password = regForm.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('some_path')

Django 2 Login Registration

I'm Prety new in Django. After a few google search, I find full CRUD and I know how to handle that. But in User registration, I fell some problem all over the online every one uses Form.py to handle registration form but I don't want to use Form.py I like to customize it.
but the problem is when I use auth for login then Django auth says it's a wrong password
I use
authenticate(email=email,password=password)
for login check
Is anyone please explain custom login registration without using Form.py with some example.
Here is my View.py Code
def loginCheck(request):
if request.method == 'POST':
username = request.POST.get('username'),
password = request.POST.get('password'),
user = authenticate(request, username=username, password=password)
if user is not None:
return HttpResponse('Find User')
else:
return HttpResponse("Not Find User")
and my User Registration Code
def registration(request):
checkData = AuthUser.objects.filter(email=request.POST.get('email'))
if not checkData:
User.objects.create_user(
username=request.POST.get('username'),
email=request.POST.get('email'),
password=(request.POST.get('password')),
)
messages.add_message(request, messages.INFO, 'User Saved Successfully')
return redirect('loginView')
else:
messages.add_message(request, messages.INFO, 'Email Already Exists')
return redirect('loginView')
My Login code return Not Find User.
Try this minimal example. In this, you can create User and log in through API.
import json
from django.views.generic import View
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.contrib.auth import authenticate, login
class UserRegisterView(View):
def get(self, request):
return JsonResponse({"message": "METHOD NOT ALLOWED"})
def post(self, request, *args, **kwargs):
json_body = json.loads(request.body)
username = json_body.get('username')
password = json_body.get('password')
email = json_body.get('email')
is_staff = json_body.get('is_staff', False)
is_superuser = json_body.get('is_superuser', False)
User.objects.create_user(
username=username, email=email,
password=password, is_staff=is_staff,
is_superuser=is_superuser
)
return JsonResponse({"message": "User created"})
class LoginView(View):
def get(self, request):
return JsonResponse({"message": "METHOD NOT ALLOWED"})
def post(self, request, *args, **kwargs):
'''
input data format:
{
"username" : "my username",
"password":"mysecret123#"
}
'''
json_body = json.loads(request.body)
username = json_body.get('username')
password = json_body.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return JsonResponse({"message": "login success"})
else:
return JsonResponse({"message": "login failed"})
Why I parsed request.body ?
How to receive json data using HTTP POST request in DJANGO
Reference:
How to authenticate user in DJANGO (official-doc)
UPDAYE-1
updated view as per the request,checking sufficent data in POST method (bold code)
def loginCheck(request):
if request.method == 'POST' and 'username' in request.POST and 'password' in request.POST:
username = request.POST.get('username'),
password = request.POST.get('password'),
user = authenticate(request, username=username, password=password)
if user is not None:
return HttpResponse('Find User')
else:
return HttpResponse("Not Find User")
return HttpResponse("POST data wrong")
If you want to your own registration process, you must use set_password function for saving password.
from django.contrib.auth.models import User
user = User.objects.get_or_create(username='john')
user.set_password('new password')
user.save()

Django authenticate user is not working

I am athenticating user and redirecting him to index page:
def sign_user(request):
username = request.POST['login']
password = request.POST['pwd']
user = authenticate(username=username, password=password)
if user is not None:
print('success:' + username + " " + password)
return redirect('/')
this is index view:
def index(request):
user = request.user
print(user)
And as a result here I get: AnonymousUser
What do I do?
You need to login the user, like the docs say.
if user is not None:
login(request, user)
Try this way,
from django.contrib.auth import authenticate, login
def sign_user(request):
username = request.POST['login']
password = request.POST['pwd']
try:
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/') # login success
except:
return redirect('unable to login')

login() is not working at all - Django

I have a django app and I am trying to integrate the login system that they have within the framework. I have the following line of code:
user = authenticate(username=username, password=password)
login(request, user)
I am running this method right after I create a new user after the user signs up and creates an account. I know the authentication is going to be successfull because I just created the account and I know it is there. I am gettting the following error
login() takes 1 positional argument but 2 were given
In the documentation is says you pass in a request and user... so why is it not working. this is driving me crazy....
Here is the documentation on djangos websites:
login(request, user, backend=None)[source]¶
To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework.
Note that any data set during the anonymous session is retained in the session after a user logs in.
This example shows how you might use both authenticate() and login():
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
Here is my full signup method:
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
username = cd['username']
password = cd['password']
verify = cd['verify']
email = cd['email']
if password == verify:
secure_password = make_password(password)
user = User.objects.create(
username = username,
password = secure_password,
email = email,
)
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
else:
return redirect('home')
else:
form = SignupForm()
parameters = {
'form':form,
}
return render(request, 'users/signup.html', parameters)
else:
form = SignupForm()
parameters = {
'form':form
}
return render(request, 'users/signup.html', parameters)
if you havent declared any function with the same name as login
then
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
you missed the request in the authenticate.
and if you have declared a function with the name login then change it to something else