| 1 |
from django.conf import settings |
| 2 |
from django.contrib import admin, messages |
| 3 |
from django.contrib.admin.options import IS_POPUP_VAR |
| 4 |
from django.contrib.admin.utils import unquote |
| 5 |
from django.contrib.auth import update_session_auth_hash |
| 6 |
from django.contrib.auth.forms import ( |
| 7 |
AdminPasswordChangeForm, |
| 8 |
AdminUserCreationForm, |
| 9 |
UserChangeForm, |
| 10 |
) |
| 11 |
from django.contrib.auth.models import Group, User |
| 12 |
from django.core.exceptions import PermissionDenied |
| 13 |
from django.db import router, transaction |
| 14 |
from django.http import Http404, HttpResponseRedirect |
| 15 |
from django.template.response import TemplateResponse |
| 16 |
from django.urls import path, reverse |
| 17 |
from django.utils.decorators import method_decorator |
| 18 |
from django.utils.html import escape |
| 19 |
from django.utils.translation import gettext |
| 20 |
from django.utils.translation import gettext_lazy as _ |
| 21 |
from django.views.decorators.csrf import csrf_protect |
| 22 |
from django.views.decorators.debug import sensitive_post_parameters |
| 23 |
|
| 24 |
csrf_protect_m = method_decorator(csrf_protect) |
| 25 |
sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) |
| 26 |
|
| 27 |
|
| 28 |
@admin.register(Group) |
| 29 |
class GroupAdmin(admin.ModelAdmin): |
| 30 |
search_fields = ("name",) |
| 31 |
ordering = ("name",) |
| 32 |
filter_horizontal = ("permissions",) |
| 33 |
|
| 34 |
def formfield_for_manytomany(self, db_field, request=None, **kwargs): |
| 35 |
if db_field.name == "permissions": |
| 36 |
qs = kwargs.get("queryset", db_field.remote_field.model.objects) |
| 37 |
# Avoid a major performance hit resolving permission names which |
| 38 |
# triggers a content_type load: |
| 39 |
kwargs["queryset"] = qs.select_related("content_type") |
| 40 |
return super().formfield_for_manytomany(db_field, request=request, **kwargs) |
| 41 |
|
| 42 |
|
| 43 |
@admin.register(User) |
| 44 |
class UserAdmin(admin.ModelAdmin): |
| 45 |
add_form_template = "admin/auth/user/add_form.html" |
| 46 |
change_user_password_template = None |
| 47 |
fieldsets = ( |
| 48 |
(None, {"fields": ("username", "password")}), |
| 49 |
(_("Personal info"), {"fields": ("first_name", "last_name", "email")}), |
| 50 |
( |
| 51 |
_("Permissions"), |
| 52 |
{ |
| 53 |
"fields": ( |
| 54 |
"is_active", |
| 55 |
"is_staff", |
| 56 |
"is_superuser", |
| 57 |
"groups", |
| 58 |
"user_permissions", |
| 59 |
), |
| 60 |
}, |
| 61 |
), |
| 62 |
(_("Important dates"), {"fields": ("last_login", "date_joined")}), |
| 63 |
) |
| 64 |
add_fieldsets = ( |
| 65 |
( |
| 66 |
None, |
| 67 |
{ |
| 68 |
"classes": ("wide",), |
| 69 |
"fields": ("username", "usable_password", "password1", "password2"), |
| 70 |
}, |
| 71 |
), |
| 72 |
) |
| 73 |
form = UserChangeForm |
| 74 |
add_form = AdminUserCreationForm |
| 75 |
change_password_form = AdminPasswordChangeForm |
| 76 |
list_display = ("username", "email", "first_name", "last_name", "is_staff") |
| 77 |
list_filter = ("is_staff", "is_superuser", "is_active", "groups") |
| 78 |
search_fields = ("username", "first_name", "last_name", "email") |
| 79 |
ordering = ("username",) |
| 80 |
filter_horizontal = ( |
| 81 |
"groups", |
| 82 |
"user_permissions", |
| 83 |
) |
| 84 |
|
| 85 |
def get_fieldsets(self, request, obj=None): |
| 86 |
if not obj: |
| 87 |
return self.add_fieldsets |
| 88 |
return super().get_fieldsets(request, obj) |
| 89 |
|
| 90 |
def get_form(self, request, obj=None, **kwargs): |
| 91 |
""" |
| 92 |
Use special form during user creation |
| 93 |
""" |
| 94 |
defaults = {} |
| 95 |
if obj is None: |
| 96 |
defaults["form"] = self.add_form |
| 97 |
defaults.update(kwargs) |
| 98 |
return super().get_form(request, obj, **defaults) |
| 99 |
|
| 100 |
def get_urls(self): |
| 101 |
return [ |
| 102 |
path( |
| 103 |
"<id>/password/", |
| 104 |
self.admin_site.admin_view(self.user_change_password), |
| 105 |
name="auth_user_password_change", |
| 106 |
), |
| 107 |
] + super().get_urls() |
| 108 |
|
| 109 |
# RemovedInDjango60Warning: when the deprecation ends, replace with: |
| 110 |
# def lookup_allowed(self, lookup, value, request): |
| 111 |
def lookup_allowed(self, lookup, value, request=None): |
| 112 |
# Don't allow lookups involving passwords. |
| 113 |
return not lookup.startswith("password") and super().lookup_allowed( |
| 114 |
lookup, value, request |
| 115 |
) |
| 116 |
|
| 117 |
@sensitive_post_parameters_m |
| 118 |
@csrf_protect_m |
| 119 |
def add_view(self, request, form_url="", extra_context=None): |
| 120 |
if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"): |
| 121 |
return self._add_view(request, form_url, extra_context) |
| 122 |
|
| 123 |
with transaction.atomic(using=router.db_for_write(self.model)): |
| 124 |
return self._add_view(request, form_url, extra_context) |
| 125 |
|
| 126 |
def _add_view(self, request, form_url="", extra_context=None): |
| 127 |
# It's an error for a user to have add permission but NOT change |
| 128 |
# permission for users. If we allowed such users to add users, they |
| 129 |
# could create superusers, which would mean they would essentially have |
| 130 |
# the permission to change users. To avoid the problem entirely, we |
| 131 |
# disallow users from adding users if they don't have change |
| 132 |
# permission. |
| 133 |
if not self.has_change_permission(request): |
| 134 |
if self.has_add_permission(request) and settings.DEBUG: |
| 135 |
# Raise Http404 in debug mode so that the user gets a helpful |
| 136 |
# error message. |
| 137 |
raise Http404( |
| 138 |
'Your user does not have the "Change user" permission. In ' |
| 139 |
"order to add users, Django requires that your user " |
| 140 |
'account have both the "Add user" and "Change user" ' |
| 141 |
"permissions set." |
| 142 |
) |
| 143 |
raise PermissionDenied |
| 144 |
if extra_context is None: |
| 145 |
extra_context = {} |
| 146 |
username_field = self.opts.get_field(self.model.USERNAME_FIELD) |
| 147 |
defaults = { |
| 148 |
"auto_populated_fields": (), |
| 149 |
"username_help_text": username_field.help_text, |
| 150 |
} |
| 151 |
extra_context.update(defaults) |
| 152 |
return super().add_view(request, form_url, extra_context) |
| 153 |
|
| 154 |
@sensitive_post_parameters_m |
| 155 |
def user_change_password(self, request, id, form_url=""): |
| 156 |
user = self.get_object(request, unquote(id)) |
| 157 |
if not self.has_change_permission(request, user): |
| 158 |
raise PermissionDenied |
| 159 |
if user is None: |
| 160 |
raise Http404( |
| 161 |
_("%(name)s object with primary key %(key)r does not exist.") |
| 162 |
% { |
| 163 |
"name": self.opts.verbose_name, |
| 164 |
"key": escape(id), |
| 165 |
} |
| 166 |
) |
| 167 |
if request.method == "POST": |
| 168 |
form = self.change_password_form(user, request.POST) |
| 169 |
if form.is_valid(): |
| 170 |
# If disabling password-based authentication was requested |
| 171 |
# (via the form field `usable_password`), the submit action |
| 172 |
# must be "unset-password". This check is most relevant when |
| 173 |
# the admin user has two submit buttons available (for example |
| 174 |
# when Javascript is disabled). |
| 175 |
valid_submission = ( |
| 176 |
form.cleaned_data["set_usable_password"] |
| 177 |
or "unset-password" in request.POST |
| 178 |
) |
| 179 |
if not valid_submission: |
| 180 |
msg = gettext("Conflicting form data submitted. Please try again.") |
| 181 |
messages.error(request, msg) |
| 182 |
return HttpResponseRedirect(request.get_full_path()) |
| 183 |
|
| 184 |
user = form.save() |
| 185 |
change_message = self.construct_change_message(request, form, None) |
| 186 |
self.log_change(request, user, change_message) |
| 187 |
if user.has_usable_password(): |
| 188 |
msg = gettext("Password changed successfully.") |
| 189 |
else: |
| 190 |
msg = gettext("Password-based authentication was disabled.") |
| 191 |
messages.success(request, msg) |
| 192 |
update_session_auth_hash(request, form.user) |
| 193 |
return HttpResponseRedirect( |
| 194 |
reverse( |
| 195 |
"%s:%s_%s_change" |
| 196 |
% ( |
| 197 |
self.admin_site.name, |
| 198 |
user._meta.app_label, |
| 199 |
user._meta.model_name, |
| 200 |
), |
| 201 |
args=(user.pk,), |
| 202 |
) |
| 203 |
) |
| 204 |
else: |
| 205 |
form = self.change_password_form(user) |
| 206 |
|
| 207 |
fieldsets = [(None, {"fields": list(form.base_fields)})] |
| 208 |
admin_form = admin.helpers.AdminForm(form, fieldsets, {}) |
| 209 |
|
| 210 |
if user.has_usable_password(): |
| 211 |
title = _("Change password: %s") |
| 212 |
else: |
| 213 |
title = _("Set password: %s") |
| 214 |
context = { |
| 215 |
"title": title % escape(user.get_username()), |
| 216 |
"adminForm": admin_form, |
| 217 |
"form_url": form_url, |
| 218 |
"form": form, |
| 219 |
"is_popup": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), |
| 220 |
"is_popup_var": IS_POPUP_VAR, |
| 221 |
"add": True, |
| 222 |
"change": False, |
| 223 |
"has_delete_permission": False, |
| 224 |
"has_change_permission": True, |
| 225 |
"has_absolute_url": False, |
| 226 |
"opts": self.opts, |
| 227 |
"original": user, |
| 228 |
"save_as": False, |
| 229 |
"show_save": True, |
| 230 |
**self.admin_site.each_context(request), |
| 231 |
} |
| 232 |
|
| 233 |
request.current_app = self.admin_site.name |
| 234 |
|
| 235 |
return TemplateResponse( |
| 236 |
request, |
| 237 |
self.change_user_password_template |
| 238 |
or "admin/auth/user/change_password.html", |
| 239 |
context, |
| 240 |
) |
| 241 |
|
| 242 |
def response_add(self, request, obj, post_url_continue=None): |
| 243 |
""" |
| 244 |
Determine the HttpResponse for the add_view stage. It mostly defers to |
| 245 |
its superclass implementation but is customized because the User model |
| 246 |
has a slightly different workflow. |
| 247 |
""" |
| 248 |
# We should allow further modification of the user just added i.e. the |
| 249 |
# 'Save' button should behave like the 'Save and continue editing' |
| 250 |
# button except in two scenarios: |
| 251 |
# * The user has pressed the 'Save and add another' button |
| 252 |
# * We are adding a user in a popup |
| 253 |
if "_addanother" not in request.POST and IS_POPUP_VAR not in request.POST: |
| 254 |
request.POST = request.POST.copy() |
| 255 |
request.POST["_continue"] = 1 |
| 256 |
return super().response_add(request, obj, post_url_continue) |