from django.conf import settings
from django.contrib.auth.models import User, check_password
import cranslib.gestion.authentification as auth
import cranslib.utils.logs as logs
LOGGER = logs.getFileLogger( "accounts" )

class LdapBackend:
    """
    Authenticate against the cr@ns API
    """
    def authenticate(self, username=None, password=None):
        try:
            crans_user = auth.login( username, password )
            LOGGER.info( "user %s logged in" % username )
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked;
                user = User(username=username, password="")
            user.first_name = crans_user.prenom
            user.last_name = crans_user.nom
            user.email = crans_user.mail
            if crans_user.is_nounou():
                user.is_staff = True
                user.is_superuser = True
            user.save()
            return user
        except auth.AuthentificationFailed, e:
            print "Auth failed"
            LOGGER.warning("authentification Failed [%s]" % str(e) )
        except Exception, e:
            LOGGER.critical( str( e ) )
            raise e



    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
