Django REST: make request.session['key'] available on all views - django

I'm trying to check if a user logged in saving a token in request.session["token"]. On login, the request.session["token"] is set and the print() works. How do I make that key available on all views?
#api_view(['POST'])
def login(request):
if request.data["usuario"] and request.data["pwd"]:
try:
user_item = User.objects.get(usuario=request.data["usuario"])
except User.DoesNotExist:
return Response({'errors': 'Usuario no existe'}, status=402)
usr_pwd = request.data["pwd"]
bd_pwd = user_item.pwd
if bcrypt.checkpw(usr_pwd.encode('utf-8'),bd_pwd.encode('utf-8')):
token = jwt.encode({'user': request.data["usuario"]}, 'palacin', algorithm='HS256')
request.session["token"] = token
print(request.session["token"]) # <-- THIS PRINT WORKS
return Response(200)
else:
return Response({'errors': 'Usuario y/o contraseña incorrectos.'}, status=401)
else:
return Response({'errors': 'Usuario y/o contraseña no especificados'}, status=400)
#api_view(['POST'])
def getUser(request):
print(request.session["token"]) # <-- THIS PRINT DOESN'T WORK
'''if "token" in request.session:
return Response(jwt.decode(request.session["token"], 'palacin', algorithms=['HS256']))
else:
return Response({'errors': 'Sesión no iniciada'}, status=403)'''

Related

Django custom login form validation with AJAX

I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to validate a user's email and password in my login form... right now almost 100% of things work, for example, alert messages for mandatory inputs; however, from the Utils.py file if user "elif not object_user.allow_private_access:" validation is not working and, most importantly, validation is not checking user's password (also commented out in Utils.py). The "post" part in Views.py might have to be updated.
I have included my custom Login form from Forms.py, Views.py (for Login page) and Utils.py (which does the validation and sends error messages to the front-end) and Urls.py. I did not add my AJAX because that is working well.
Forms.py
class UserLoginForm(forms.ModelForm):
helper = FormHelper()
helper.add_input(Submit('login_form_submit',
numeratio_static_textLanguage['global_input_alert_maxCharacters_32'],
css_class='global_component-button'))
class Meta:
model = CustomUser
fields = ['email', 'password']
widgets = { 'email': forms.EmailInput(attrs={
'maxlength': '256',
'style': 'text-transform: lowercase',
'id': 'input-email',
'class': 'global_component-input box'}
),
'password': forms.PasswordInput(attrs={
'type': 'password',
'maxlength': '128',
'id': 'input-password',
'class': 'global_component-input box'}
)
}
def __init__(self, *args, **kwargs):
super(UserLoginForm, self).__init__(*args, **kwargs)
self.helper.form_action = ''
self.helper.form_method = 'post'
self.helper.form_id = 'login_form'
self.helper.form_class = 'login_form'
Views.py
#csrf_exempt
#anonymous_required(redirect_url='page__home')
#require_http_methods(["GET", "POST"])
def view_userLogin(request, *args, **kwargs):
template_name = '../frontend/templates/frontend/templates.user/template.page_login.html'
form_class = UserLoginForm
if request.method == 'GET':
return render(request, template_name, { 'userLogin_form': form_class(),
'json_textGlobal': static_textGlobal,
'json_textLanguage': static_textLanguage})
elif request.method == 'POST':
bound_user_login_form = form_class(request.POST)
data_validation = validation_userLogin_form(bound_user_login_form)
print('Before validation', data_validation)
if data_validation['result']:
email = bound_user_login_form.cleaned_data['email'].lower()
password = bound_user_login_form.cleaned_data['password']
check_exists_email = get_user_model().objects.filter(email__iexact=email).count() > 0
if check_exists_email:
object_user = get_user_model().objects.get(email__iexact=email)
if object_user.allow_private_access:
print(object_user.allow_private_access)
email_to_authenticate = get_user_model().objects.filter(email__iexact=email)[0].email
user = authenticate(request, username=email_to_authenticate, password=password)
print(email_to_authenticate, user)
if user is not None:
user.save()
login(request, user)
data_validation['redirect'] = True
data_validation['redirect_url'] = reverse('page__home')
return HttpResponseRedirect(reverse('page__home'))
else:
object_user.save()
else:
data_validation['redirect'] = False
return render(request, template_name, { 'userLogin_form': form_class(),
'json_textGlobal': static_textGlobal,
'json_textLanguage': static_textLanguage})
else:
return HttpResponseRedirect(reverse('page__error_404'))
#require_http_methods(["POST"])
def validate_userLogin(request, *args, **kwargs):
response_user_login_validate = validate_field_userLogin(request.POST)
return HttpResponse(json.dumps(response_user_login_validate), content_type="application/json")
#require_http_methods(["POST"])
def validate_userLogin_email(request, *args, **kwargs):
entered_email = request.POST['email'].lower()
response_user_login_validate = {'check_exists_email': not NumeratioUser.objects.filter(email=entered_email).count() == 0}
return HttpResponse(json.dumps(response_user_login_validate), content_type="application/json")
#require_http_methods(["POST"])
def validate_userLogin_unique_token(request, *args, **kwargs):
entered_unique_token = request.POST['unique_token']
response_user_login_validate = {'unique_token_exists': not NumeratioUser.objects.filter(unique_token=entered_unique_token).count() == 0}
return HttpResponse(json.dumps(response_user_login_validate), content_type="application/json")
Utils.py
def validation_userLogin_form(bound_user_login_form):
if bound_user_login_form.is_valid():
return {'result': True}
else:
error_messages = {}
if bound_user_login_form.errors:
error_messages.update(bound_user_login_form.errors)
return {'result': False, 'error_messages': error_messages}
def validate_field_userLogin(post_request):
error_messages = []
response = {'is_valid_field': False}
if 'email' in post_request:
validate_login_email(post_request, error_messages)
elif 'password' in post_request:
validate_login_password(post_request, error_messages)
if len(error_messages) < 1:
response['is_valid_field'] = True
else:
response['error_messages'] = error_messages
return response
def validate_login_email(post_request, error_messages):
entered_email = post_request['email'].lower()
try:
object_user = get_user_model().objects.get(email__iexact=entered_email)
print(object_user)
if entered_email == '':
error_messages.append(numeratio_static_textLanguage['global_input_alert_mandatoryField'])
elif not object_user.allow_private_access:
error_messages.append(numeratio_static_textLanguage['global_input_alert_noAccess'])
except NumeratioUser.DoesNotExist:
if entered_email == '':
error_messages.append(numeratio_static_textLanguage['global_input_alert_mandatoryField'])
elif not is_valid_format_email(entered_email):
error_messages.append(numeratio_static_textLanguage['global_input_alert_emailIncorrect'])
elif len(entered_email) > 256:
error_messages.append(numeratio_static_textLanguage['global_input_alert_maxCharacters_256'])
def validate_login_password(post_request, error_messages):
entered_password = post_request['password']
if entered_password == '':
error_messages.append(numeratio_static_textLanguage['global_input_alert_mandatoryField'])
# elif entered_password != check_password:
# error_messages.append(numeratio_static_textLanguage['global_input_alert_passwordNotValid'])
elif len(entered_password) > 128:
error_messages.append(numeratio_static_textLanguage['global_input_alert_maxCharacters_128'])
Urls.py
urlpatterns = [
path('login/', views.view_userLogin, name='page__user_login'),
path('login/validate/', views.validate_userLogin, name='page__user_login_validate'),
path('login/validate_email/', views.validate_userLogin_email, name='page__user_login_validateEmail'),
path('login/validate_unique_token/', views.validate_userLogin_unique_token, name='page__user_login_validateUniqueToken'),
.......
]

