Django-xmpp -Ejabberd Integration - django

I have created a django-rest project so that a user can register using email and subsequently user can activate the account using email link. The user authentication for rest server is working fine.
However, I want to create a ejabberd server for an instant messaging apps. I want to use external authentication method in ejabberd so that ejabberd can use the django project data.
Hence as per the guide line in Django-xmpp I am trying the following.
I have change the lines in ejabberd.cfg as
{auth_method, external}.
{extauth_program, "/home/...../ejabberd_auth.sh"}.
After that I have created a file name ejabberd_auth.sh which contains the following
#!/bin/bash
cd /home/------/src #(my django-rest project folder/location of manage.py)
python manage.py ejabberd_auth $#
Then I changed the setting.py in my django project. The settings file looks like
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-------'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
# Rest Framework app
'rest_framework',
'rest_framework.authtoken',
# Internal Apps
'data',
'django_gravatar',
'xmpp',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.DjangoModelPermissions'
)
}
ROOT_URLCONF = 'ndMyFirst.urls'
WSGI_APPLICATION = 'ndMyFirst.wsgi.application'
XMPP_DOMAIN = 'localhost'
XMPP_BOSH_SERVICE_URL = 'localhost:5280/http-bind'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'`
Then I started ejabberd server. When I am trying to login in 127.0.0.1:5280/admin unauthorized response received. I have also tried to register a user using ejabberdctl register admin localhost password and not allowed message received.
I do not have any idea the external authentication works.
What should I do so that the external authentication works.

Related

In my settings.py file I set DEBUG = False, but website still debugs on webserver (nginx)

This is the settings.py file. As you can see, both debug and template debug are set to False. Yet, if I try to trigger a 404 error, I don't get a regular 404 error or the one from my 404.html file. The 404 error that it returns is the one from Django where it says :
"You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page."
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'this is a secret'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['mywebsite.com','my website\'s ip']
# Application definition
INSTALLED_APPS = (
'myapp',
'django.contrib.admin',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'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',
)
ROOT_URLCONF = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = '/home/django/django_project/django_project/static'
STATIC_URL = '/static/'
Help!
(just to mark that this question is answered - by #e4c5)
summary:
if your django application is running as a separate daemon (manage.py runfcgi, gunicorn, uwsgi etc.), every time you change source file (this includes settings.py) - application need to be restarted
regarding templates - this depends how you load them - if you use any form of cache - you should reload daemon, without cache - it should be reloaded automatically
make sure that your date and time is always set properly, sometimes reported errors include that after code upgrade application is still running old one - in most cases there is an issue with the dates - compiled .pyc files are newer than your source .py ones, ./manage.py clean_pyc after deployment is a good thing to do.

Django Models save() works on localhost, but not on a remote server

I'm working on a very basic Django app in hopes of teaching myself the framework, and I've hit a small snag. The app is intended to take user input, store it in a mysqlite database, and display the contents of the database on receiving a request. I have everything working properly when the app is run locally (manage.py runserver), however it's misbehaving once it's deployed. For some reason, the storage logic is malfunctioning on the live site (Windows Server 2012 via MS Azure).
Here is the code in question:
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import render_to_response
from helloworld.models import Registry
def home(request):
return render_to_response("home.html")
def register(request):
return render_to_response("register.html")
def view(request):
entries = Registry.objects.all()
args = {}
args["entries"] = entries
return render_to_response("registry.html", args)
def submit(request):
nameIn = request.GET.get('name')
ageIn = request.GET.get('age')
monthIn = request.GET.get('month')
try:
Registry(name=nameIn, age=ageIn, month=monthIn).save()
except:
pass
return view(request)
I've done a fair amount of debugging, and tried several approaches to storing the data. I've checked that the method is receiving valid values. I can't, for the life of me, figure out why that call to save() is throwing an error. Hopefully it will be obvious to one of you Django-pros! THanks in advance, any help will be greatly appreciated! P.s. I'm attaching my settings file, as i have a sneaking suspicion that poor configuration is the source of my troubles.
"""
Django settings for cny_solar project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 's7xv#m=5h=mjrdg_7-$=7kr8kx4np9$#6qzlg+m4xt&6-#-zi2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS=['127.0.0.1','localhost']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloworld',
)
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',
)
ROOT_URLCONF = 'helloworld.urls'
WSGI_APPLICATION = 'helloworld.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_ROOT = BASE_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('assets', os.path.join(BASE_DIR, 'static')),
)

Django hosting static files on the server

I am trying to deploy my Django project on the server. But, when I use it, the static file on Django can not be read correctly
I deploy my project on Debian server. The static file of course in same server, I have succeeded in deploying my project. But static files like css still can not appear in my project
This is my settings files:
"""
Django settings for akun project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_DIR = os.path.join(PROJECT_ROOT)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8g*v#sf1i0y#+#5jyy$kk)wlixu*9yo(t$&1n%59ip*391sy#u'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'simofa',
'accounts',
)
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',
)
ROOT_URLCONF = 'akun.urls'
WSGI_APPLICATION = 'akun.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'pgina',
'USER': 'root',
'PASSWORD': '123',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Jakarta'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
# template location
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(PROJECT_ROOT), "static", "templates"),
'/home/boss/kantor/akun/templates/',
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(PROJECT_DIR),"static","static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_DIR),"static","media")
STATICFILES_DIRS = os.path.join(os.path.dirname(PROJECT_DIR),"static","static"),
i'm trying to change STATIC_URL='/static/' to the url STATIC_URL='http://www.url.com/my_project/static'
but the result still doesn't appears
When i try in my localhost, it works properly.
how is the solution ?
In production you need first to define STATIC_ROOT and then run collectstatic in order to have your static files collected there.
After running collectstatic you should be able to cd to the dir associated to STATIC_ROOT and see the files.
EDIT: the code below should be added in he Apache conf file, not in the Django settings
Finally if you are using Apache (and you are serving the files from the same server where you are running the Django app) you will need to serve the path of the STATIC_ROOT under the url defined in STATIC_URL, for example assuming STATIC_URL is /static/:
Alias /static/ /path/to/mysite.com/static_root_directory/
and then set permissions:
<Directory /path/to/mysite.com/static_root_directory>
Require all granted
</Directory>
PS you didn't provide many details about your environment (server, static on same server or not) so I had to make assumptions. If you provide more details I'm happy to help.
Static files dirs should be a tuple
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

