LDAP authentication in Django - django

I'm very new to Django and LDAP ... any help is is appreciated.
So i'm trying to setup and ldaps in Django. I'm trying to follow this (http://packages.python.org/django-auth-ldap/) instruction, but i have few questions ...
Where is AUTHENTICATION_BACKENDS located? So that i can add django_auth_ldap.backend.LDAPBackend
Where is AUTH_LDAP_SERVER_URI?
If i get the solutions to these i maybe able to figure out the rest ...
Thanks a lot for looking into this.

AUTHENTICATION_BACKENDS should be located in your settings.py. This is where almost all configuration is done.
For AUTH_LDAP_SERVER_URI, I think you need to add this as a global variable to your settings.py.
You may also take a quick look at the example configuration on the page you referred to.
EDIT
You are right, those variables are not present in the initial settings.py. You need to add the following to your settings.py:
# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com" # replace by the real URI

Related

where to add "social_core.backends.yammer.YammerOAuth2" for social authentication in django

Hey guys I am new to django , I am learning to build some application using it , so I am following some example instructions of some blog. In that there is need of configuring an social authentication django package with my app.
I am not getting where to add this line please point out.
Add social_django to INSTALLED_APPS Add
social_core.backends.yammer.YammerOAuth2 to AUTHENTICATION_BACKENDS
Set LOGIN_REDIRECT_URL = ‘/badges/’ Set LOGIN_URL = ‘/login/yammer’

JSON Web Token for Django REST won't authenticate to user database

I have a working Django REST API backend. I was previously using session authentication, but would like to move to token based for scaling across multiple servers. I have been researching this for a couple days now and I have not found an answer to my problem. I added the djangorestframework-jwt package to my application but when I try to authenticate is always returns:
{"non_field_errors":["Unable to login with provided credentials."]}
I see in the jwt package where this error is, and can follow the code back through the authentication process. I do not see any errors in the auth process. When I try to create a user with those credentials it says that a user already exists, so I know it is hitting the correct user table. I am not sure why the obtain_jwt_token endpoint will not authenticate my credentials. Below are relevant sections of my django app. Any help would be greatly appreciated. If I am leaving anything out that could help figure this out please let me know and I will upload it. Thanks,
app/settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100,}
app/urls.py
urlpatterns = patterns('',
# Api
url(r'^api/', include(router.urls)),
url(r'^api/stats', statsviews.StatsView.as_view()),
url(r'^api/testing', statsviews.TestView.as_view()),
url(r'^api/login', 'rest_framework_jwt.views.obtain_jwt_token'),
url(r'^api/logout', logout, {'next_page': '/api/login'}),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
curl command
curl -d "email=test#myemail.com&password=test123" http://webhost.mywebsite.com:8080/api/login/
I have a very similar setup to you. A simple app, utilizing vanilla DRF JWT authentication. The only difference that I can tell is that I have rest_framework_jwt included in my INSTALLED_APPS list:
INSTALLED_APPS = (
...
# Third Party Dependencies
'rest_framework',
'rest_framework_jwt',
'corsheaders',
....
Try adding that and see where it gets you.
I encountered the same problem too,and finally found the way out.
following the quick start guide (http://www.django-rest-framework.org/tutorial/quickstart/) , using python manage.py migrate to create table structure; using python manage.py createsuperuser to create an initial user named admin with a password of "password123"; (attention: the passwords mismatch in guides)
now it should be ok.
$ curl -X POST -d "username=admin&password=password123" http://127.0.0.1:8000/api-token-auth/
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MiwiZW1haWwiOiJhZG1pbkA3amdvLmNvbSIsImV4cCI6MTQ3MDY0NjY4Mn0.Dg4KW5pHHJfuaRzjqHTu8kYIzkq8js9}

Django Debug Toolbar show queries from middleware

I am using Django Debug Toolbar to debug and optimize my website. I am also using some custom middleware to do things such as checking to see if a user is logged in and is allowed to access the url they are trying to view, querying ads, etc.
In this middleware, sometimes SQL queries are performed, but the queries don't show up under the 'queries' panel in DDT. Is there any way to get DDT to recognize and track middleware?
According to the documentation:
The order of MIDDLEWARE_CLASSES is important. You should include the
Debug Toolbar middleware as early as possible in the list. However, it
must come after any other middleware that encodes the response’s
content, such as GZipMiddleware.
The solution is to put debug_toolbar.middleware.DebugToolbarMiddleware before your custom middleware in MIDDLEWARE_CLASSES.
One of the place i found error is when I added a separate file debugtoolbar.py for all settings pertaining to enable debug_toolbar. I just imported this in my settings_local.py but it was calling somehow twice and it was not showing the queries.
As soon as I added a conditional statement to add
import os
import sys
from my_project.settings import INSTALLED_APPS, MIDDLEWARE_CLASSES
DEBUG_TOOLBAR_APPS_NAME = 'debug_toolbar'
if DEBUG_TOOLBAR_APPS_NAME not in INSTALLED_APPS:
INSTALLED_APPS += ( DEBUG_TOOLBAR_APPS_NAME, )
DEBUG_TOOLBAR_MIDDLEWARE = 'debug_toolbar.middleware.DebugToolbarMiddleware'
if DEBUG_TOOLBAR_MIDDLEWARE not in MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = ( DEBUG_TOOLBAR_MIDDLEWARE, ) + MIDDLEWARE_CLASSES
def custom_show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': 'my_project.settings.custom_show_toolbar',
}
It started working all fine. Hope this will save someone's time.

Django admin DoesNotExist at /admin/

I have some problems with Django admin.
after syncdb, the result is:
Creating tables ...
Installing custom SQL ...
Installing indexes ...
No fixtures found.
What does this mean?
Anyway, when I visit the website admin panel http://www.example.com/admin/, I receive this message:
DoesNotExist at /admin/
Site matching query does not exist.
setting.py contains:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
)
ur.py contains:
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'rshd.views.home', name='home'),
# url(r'^rshd/', include('rshd.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You don't really need the sites framework if you only run one site from the project, so the easiest fix would be to remove the following item from your INSTALLED_APPS and the error should go away:
'django.contrib.sites'
You can also re-create the missing Site object from shell. Run python manage.py shell and then:
from django.contrib.sites.models import Site
Site.objects.create(pk=1, domain='www.example.com', name='example.com')
You can fix this error if you are using django.contrib.sites without removing it by changing SITE_ID = 1 value in settings.py file.
It is happen to me when I changed domain name on my server, I deleted old domain name from http://mynewdomainname.com/admin/sites/site/ manually, and the old domain record in database has id = 1, also I added new domain name mynewdomainname.com and it is id was id = 2,
I just changed to SITE_ID = 2 and the error gone SITE_ID refers to current "pk" of active domain name you use as default.
In code:
>>> from django.contrib.sites.models import Site
>>> # get_current() came from SiteManager class manager,
>>> # see site-packages/django/contrib/sites/models.py
>>> current_site = Site.objects.get_current()
>>> print(current_site.pk)
2
>>> print(current_site.domain)
'http://mynewdomainname.com'
this happen after settings.py changed
SITE_ID = 2
Be careful about current domain id in django sites app.
The same problem also suddenly came to me, and you know there're many solutions. However, what's the reason of this sudden problem?
After dig in deeply, I found the reason is that, we ignored a step in the first syncdb action.
When you have your first syncdb, django will ask you to create a default account, if you don't input in this interactive show, that site object would not be created automatically.
So be careful of this. I'm using django 1.3.1, don't know whether the latest version has resolved this issue.
Since the above comments are pretty old and the syncdb command doesn't exist, and I don't want to remove django.contrib.sites, here's what worked for me:
Increment SITE_ID. I had SITE_ID = 1, changed it to SITE_ID = 2 and everything worked again.
Add SITE_ID = 1 in your settings.py
just fixed the issue by an another way:
I use PostgreSQL and Django 1.45...
as i removed the www.example.com Site and added a new www.xxx.com Site it was added as ID=2
'cause PostgreSQL doesn't go back in the ID numbers and the login and logout Django-Sites are somehow bound only to the ID=1 Site in your DB...
I went to my PostgreSQL DB and changed the ID of www.xxx.com to 1 and then I was able to see the login and logout Site again :)
btw. [yes, you just can remove the django.contrib.sites from your settings.py if you don't need it ^^ (but I haven't tried this one out in my case, with the ID number problem)]
hope it will work for further users! ;)
Yes change the SITE_IT=1 to SITE_ID=2 and everything is ok
Yes, the solution mentioned at the top can be (part of) the solution.
I've noticed however, that not only including django.contrib.sites without configuration can cause that problem, also including any site of
allauth (pip install django-allauth) might cause this problem if said package is not configured correctly.
(And allauth is as far as I've seen not configured correctly by default...)
Another thing you can do is simple if you get some error or just want to change site.
Download sqlitebrowser
open your sqlite.db
search for django_sites
change domain name and display name to whatever you want
Check your Window task manager and make sure that there is 1 process name 'python.exe' is running. If there are many, delete all of them then restart the server. This solution works for me.

Registered models do not show up in admin

I added a model to admin via admin.site.register, and it does not show up in admin. Since admin is so "It just works", I have no idea of how to debug this. Pointers?
After adding and registering your admin:
# app/admin.py
class YourModelAdmin(admin.ModelAdmin):
pass
admin.site.register(YourModel, YourModelAdmin)
Make sure your app is in your project settings.py:
# settings.py
INSTALLED_APPS = (
# other apps ...
'app',
)
Sync your project for that model if you have not done so already:
python manage.py syncdb
Restart your server, CTRL-C:
python manage.py runserver
In such a situation is also a good practice to check if the user logged in to the admin panel has rights to manage such a model. If they do then you could change your code to access the functions as root.
When in doubt, shut down server, syncdb, start server.
I have the experience, that sometimes after changing an admin.py the dev-sever won't be restarted. in that case touch settings.py helps.
I think the checklist in Thierry's answer is almost definitive, but make sure that urls.py contains admin.autodiscover() to load INSTALLED_APPS admin.py modules.
# urls.py
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
('^admin/', include(admin.site.urls)),
)
More info in the django docs.
Have you added the application to your installed apps? That has happened to me both one and two times. :) Otherwise it would be useful for us to see the code to help you.
Also make sure there are no syntax errors in your admin.py or anything. That can cause an app to fail to be registered with the AdminSite.
I've faced the same problem, but it was a little tricky than yours.
Consider, that you have a project with, say, five or even more apps. For me it is more obvious to register all models in just one admin.py file, so I have decided to do it in one place - core directory. Of course, it was not an app, so none of models showed up on admin page.
comment out the some lines in urls.py see docs for more details
admin.autodiscover()
urlpatterns = patterns('',
('^admin/', include(admin.site.urls)),
)