Django Auth behind proxy server

Posted on the January 15th, 2011 under Django, Programming, Python by Mauro

Yesterday I had a weird problem with a Django application that should primarily work on computer behind a proxy server: for some reason that I didn’t understand yet, the proxy lost the session’s cookie, but only when a form send data (via POST) to a view that is visible only to logged users (=O).
The other views works well, but that particular views lost the cookie! What to do in this case?
A simple workaround helped me: I sent the session id via GET to the view. I know, django never use this for security reason, but I didn’t find a “official” solution, so this is what I did:

I create this middleware that use the query string session id if it doesn’t find the session’s cookies in the request:

from django.conf import settings
 
class FakeSessionCookieMiddleware(object):
 
    def process_request(self, request):
        if not request.COOKIES.has_key(settings.SESSION_COOKIE_NAME) and request.GET.has_key(settings.SESSION_COOKIE_NAME):
            request.COOKIES[settings.SESSION_COOKIE_NAME] = request.GET[settings.SESSION_COOKIE_NAME]

You have to add this middleware to your settings.py before django.contrib.sessions.middleware.SessionMiddleware:

MIDDLEWARE_CLASSES = (
    ...
    'myapp.middleware.FakeSessionCookieMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
)

In this case the middleware class is inside the middleware.py file in myapp application.
Then you can add SESSION_COOKIE_NAME in your context like this:

context = {
    'session_cookie_name': settings.SESSION_COOKIE_NAME,
    'session_cookie_value': request.COOKIES[settings.SESSION_COOKIE_NAME], 
} 
    template = 'yourtemplate.html' 	
    return render_to_response(template, context, context_instance=RequestContext(request))

and pass “session_cookie_name” and “session_cookie_value” in your URL:

<a href="/your/url/?{{session_cookie_name}}={{session_cookie_value}}">

Is ugly and potentially dangerous, but it’s an extreme solution in case you REALLY have this problem that can’t be solved in other ways. Hope this can help someone with the same issue.

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Django Tip: Cross Domain Cookies

Posted on the January 15th, 2011 under Django, Python by Mauro

If you use the Django Auth Framework you may need to know the existence of this constant that you can set in the settings.py of your project:

SESSION_COOKIE_DOMAIN = ".yourdomain.com"

when you login, your cookies session will be set to be valid on every subdomain, so you will be still logged in www.yourdomain.com, yourdomain.com, and any every subdomains.yourdomain.com.

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Django admin: how to hide fields for certain users (that are not superusers)

Posted on the April 8th, 2010 under Django, Programming, Python by Mauro

I’m working on a project and I’m using the incredible django admin. So, yesterday I needed a way to hide some fields in a model for user that didn’t have superuser permissions. After some googling, I found a method in the ModelAdmin class that was perfect (well, I think that it’s perfect) for my needs: get_form.
The method is not really mentioned in the official django documentation except in the comment framework, but you can use it in your ModelAdmin subclass as well. It’s called before the “change form” is created, so we can dynamically change it before it’s displayed.
The principle is very simple: I dynamically populate the exclude attribute so that if a user is not a superuser I can exclude a field (or more that one field). Let’s see an example:

class MyModelAdmin(admin.ModelAdmin):
	def get_form(self, request, obj=None, **kwargs):
		self.exclude = []	
		if not request.user.is_superuser:
			self.exclude.append('field_to_hide')
		return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

What it does is simply add the field_to_hide to the exclude list of MyModelAdmin. In this case, the field will be visible only to superusers, checking the request.user.is_superuser attribute. Pretty simple!

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Time to change

Posted on the April 6th, 2010 under Programming by Mauro

According to w3c browser statistics ie6 is less then 10% of the market today, and ie7 is 11%. IE8 is growing (about 15%) and, although it is not the best browser on earth it is a big step forward. A preview release of IE9 has been unveiled, and it seems that something is really changing. So we (web designers in this case) should seriously start to think about saying goodbye to the horrible and heated ie6 right now, serving a specific universal CSS for that browser:
http://forabeautifulweb.com/blog/about/universal_internet_explorer_6_css.

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Persistent drag and drop tree with jQuery, PHP and MySQL – CRUD

Posted on the August 4th, 2009 under Javascript, MySQL, PHP, Programming, jQuery by Mauro

Many people asked me how to implement the basic CRUD functionalities for the D&D Tree, so here it is:


download Download persistentTreeCRUD.zip

I use the simpletree callback function afterDblClick for the modify functionality, and a simple jQuery click for add and delete. I also used nyroModal for the popup windows.
In this example i reload the page when a CRUD operation is performed, a better implementation should use ajax to modify the tree on the fly.
Is not perfect but it works :) Enjoy!

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

How to develop a Plug-in for Panic Coda with Python

Posted on the March 31st, 2009 under Programming, Python by Mauro

If you are (like me) a mac fan and you use the excellent Panic Coda to develop, you should know that is now possible to write plugins with every languages you want (if you have the interpreter installed on your system).
Python is bundled on every mac, and is also a beautiful and simple language, so i want to show how to develop a simple plugin for Coda with Python!
First of all you need to download the Coda Plug-in Creator that is the application that will convert your python script into a brand new plugin.
Read the full article…

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Persistent drag and drop tree with jQuery, PHP and MySQL – part 2

Posted on the March 29th, 2009 under Javascript, MySQL, PHP, Programming, jQuery by Mauro

In this second part of this article (this is the first part) i’m going to show you how to retreive and serialize the tree structure using jQuery and sent the serialized data to a php script (using ajax) that saves it on the database. In this way, we can have the persistence of any change made on the tree.
Read the full article…

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Persistent drag and drop tree with jQuery, PHP and MySQL – part 1

Posted on the March 15th, 2009 under Javascript, MySQL, PHP, Programming, jQuery by Mauro

I’m developing a website that have a catalog with nested categories; this categories are also ordered and with a not predefined depth levels. I needed to find a way to manage with category in a fast and intuitive way for the user, so i decided to use a directory like tree allowing the users to drag and drop the categories to change the order and even the position on the tree: of course i use jQuery to do this, and PHP/MySQL to save the structure of the tree in a database.
I found a nice tree jQuery plugin on the web, that i used as a starting point for my project: http://news.kg/wp-content/uploads/tree/. The plugin work well on all browser i tested (FF3, Safari 3, IE6, IE7). It provide the drag and drop funcionality and some interesting callback, like afterClick and afterDblClick.
But let’s start from the beginning. Read the full article…

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

RegEx: Link not beginning with http://

Posted on the January 23rd, 2009 under PHP by Mauro

I had to find a regex to match not a string that contain something, but a string that not contain something, and in particular i had to check that a link entered in a form does not begin with http://. I needed to use a regex for this that work with PHP and, i have to admin, it was not so simple.
The method that i found is based on lookahead technique, but seem to work only with preg_match() and not with ereg(). Is not perfect, because it don’t match any string that contain http://, not only that begin with.
This is the regex:


(^((?!.*http\://).)*$)

This match www.ciao.com, but not http://www.ciao.com and also not www.ciao.com/http:// and any string that contain http://. It work for my needs, but is not what really wanted to achieve.
If you know a method to correct the regex, please tell me.

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)