Django how to check if user is in path

I made an unique url and I want to check if the acutal url contains the uid so I made a if statement which is always false in my case so what can I change that it works and checks if the path contains the uid.
views.py
#login_required(login_url='home:login')
def ChangeEmailView(request, token):
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
if request.path == str(token):
if request.method == 'POST':
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
if form.is_valid():
form.save()
return redirect('home:profilesettings')
else:
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
else:
print('site wasnt found')
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
return redirect('home:index')
context = {'form': form, 'token': token}
return render(request, 'home/email_settings.html', context)
Given that URL bound to ChangeEmailView was set by
path('settings/email/changeemail/<str:token>', views.ChangeEmailView , name="changeemail")
then if request.path == str(token) is always False because request.path includes full URL path (i.e. /settings/email/changeemail/) not just your token.
I think you want the following
#login_required(login_url='home:login')
def ChangeEmailView(request, token):
packet = get_object_or_404(TempUrl, user=request.user)
site_token = packet.uid
if token == str(site_token):
if request.method == 'POST':
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
if form.is_valid():
form.save()
return redirect('home:profilesettings')
else:
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
else:
print('site wasnt found')
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
return redirect('home:index')
context = {'form': form, 'token': token}
return render(request, 'home/email_settings.html', context)
Django will extract last entry of URL path and pass to your view as the token parameter, you can just use that to check if your uid is present.

Django authenticate always return None even if username and password are correct