I have deployed my django project in pythonanywhere, DATABASES is improperly configured error

I have deployed my django project in pythonanywhere without any databases required, I am getting the error- DATABASES is improperly configured . The link to my deployed project is -http://drchitradhawle.pythonanywhere.com/
My setting.py file is-
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'fi+9_egiio(7l6xvbgk%o=!k(ktn3!ywhc4+p_6^57j4yvl0tp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webpage',
)
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',
)
ROOT_URLCONF = 'website.urls'
WSGI_APPLICATION = 'website.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_ROOT = "/home/DrChitraDhawle/website/webpage/static"
STATIC_URL = '/static/'
STATICFILES_DIR = (
('assets', '/home/DrChitraDhawle/website/webpage'),
)
#
#STATICFILES_DIR = [os.path.join(BASE_DIR, '')]
MEDIA_URL = 'http://localhost:8085/media/'
Django needs a database to store information such as session/cookie info. So even if you don't use the database for your own website stuff, you still need one.
Fortunately, just using the default sqlite settings, and then running ./manage.py syncdb should be enough to get everything working for now.
Although you don't want to use database in your project but still you have to give database defination as #conrad said. So you can use sqlite3, a file based database that does not require setting up a database account and password.
Set up your database setting as -
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/home/<username>/<ProjectName>/db.sqlite',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': ''
}
}
After that run the below command in console -
python ./manage.py syncdb
Now you will be asked for password, username and email-Id for creating superuser for database.
And its all done!

How to achieve LDAP authentication in Django, How to access User object in View?

I want to build a site using Django wherein to enter it, the users have to authenticate themselves through LDAP server.
I have read the python-ldap configuration and configured settings.py accordingly. I'm able to authenticate a user from local database, but when I try to do it through LDAP, it doesn't work.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = [os.path.join(BASE_DIR,'templates')]
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
# Baseline configuration.
AUTH_LDAP_SERVER_URI = "ldap://10.1.10.10"
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: 0
}
AUTH_LDAP_BIND_DN = "cn=myname,dc=example,dc=com"
AUTH_LDAP_BIND_PASSWORD = "dontevenask"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
#AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^eh5xdkui7vw!^x&l%q44ak6+yglnx5q(tqwd8l+w!sxml7q!&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
)
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',
)
ROOT_URLCONF = 'users.urls'
WSGI_APPLICATION = 'users.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS':{
'read_default_file':'/home/user/config.cnf',
},
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
Here is my views.py file
def loggedin(request):
uid = request.user.username
return render_to_response('loggedin.html',
{'full_name':uid})
And the loggedin.html file
{% block content %}
<h2> Hi {{full_name}} Logged in! </h2>
<p> Click here to logout </p>
{% endblock %}
I did refer to other posts but didn't find the solution.
What am I missing?
There are several issues that might cause the LDAP authentication not to work.
I am assuming you are running linux host. Have you verified that the LDAP settings you have entered works properly? Use command line tool 'ldapsearch' verify that the server works and responses as you might expect.
After you have successfully authenticated with ldapsearch and the authentication is still not working in Django i suggest you put logging on on and paste the logs somewhere.
Without futher info its hard to say what part of your setup is incorrect.
So, here goes the answer!
I changed "(uid=%(user)s)") to "(samaccountname=%(user)s)") which did the trick.
Having the logger helped locate what the problem was - was it even talking to LDAP or just trying to authenticate with the local database.