Django HoneyPot Change Password Issue - python

I would appreciate if you could give me any clue! As I don't have experience in this, probably I've misunderstood smth.
I'm using honeypot, more specifically honeypot.middleware.HoneypotMiddleware with HONEYPOT_FIELD_NAME in my API (settings.py).
As for the moment it's enough, I'm using the basic implementation for login, password change, reset from django.contrib.auth. In login I did a small customization so I added it in the url (authentication_form=CustomAuthenticationForm).
So I don't konw what I'm missing because the login page works (it is also a form), but the password change, reset ones are returning 400 Bad Request. Honey Pot Error (honey_pot_fieldname). Request aborted.
django: 2.1.2
django-honeypot: 0.7.0
[Updating with code]
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
....
'honeypot',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'honeypot.middleware.HoneypotMiddleware',
]
HONEYPOT_FIELD_NAME = config('HONEYPOT_FIELD_NAME')
forms.py
from django.contrib.auth.forms import AuthenticationForm
class CustomAuthenticationForm(AuthenticationForm):
error_messages = {
'invalid_login': _(
"Please enter a correct %(username)s and password. Note that both "
"fields may be case-sensitive."
),
'inactive': _("This account is inactive."),
'suspended': _("Your account has been temporarily suspended. For more information,\
please contact us."),
}
def clean(self)
def confirm_login_allowed(self, user)
urls.py
from django.contrib.auth import views as auth_view
urlpatterns = [
....
# ---- BASIC USER AUTHENTICATION (DJANGO)
path('api/login/', auth_view.LoginView.as_view(authentication_form=CustomAuthenticationForm), name='login'),
path('api/logout/', auth_view.LogoutView.as_view(), name='logout'),
# ---- PASSWORD CHANGE, RESET
path('api/password_change/', auth_view.PasswordChangeView.as_view(), name='password_change'),
path('api/password_change_done/', auth_view.PasswordChangeDoneView.as_view(),
name='password_change_done'),
....
]
[Templates]
templates/resgistration/login.html
{% extends 'base.html' %}
{% load i18n widget_tweaks %}
{% block head %}
{% load bootstrap3 %}
{{ form.media }}
{% endblock %}
{% block content %}
<div class="col-sm-4 col-sm-offset-4" style="margin-top:20px;">
<h1 class="display-4 text-center" >User login</h1>
<legend></legend>
<form method="post">
{% csrf_token %}
{% bootstrap_form form layout='inline' %}
{% buttons %}
<button type="submit" class="btn btn-primary center-block" style="margin-top: 20px">Log in</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
templates/resgistration/password_change_form.html
{% extends 'base.html' %}
{% load i18n widget_tweaks %}
{% block head %}
{% load bootstrap3 %}
{{ form.media }}
{% endblock %}
{% block content %}
<div class="col-sm-4 col-sm-offset-4" style="margin-top:20px;">
<h1 class="display-4 text-center" >{{ title }}</h1>
<legend></legend>
<form method="post">
{% csrf_token %}
{% bootstrap_form form layout='inline' %}
{% buttons %}
<button type="submit" class="btn btn-primary center-block" style="margin-top: 20px">Change password</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
Thanks in advance!

[Updating with solution]
Finally I achieved it!
I only had to add at the top of the template change_password_form.html the line
{% load honeypot %}
and within the form including the tag:
{% render_honeypot_field "field_name" %}
For achieve this helped me this article
django-honeypot
Hope that will be helpful for others.

Related

Django 3.1.1 - changing password success but success page don't show

