Django Contrib Auth for MongoDB Middleware Session Authentication code
Django/MongoDB Session Middleware
Folder structure:-
-----Session
---------_init_.py
---------db.py
---------middleware.py
db.py
import datetime
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation
from django.utils.encoding import force_unicode
from <<projectname>>.db import get_db_connection
class SessionStore(SessionBase):
"""
Implements database session store.
"""
def __init__(self, session_key=None):
super(SessionStore, self).__init__(session_key)
def load(self):
db = get_db_connection()
s = db.session.find_one({"session_key": self.session_key,"expire_date":{"$gte":datetime.datetime.now()}})
if not s:
self.create()
return {}
return self.decode(force_unicode(s['session_data']))
def exists(self, session_key):
db = get_db_connection()
if db.session.find({"session_key": session_key}).count() > 0:
return True
else:
return False
return True
def create(self):
while True:
self.session_key = self._get_new_session_key()
try:
# Save immediately to ensure we have a unique entry in the
# database.
self.save(must_create=True)
except CreateError:
# Key wasn't unique. Try again.
continue
self.modified = True
self._session_cache = {}
return
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
db = get_db_connection()
sesobj = db.session.find_one({"session_key":self.session_key})
if sesobj:
sesobj['session_data'] = self.encode(self._get_session(no_load=must_create))
sesobj['expire_date'] = self.get_expiry_date()
db.session.save(sesobj)
else:
obj = {"session_key":self.session_key,
"session_data":self.encode(self._get_session(no_load=must_create)),
"expire_date":self.get_expiry_date()}
db.session.insert(obj)
def delete(self, session_key=None):
if session_key is None:
if self._session_key is None:
return
session_key = self._session_key
try:
db = get_db_connection()
db.session.find_one({"session_key":session_key}).delete()
except Exception, exception:
pass
middleware.py:-
import time
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils.http import cookie_date
from <<projectname>>.db import get_db_connection
class SessionMiddleware(object):
def process_request(self, request):
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
request.session = SessionStore(session_key)
def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie.
"""
try:
accessed = request.session.accessed
modified = request.session.modified
except AttributeError:
pass
else:
if accessed:
patch_vary_headers(response, ('Cookie',))
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Save the session data and refresh the client cookie.
request.session.save()
response.set_cookie(settings.SESSION_COOKIE_NAME,
request.session.session_key, max_age=max_age,
expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None)
return response
Folder structure:-
-----Session
---------_init_.py
---------db.py
---------middleware.py
Step1: Create an app for session in your project
Step 2: Import your db_connection
Step 3: Just copy paste the db.py and middleware file in your app
I hope this will helpful for django/mongodb beginners to know about ,
"Django Contrib Auth Middleware Session in MongoDB"
db.py
import datetime
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation
from django.utils.encoding import force_unicode
from <<projectname>>.db import get_db_connection
class SessionStore(SessionBase):
"""
Implements database session store.
"""
def __init__(self, session_key=None):
super(SessionStore, self).__init__(session_key)
def load(self):
db = get_db_connection()
s = db.session.find_one({"session_key": self.session_key,"expire_date":{"$gte":datetime.datetime.now()}})
if not s:
self.create()
return {}
return self.decode(force_unicode(s['session_data']))
def exists(self, session_key):
db = get_db_connection()
if db.session.find({"session_key": session_key}).count() > 0:
return True
else:
return False
return True
def create(self):
while True:
self.session_key = self._get_new_session_key()
try:
# Save immediately to ensure we have a unique entry in the
# database.
self.save(must_create=True)
except CreateError:
# Key wasn't unique. Try again.
continue
self.modified = True
self._session_cache = {}
return
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
db = get_db_connection()
sesobj = db.session.find_one({"session_key":self.session_key})
if sesobj:
sesobj['session_data'] = self.encode(self._get_session(no_load=must_create))
sesobj['expire_date'] = self.get_expiry_date()
db.session.save(sesobj)
else:
obj = {"session_key":self.session_key,
"session_data":self.encode(self._get_session(no_load=must_create)),
"expire_date":self.get_expiry_date()}
db.session.insert(obj)
def delete(self, session_key=None):
if session_key is None:
if self._session_key is None:
return
session_key = self._session_key
try:
db = get_db_connection()
db.session.find_one({"session_key":session_key}).delete()
except Exception, exception:
pass
middleware.py:-
import time
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils.http import cookie_date
from <<projectname>>.db import get_db_connection
class SessionMiddleware(object):
def process_request(self, request):
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
request.session = SessionStore(session_key)
def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie.
"""
try:
accessed = request.session.accessed
modified = request.session.modified
except AttributeError:
pass
else:
if accessed:
patch_vary_headers(response, ('Cookie',))
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Save the session data and refresh the client cookie.
request.session.save()
response.set_cookie(settings.SESSION_COOKIE_NAME,
request.session.session_key, max_age=max_age,
expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None)
return response
code written by,
T.Thanga Vignesh Raja
T.Thanga Vignesh Raja
Comments
Post a Comment