I'm trying to do a web page using django. Where a user can register and login to the page. But When I try to login the authenticate function returns None even if the entered password and username are correct.
I'm using django version 2.1.2 and Python 3.5
I have tried adding
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
in settings.py
this is the function that I'm using for registration.
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.refresh_from_db()
username= request.POST.get('username')
user.password=form.cleaned_data.get('password1')
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.save()
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})
This is the function that i use for login
class getLogin(View):
def get(self, request):
if request.user.is_authenticated:
return render(request, "authentication/signin.html")
else:
return render(request,"authentication/signin.html")
def post(self, request):
user = request.POST.get('user')
password = request.POST.get('pass')
usernamelog = User.objects.get(username=user)
auth = authenticate(username=usernamelog, password=password)
print("auth",auth)
if auth:
request.session['user']=auth.id
request.session['grade']=auth.student.grade
print("re",request.session['user'])
print("ath",auth.username)
request.session['username']=auth.username
print("usr", request.session['username'])
request.session['super']=auth.is_superuser
print("ddd",auth.student.grade)
# request.session['auth'] = auth.is_superuser
if auth.is_superuser:
return render(request,"app/admin.html")
else:
student_id=request.session['user']
grade = request.session['grade']
ex = Exam.objects.filter(level=grade)
code = Code.objects.filter(student_id=student_id)
return render(request, "app/student.html", {'link': ex, 'code': code,'profile':student_id})
else:
messages.add_message(request, messages.ERROR, 'Username or password mismatch')
return redirect('login')
I'm not able to authenticate the user even the given username and password are correct
First of all, as Daniel Roseman pointed out, you are overwriting the correctly saved user object with unhashed password. If you want to save the Student model, the you should call user.student.save() instead of user.save().
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.student.save() # this will save the Student data
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})

How to Filter the authenticated user by the Staff Status in Django? I'm in Trouble

Here all My codes and I haven't set it yet, just a regular auth
class login(View):
template_name = "admin/page.html"
context = {}
def get(self, *args, **kwargs):
next = self.request.GET.get('next')
forms = adminForm()
if next :
self.context['next'] = next
self.context['forms'] = forms
return render(self.request, self.template_name, self.context)
def post(self, *args, **kwargs):
forms = adminForm(self.request.POST or None)
next = self.request.POST.get('next')
if forms.is_valid() :
user = authenticate(username=forms.cleaned_data.get('username'), password=forms.cleaned_data.get('password'))
login(self.request, user)# authenticate(username=forms.cleaned_data.get('username'), password=forms.cleaned_data.get('password')))
if next :
return redirect(next)
return redirect('/admin/users')
if not forms.is_valid() :
self.context['errors'] = 'Invalid Username or Password'
self.context['forms'] = forms
return render(request, self.template_name, self.context)

User registration will not save

I want to save the user registration in Django but it always return "Existing". How am I going to solve this? My code is as follows
class RegisterView(View):
template = "#"
context_data = ModelUser.objects.all()
def get(self, *args, **kwargs):
return render(self.request, self.template, {'context_data' : self.context_data})
def post(self, *args, **kwargs):
user = ModelUser()
if self.request.method == 'POST':
if self.request.POST.get('fname') and self.request.POST.get('lname') and self.request.POST.get('email') and self.request.POST.get('username') and self.request.POST.get('password'):
user.fname = self.request.POST.get('fname')
user.lname = self.request.POST.get('lname')
user.email = self.request.POST.get('email')
user.username = self.request.POST.get('username')
user.password = self.request.POST.get('password')
for account in self.context_data:
if self.request.POST.get('email') == user.email or self.request.POST.get('username') == user.username:
return HttpResponse('Existing')
if user.password != self.request.POST.get('repassword'):
return HttpResponse('password not match!')
else:
user.save()
return HttpResponse('Successfully created!')
else:
return HttpResponse('Invalid')
change the post method like this:
def post(self, *args, **kwargs):
try:
fname = self.request.POST['fname'
lname = self.request.POST['lname']
email = self.request.POST['email']
username = self.request.POST['username']
password = self.request.POST['password']
except KeyError as e:
print('Key Missing for {}'.format(str(e)))
return HttpResponse('Invalid Request')
if self.context_data.filter(username=usname).exists():
return HttpResponse('Existing')
if password != self.request.POST.get('repassword'):
return HttpResponse('password not match!')
else:
UserModel.objects.create_user(fname=fname, lname=lname, username=username, password=password)
# Or
# u = UserModel(fname=fname, lname=lname, username=username)
# u.set_password(password)
# u.save()
return HttpResponse('Successfully created!')