What i want is to limit access to the django admin login page to only the superuser. Meaning if you are not the superuser, and try to access http://127.0.0.1:8000/admin
- you should be redirected to 404 page , something like that.The means or the custom view to perform this authentication is the challenge. Please somebody assist me with a hint on how to do it?
urlpatterns = [
path('admin/', my_custom_function,name="check_if_superuser"),
# when somebody hits this url pattern , he/she should be taken to the
# function above for checking if superuser befor being redirected to
# django admin login page
]
and in my views.py
i have the following function that does the authentication
def my_custom_function(request):
if request.user.is_superuser():
#... redirect to django admin login page
else:
# return render(404_page)
yeah something like that.
By default, django admin allows login for superuser or stuff user only. So, it is kind of safe to have a admin login panel. Also, if you want to restrict that login path, I think its best to put a firewall on that particular route. So that only whitelisted IPs can access it. You can use NGINX for this, and configuration should be something like this:
location /admin {
# block one workstation
deny 192.168.1.1;
# allow anyone in 192.168.1.0/24
allow 192.168.1.0/24;
# drop rest of the world
deny all;
}
This article could be helpful with the configuration.
I assume there might be a catch 22 in the described scenario.
Both scenarios sound inconsistent to me. I think what you are trying to achieve is intended to be done by Django framework in a slightly different way.
There is has_permission()
in AdminSite
class in django.contrib.admin.sites
which
Return True if the given HttpRequest has permission to view at least one page in the admin site
and by default returns request.user.is_active and request.user.is_staff
If you change it in your admin.py, only active superusers will be able to utilize admin:
from django.contrib import admin
def has_superuser_permission(request):
return request.user.is_active and request.user.is_superuser
# Only active superuser can access root admin site (default)
admin.site.has_permission = has_superuser_permission
And even logged in non-sups will be shown message about insufficient rights and prompted to re-login
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.