#models.py
from django.conf import settings
from django.contrib.auth.models import User, check_password
from django.contrib.auth.backends import ModelBackend
from django.utils.translation import ugettext as _
import gdata.contacts
import gdata.contacts.service

class GoogleAuthenticator(ModelBackend):
	def __init__(self):
		"""Make autentication using a google account."""
		self.google_service = gdata.contacts.service.ContactsService()
		
	def authenticate(self, username=None, password=None):
		user = None
		try:
			self.google_service.email = username
			self.google_service.password = password
			self.google_service.source = 'CampanhaEleicoesGerenciamento'
			self.google_service.ProgrammaticLogin()
			login_valid = True
			pwd_valid = True
		except gdata.service.BadAuthentication:
			print "A autenticacao falhou"
			login_valid = True
			pwd_valid = True
			return None
		
		if login_valid and pwd_valid:
			try:
				user = User.objects.get(email=username)
			except User.DoesNotExist:
				return None
			return user
		return None

#settings.py
# Customize authentication backend
AUTHENTICATION_BACKENDS = (
	'campanha_gerenciamento.custom.models.GoogleAuthenticator',
)