I config urls and add custom template (override registration/password_change_done.html and registration/password_change_form.html:) in my project but when I change password success the url have changed correctly (http://127.0.0.1:8000/accounts/password/change/done/ url) but success page didn't show, it still shows the change password form. My code as below:
configuration urls.py:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
urlpatterns = [
url('password/change/',
auth_views.PasswordChangeView.as_view(),
name='password_change'),
url('password/change/done/',
auth_views.PasswordChangeDoneView.as_view(),
name='password_change_done'),
url('password/reset/',
auth_views.PasswordResetView.as_view(),
name='password_reset'),
url('password/reset/done/',
auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done'),
url('password/reset/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
url('password/reset/complete/',
auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete'),
]
password_change_done.html:
{% extends "base.html" %}
{% block content %}
<div class='row'>
<div class="col-12 text-center py-5">
<h1 class='my-5 py-5'>Password successfully changed!</h1>
</div>
</div>
{% endblock %}
password_change_form.html:
{% extends "base.html" %}
{% block content %}
<div class='row'>
<div class='col-md-6 col-10 mx-auto'>
<h1>Change your Password</h1>
<form method='post' action=''>{% csrf_token %}
{{ form.as_p }}
<span style='margin-bottom: 12px;'></span>
<button type="submit" class='btn btn-block btn-info'>Save</button>
</form>
</div>
</div>
{% endblock %}

Problem with ERR_TOO_MANY_REDIRECTS django 2.1

I started to create login module in django. Login module is ok but I have problem with logout. When i click Logout - we see "error -ERR_TOO_MANY_REDIRECTS"
Probably something in this file is incorect: account/urls.py
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'account'
urlpatterns = [
path('', auth_views.LoginView.as_view(template_name='account/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'),
path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'),
path('dashboard/', views.dashboard, name='dashboard'),
base.html
<body>
<div id="header">
{% if request.user.is_authenticated %}
<ul class="menu">
<li {% if section == "dashboard" %} class="selected"{% endif %}>
Panel główny
</li>
<li {% if section == "images" %} class="selected"{% endif %}>
Obrazy
</li>
<li {% if section == "people" %} class="selected"{% endif %}>
Ludzie
</li>
</ul>
{% endif %}
<span class="user">
{% if request.user.is_authenticated %}
Witaj, {{ request.user.first_name }}
Wyloguj
{% else %}
Zaloguj
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
logout.html
{% extends "base.html" %}
{% block title %} Wylogowanie {% endblock %}
{% block content %}
<h1>Wylogowanie</h1>
<p>Zostales wylogowany. Mozesz
zalogowac sie ponownie</p>
{% endblock %}
settings.html
...
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_REDIRECT_URL = reverse_lazy('account:logout')
show error
You've set LOGOUT_REDIRECT_URL to point back to the LogoutView which will cause a redirect loop. The LOGOUT_REDIRECT_URL should point to a URL that the user will be redirected to after they've logged out using the LogoutView.
Setting LOGOUT_REDIRECT_URL will override any template that's been set. Since you've explicitly set a template for the LogoutView in your urls.py, you should remove LOGOUT_REDIRECT_URL from your settings which will allow the template to be rendered.

Django 1.10.2 error "NoReverseMatch at " ,"Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found." [duplicate]

This question already has answers here:
What is a NoReverseMatch error, and how do I fix it?
(6 answers)
Closed 6 years ago.
I am new to python & Django. I am getting one error and have absolutely no idea how to solve it.
Any help will be appreciated.
from django.shortcuts import render
# Create your views here.
#log/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
# this login required decorator is to not allow to any
# view without authenticating
#login_required(login_url="login/")
def home(request):
return render(request,"home.html")
The code in urls.py is,
from django.conf.urls import include,url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from log.forms import LoginForm
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('log.urls')),
url(r'^login/$', auth_views.login ,{'template_name': 'login.html','authentication_form': LoginForm}),
url(r'^logout/$', auth_views.logout, {'next_page': '/login'}),
]
The code in login.html is,
{% extends 'base.html' %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please Sign In</h3>
</div>
<div class="panel-body">
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<p class="bs-component">
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
</p>
<p class="bs-component">
<center>
<input class="btn btn-success btn-sm" type="submit" value="login" />
</center>
</p>
<input type="hidden" name="next" value="{{ next }}" />
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
{% if not user.is_authenticated %}
$("ul.nav.navbar-nav.navbar-right").css("display","none");
{% endif %}
</script>
{% endblock %}
Hope this much info will do....
Add a name to the login url pattern:
kwargs = {'template_name': 'login.html','authentication_form': LoginForm}
...
url(r'^login/$', auth_views.login, kwargs=kwargs, name='login'),
# ^^^^
and then use that name in your template:
<form method="post" action="{% url 'login' %}">

Production only: sometimes get 403 CSRF verification failed

I have a login form that logs the users into the admin site. It works fine in development, and mostly works fine in production, but sometimes it gives a 403 CSRF verification failed error. Note that this happens to users that were able to log in before, so I can't imagine it's an issue with their browser.
It looks like jenniwren had a similar issue in this comment. They never asked a question about it, and the other commenters had no clue why that would happen.
Here's what I have:
urls.py
urlpatterns += patterns('django.contrib.auth.views',
url(r'^logout$', 'logout', {'next_page': 'mysite_login'}, name='mysite_logout'),
url(r'^login$', 'login', name='mysite_login'),
url('^', include('django.contrib.auth.urls')),
)
main/registration/login.html
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
{% if form.errors and not form.non_field_errors %}
<p class="errornote">Please correct the error(s) below.</p>
{% endif %}
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
<p class="errornote">
{{ error }}
</p>
{% endfor %}
{% endif %}
<form action="{{ app_path }}" method="post" id="login-form">
{% csrf_token %}
<div class="form-row">
{% if form.errors %}
{ form.username.errors }}
{% endif %}
{{ form.username.label_tag }}
{{ form.username }}
</div>
<div class="form-row">
{% if form.errors %}
{{ form.password.errors }}
{% endif %}
{{ form.password.label_tag }}
{{ form.password }}
</div>
<input type="hidden" name="next" value="{{ next }}" />
<div class="submit-row">
<input type="submit" value="Log in" />
</div>
<div class="password-reset-link">
Forgot your password?
</div>
</form>
{% endblock content %}
settings.py
INSTALLED_APPS = (
'filebrowser',
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'psycopg2',
'main',
'mysite'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware'
)
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
CSRF_COOKIE_HTTPONLY = True
This problem might occur if:
A user opens the login page in two different tabs
A user logins in one tab.
A user tries to login again in a different tab (although he is already logged in).
If your CSRF_FAILURE_VIEW shows your site template, you might be able to let the users know they are already logged in, and do not need to refresh the page.
This is a message I got whed Debug=True:
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
I think this answer will help you, you can also use #csrf_exempt annotation
over your function(view) like this:
#csrf_exempt
def foo():
return 'bar'
django doc on this subject: https://docs.djangoproject.com/en/3.0/ref/csrf/
I was doing some proxying for the admin url and fixed my issue by editing my settings.py file and adding:
CSRF_TRUSTED_ORIGINS = [".subdomain.com"]
Using my organisation's gsuite subdomain. See the django docs for reference

How does Django 1.4 CSRF work?

I have that urls.py:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(
r'^login/$',
'django.contrib.auth.views.login',
{'template_name': 'loyalty/login.html'},
name='login'
),
url(
r'^logout/$',
'django.contrib.auth.views.logout',
{'next_page': '/', },
name='logout'),
)
and have template login.html*:
{% extends "loyalty/auth.html" %}
{% load i18n %}
{% block auth_form %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="" method="post" id="login-form">{% csrf_token %}
{% if form.username.errors %}{{ form.username.errors }}{% endif %}
{{ form.username }}
{% if form.password.errors %}{{ form.password.errors }}{% endif %}
{{ form.password }}
<input type="hidden" name="this_is_the_login_form" value="1" />
<input type="hidden" name="next" value="{{ next }}" />
<button type="submit" name="submit">{% trans 'Log in' %}</button>
</form>
{% endblock %}
and i have in settings.py:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
But this gives me this error:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF cookie not set.
In administrative interface, I have same problem.
What can I do to solve this problem?
You probably aren't passing the Request context from your view.
Example:
def show_form(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
return render_to_response("template_to_display.html", {'form':form}, context_instance = template.RequestContext(request))
Update: I would suggest rearranging your middleware. Try removing the localemiddleware or placing it at last. The django default is this
I solved this problem. Problem in browser. Tried an other browser and all works fine. Didn't understand why I had this problem, because I tried clean cache and cookies.

Categories