Ejemplo n.º 1
0
    def authenticate(self, username=None, password=None):
        """Attempt to authenticate a particular user.

        The username field is taken
        to be an email address and checked against LDAP if the user cannot
        be found.

        Always returns an instance of `django.contrib.auth.models.User` on
        success, otherwise returns None.
        """
        User = get_user_model()
        if password is None:
            return None
        try:
            user = User.objects.get(email__iexact=username)
            if user.check_password(password):
                return user
            else:
                try:
                    ldapauth = LDAPBackend()
                    return ldapauth.authenticate(username=user.username,
                                                 password=password)
                except:
                    return None
        except User.DoesNotExist:
            try:
                ldapauth = LDAPBackend()
                user = ldapauth.authenticate(username=username,
                                             password=password)
                if user is None:
                    return None

                first_name = user.first_name
                last_name = user.last_name
                email = user.email
                if email:
                    if User.objects.filter(email__iexact=email).count() > 1:
                        user.delete()
                    user = User.objects.get(email__iexact=email)
                    user.first_name, user.last_name = first_name, last_name
                    user.save()
                else:
                    user = User.objects.get(username=username)
                    user.first_name, user.last_name = first_name, last_name
                    user.save()
                return user
            except Exception, e:
                logger.warning(
                    "User does not exist even after LDAP. Exception: {0}".
                    format(e))
                return None
Ejemplo n.º 2
0
def authenticateEntry(request):
    """接收http请求,然后把请求中的用户名密码传给loginAuthenticate去验证"""
    if request.is_ajax():
        strUsername = request.POST.get('username')
        strPassword = request.POST.get('password')
    else:
        strUsername = request.POST['username']
        strPassword = request.POST['password']

    if settings.ENABLE_LDAP:
        ldap = LDAPBackend()
        user = ldap.authenticate(username=strUsername, password=strPassword)
        if user:
            if user.is_active:
                request.session['login_username'] = strUsername
                result = {'status': 0, 'msg': 'ok', 'data': ''}
            else:
                result = {'status': 5, 'msg': 'user is not active', 'data': ''}
            return HttpResponse(json.dumps(result),
                                content_type='application/json')

    result = loginAuthenticate(strUsername, strPassword)
    if result['status'] == 0:
        request.session['login_username'] = strUsername
    return HttpResponse(json.dumps(result), content_type='application/json')
    def authenticate(self, username, password):

        user = None
        try:
            user = LDAPBackend.authenticate(self, username, password)
        except Exception, e:
            LOG.exception(e)
Ejemplo n.º 4
0
def authenticateEntry(request):
    """接收http请求,然后把请求中的用户名密码传给loginAuthenticate去验证"""
    if request.is_ajax():
        strUsername = request.POST.get('username')
        strPassword = request.POST.get('password')
    else:
        strUsername = request.POST['username']
        strPassword = request.POST['password']

    lockCntThreshold = settings.LOCK_CNT_THRESHOLD
    lockTimeThreshold = settings.LOCK_TIME_THRESHOLD

    if settings.ENABLE_LDAP:
        ldap = LDAPBackend()
        user = ldap.authenticate(username=strUsername, password=strPassword)
        if strUsername in login_failure_counter and login_failure_counter[
                strUsername]["cnt"] >= lockCntThreshold and (
                    datetime.datetime.now() -
                    login_failure_counter[strUsername]["last_failure_time"]
                ).seconds <= lockTimeThreshold:
            log_mail_record(
                'user:{},login failed, account locking...'.format(strUsername))
            result = {'status': 3, 'msg': '登录失败超过5次,该账号已被锁定5分钟!', 'data': ''}
            return HttpResponse(json.dumps(result),
                                content_type='application/json')
        if user and user.is_active:
            request.session['login_username'] = strUsername
            result = {'status': 0, 'msg': 'ok', 'data': ''}
            return HttpResponse(json.dumps(result),
                                content_type='application/json')

    result = loginAuthenticate(strUsername, strPassword)
    if result['status'] == 0:
        request.session['login_username'] = strUsername
    return HttpResponse(json.dumps(result), content_type='application/json')
Ejemplo n.º 5
0
def auth(request):
    if request.user.is_authenticated():
        usersession = UserSession.objects.get(
            session_id=request.session.session_key)
        current_ip = get_ip(request)
        if usersession.ip != current_ip:
            usersession.ip = current_ip
            usersession.save()
    cachekey = "auth_cache_{}".format(request.META.get(
        "HTTP_AUTHORIZATION") or request.session.session_key)
    content = cache.get(cachekey)
    if content:
        response = HttpResponse(content[0])
        for key, val in content[1].iteritems():
            response[key] = val
        response["X-auth-cache-hit"] = "success"
        return response
    if not request.user.is_authenticated():
        # Check basic auth against LDAP as an alternative to SSO.
        try:
            assert request.META.get("HTTP_AUTHORIZATION") is not None
            username, password = request.META["HTTP_AUTHORIZATION"].split(
                " ", 1)[1].strip().decode('base64').split(":", 1)
            ldapauth = LDAPBackend()
            if username.find("@") > -1:
                username = DepartmentUser.objects.get(
                    email__iexact=username).username
            user = ldapauth.authenticate(username=username,
                                         password=password)
            if not user:
                us = UserSession.objects.filter(user__username=username)[0]
                assert us.shared_id == password
                user = us.user
            user.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user)
        except Exception as e:
            response = HttpResponse(status=401)
            response[
                "WWW-Authenticate"] = 'Basic realm="Please login with your username or email address"'
            response.content = repr(e)
            return response
    response = HttpResponse(whoamiResource.as_detail()(request).content)
    headers, cache_headers = json.loads(response.content), dict()
    headers["full_name"] = u"{}, {}".format(
        headers.get(
            "last_name", ""), headers.get(
            "first_name", ""))
    # TODO: use url reverse on logout alias
    headers["logout_url"] = "https://oim.dpaw.wa.gov.au/logout"
    try:
        headers["kmi_roles"] = DepartmentUser.objects.get(
            email__iexact=headers["email"]).extra_data.get(
            "KMIRoles", '')
    except Exception as e:
        headers["kmi_roles"] = ''
    for key, val in headers.iteritems():
        key = "X-" + key.replace("_", "-")
        cache_headers[key], response[key] = val, val
    cache.set(cachekey, (response.content, cache_headers), 3600)
    return response
Ejemplo n.º 6
0
def login(request):
    global account
    if request.META['REMOTE_ADDR'][0:8] == "132.199.":
        if request.method == "POST":
            form = LoginForm(request.POST)
            if form.is_valid():
                post = form.save(commit=False)
                username = post.Benutzername
                try:
                    auth = LDAPBackend()
                    user = auth.authenticate(request, username, post.Passwort)
                    if user is not None:
                        request.session['Benutzername'] = username
                        request.session['stream'] = False
                        django_login(
                            request,
                            user,
                            backend='django.contrib.auth.backends.ModelBackend'
                        )
                        return render(request, 'media.html',
                                      media_template.get_template())
                    else:
                        form = LoginForm()
                        return redirect('login')
                except:
                    print('exceptLDAP')
                    form = LoginForm()
                    return redirect('login')
            else:
                form = LoginForm()
                return render(request, 'login.html', {'form': form})
        else:
            form = LoginForm()

            return render(request, 'login.html', {'form': form})
Ejemplo n.º 7
0
    def authenticate(self, username=None, password=None):
        """
        Attempt to authenticate a particular user. The username field is taken
        to be an email address and checked against LDAP if the user cannot
        be found.

        Always returns an instance of `django.contrib.auth.models.User` on
        success, otherwise returns None.
        """
        User = get_user_model()
        if password is None:
            return None
        try:
            user = User.objects.get(email__iexact=username)
            if user.check_password(password):
                return user
            else:
                try:
                    ldapauth = LDAPBackend()
                    return ldapauth.authenticate(username=user.username, password=password)
                except:
                    return None
        except User.DoesNotExist:
            try:
                ldapauth = LDAPBackend()
                user = ldapauth.authenticate(username=username, password=password)
                if user is None:
                    return None

                first_name = user.first_name
                last_name = user.last_name
                email = user.email
                if email:
                    if User.objects.filter(email__iexact=email).count() > 1:
                        user.delete()
                    user = User.objects.get(email__iexact=email)
                    user.first_name, user.last_name = first_name, last_name
                    user.save()
                else:
                    user = User.objects.get(username=username)
                    user.first_name, user.last_name = first_name, last_name
                    user.save()
                return user
            except Exception, e:
                print e
                return None
Ejemplo n.º 8
0
def login(request):
    data = json.loads(request.body)
    username = data['username']
    password = data['password']
    auth = LDAPBackend()
    user = auth.authenticate(request, username=username, password=password)
    if user is None:
        return HttpResponse(False, status=404)
    return HttpResponse(get_name(username), status=200)
Ejemplo n.º 9
0
def auth(request):
    #print(repr(request.META))
    if request.user.is_authenticated():
        usersession = UserSession.objects.get(
            session_id=request.session.session_key)
        current_ip = get_ip(request)
        if usersession.ip != current_ip:
            usersession.ip = current_ip
            usersession.save()
    cachekey = "auth_cache_{}".format(
        request.META.get("HTTP_AUTHORIZATION") or request.session.session_key)
    content = cache.get(cachekey)
    if content:
        response = HttpResponse(content[0])
        for key, val in content[1].iteritems():
            response[key] = val
        response["X-auth-cache-hit"] = "success"
        return response
    if not request.user.is_authenticated():
        try:
            assert request.META.get("HTTP_AUTHORIZATION") is not None
            username, password = request.META["HTTP_AUTHORIZATION"].split(
                " ", 1)[1].strip().decode('base64').split(":", 1)
            ldapauth = LDAPBackend()
            if username.find("@") > -1:
                username = DepartmentUser.objects.get(
                    email__iexact=username).username
            user = ldapauth.authenticate(username=username, password=password)
            if not user:
                us = UserSession.objects.filter(user__username=username)[0]
                assert us.shared_id == password
                user = us.user
            user.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user)
        except Exception as e:
            response = HttpResponse(status=401)
            response[
                "WWW-Authenticate"] = 'Basic realm="Please login with your username or email address"'
            response.content = repr(e)
            return response
    response = HttpResponse(whoamiResource.as_detail()(request).content)
    headers, cache_headers = json.loads(response.content), dict()
    headers["full_name"] = "{}, {}".format(headers.get("last_name", ""),
                                           headers.get("first_name", ""))
    headers[
        "logout_url"] = "https://oim.dpaw.wa.gov.au/logout"  # TODO: use url reverse on logout alias
    try:
        headers["kmi_roles"] = DepartmentUser.objects.get(
            email__iexact=headers["email"]).extra_data.get("KMIRoles", '')
    except Exception as e:
        headers["kmi_roles"] = ''
    for key, val in headers.iteritems():
        key = "X-" + key.replace("_", "-")
        cache_headers[key], response[key] = val, val
    cache.set(cachekey, (response.content, cache_headers), 3600)
    return response
Ejemplo n.º 10
0
    def authenticate_ldap_user(self, username, password):

        user = LDAPBackend.authenticate(username, password)
        if user:
            print(" #######################  ", user)
            print(" ###############   in  CUSTOM LDAP")

            return user
        else:
            print("&&&&&&&&&&&&&&&&&&&    errrorrrr    ")
Ejemplo n.º 11
0
def auth_ip(request):
    # Get the IP of the current user, try and match it up to a session.
    current_ip = get_ip(request)

    # If there's a basic auth header, perform a check.
    basic_auth = request.META.get("HTTP_AUTHORIZATION")
    if basic_auth:
        # Check basic auth against LDAP as an alternative to SSO.
        username, password = request.META["HTTP_AUTHORIZATION"].split(
            " ", 1)[1].strip().decode('base64').split(":", 1)
        ldapauth = LDAPBackend()
        if username.find("@") > -1:
            username = DepartmentUser.objects.get(
                email__iexact=username).username
        user = ldapauth.authenticate(username=username,
                                     password=password)
        if not user:
            us = UserSession.objects.filter(user__username=username)[0]
            assert us.shared_id == password
            user = us.user

        if user:
            response = HttpResponse(json.dumps(
                {'email': user.email, 'client_logon_ip': current_ip}))
            response["X-email"] = user.email
            response["X-client-logon-ip"] = current_ip
            return response

    # If user is using SSO, do a normal auth check.
    if request.user.is_authenticated():
        return auth(request)

    # We can assume that the Session and UserSession tables only contain
    # current sessions.
    qs = UserSession.objects.filter(
        session__isnull=False,
        ip=current_ip).order_by("-session__expire_date")

    headers = {'client_logon_ip': current_ip}

    if qs.exists():
        user = qs[0].user
        headers["email"] = user.email
        try:
            headers["kmi_roles"] = DepartmentUser.objects.get(
                email__iexact=user.email).extra_data.get("KMIRoles", '')
        except:
            headers["kmi_roles"] = ''

    response = HttpResponse(json.dumps(headers))
    for key, val in headers.iteritems():
        key = "X-" + key.replace("_", "-")
        response[key] = val

    return response
Ejemplo n.º 12
0
def auth_ip(request):
    # get the IP of the current user, try and match it up to a session
    current_ip = get_ip(request)

    # if there's a basic auth header, perform a check
    basic_auth = request.META.get("HTTP_AUTHORIZATION")
    if basic_auth:
        username, password = request.META["HTTP_AUTHORIZATION"].split(
            " ", 1)[1].strip().decode('base64').split(":", 1)
        ldapauth = LDAPBackend()
        if username.find("@") > -1:
            username = DepartmentUser.objects.get(
                email__iexact=username).username
        user = ldapauth.authenticate(username=username, password=password)
        if user:
            response = HttpResponse(
                json.dumps({
                    'email': user.email,
                    'client_logon_ip': current_ip
                }))
            response["X-email"] = user.email
            response["X-client-logon-ip"] = current_ip
            return response

    # if user is using SSO, do a normal auth check
    if request.user.is_authenticated():
        return auth(request)

    # we can assume that the Session and UserSession tables only contain current sessions
    qs = UserSession.objects.filter(
        session__isnull=False, ip=current_ip).order_by("-session__expire_date")

    headers = {'client_logon_ip': current_ip}

    if qs.exists():
        user = qs[0].user
        headers["email"] = user.email
        try:
            headers["kmi_roles"] = DepartmentUser.objects.get(
                email__iexact=user.email).extra_data.get("KMIRoles", '')
        except Exception as e:
            headers["kmi_roles"] = ''

    response = HttpResponse(json.dumps(headers))
    for key, val in headers.iteritems():
        key = "X-" + key.replace("_", "-")
        response[key] = val

    return response
Ejemplo n.º 13
0
def ldap_get_vaild(username=None, passwd=None):
    from django_auth_ldap.backend import LDAPBackend
    auth = LDAPBackend()
    user = auth.authenticate(username=username, password=passwd)
    return user
Ejemplo n.º 14
0
from django.test import TestCase

# Create your tests here.

from django_auth_ldap.backend import LDAPBackend
ldapobj = LDAPBackend()
user = ldapobj.authenticate('scott.lan','123456')
print user, 1

# import pdb; pdb.set_trace() # by scott
Ejemplo n.º 15
0
def ldap_get_vaild(username=None,passwd=None):
    from django_auth_ldap.backend import LDAPBackend
    auth = LDAPBackend()
    user = auth.authenticate(username=username,password=passwd)
    return user
Ejemplo n.º 16
0
class LdapBackend(object):
  """
  Authentication backend that uses LDAP to authenticate logins.
  The first user to login will become the superuser.
  """
  def __init__(self):
    # Delegate to django_auth_ldap.LDAPBackend
    self._backend = LDAPBackend()

    ldap_settings.AUTH_LDAP_SERVER_URI = desktop.conf.LDAP.LDAP_URL.get()
    if ldap_settings.AUTH_LDAP_SERVER_URI is None:
      LOG.warn("Could not find LDAP URL required for authentication.")
      return None

    if desktop.conf.LDAP.SEARCH_BIND_AUTHENTICATION.get():
      # New Search/Bind Auth
      base_dn = desktop.conf.LDAP.BASE_DN.get()
      user_name_attr = desktop.conf.LDAP.USERS.USER_NAME_ATTR.get()

      if desktop.conf.LDAP.BIND_DN.get():
        bind_dn = desktop.conf.LDAP.BIND_DN.get()
        ldap_settings.AUTH_LDAP_BIND_DN = bind_dn
        bind_password = desktop.conf.LDAP.BIND_PASSWORD.get()
        ldap_settings.AUTH_LDAP_BIND_PASSWORD = bind_password

      search_bind_results = LDAPSearch(base_dn,
          ldap.SCOPE_SUBTREE, "(" + user_name_attr + "=%(user)s)")

      ldap_settings.AUTH_LDAP_USER_SEARCH = search_bind_results
    else:
      nt_domain = desktop.conf.LDAP.NT_DOMAIN.get()
      if nt_domain is None:
        pattern = desktop.conf.LDAP.LDAP_USERNAME_PATTERN.get()
        pattern = pattern.replace('<username>', '%(user)s')
        ldap_settings.AUTH_LDAP_USER_DN_TEMPLATE = pattern
      else:
        # %(user)s is a special string that will get replaced during the authentication process
        ldap_settings.AUTH_LDAP_USER_DN_TEMPLATE = "%(user)s@" + nt_domain

    # Certificate-related config settings
    if desktop.conf.LDAP.LDAP_CERT.get():
      ldap_settings.AUTH_LDAP_START_TLS = desktop.conf.LDAP.USE_START_TLS.get()
      ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
      ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, desktop.conf.LDAP.LDAP_CERT.get())
    else:
      ldap_settings.AUTH_LDAP_START_TLS = False
      ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

  def authenticate(self, username=None, password=None):
    # Do this check up here, because the auth call creates a django user upon first login per user
    is_super = False
    if not UserProfile.objects.filter(creation_method=str(UserProfile.CreationMethod.EXTERNAL)).exists():
      # If there are no LDAP users already in the system, the first one will
      # become a superuser
      is_super = True
    elif User.objects.filter(username=username).exists():
      # If the user already exists, we shouldn't change its superuser
      # privileges. However, if there's a naming conflict with a non-external
      # user, we should do the safe thing and turn off superuser privs.
      existing_user = User.objects.get(username=username)
      existing_profile = get_profile(existing_user)
      if existing_profile.creation_method == str(UserProfile.CreationMethod.EXTERNAL):
        is_super = User.objects.get(username=username).is_superuser
    elif not desktop.conf.LDAP.CREATE_USERS_ON_LOGIN.get():
      return None

    try:
      user = self._backend.authenticate(username, password)
    except ImproperlyConfigured, detail:
      LOG.warn("LDAP was not properly configured: %s", detail)
      return None

    if user is not None and user.is_active:
      profile = get_profile(user)
      profile.creation_method = UserProfile.CreationMethod.EXTERNAL
      profile.save()
      user.is_superuser = is_super
      user = rewrite_user(user)

      default_group = get_default_user_group()
      if default_group is not None:
        user.groups.add(default_group)
        user.save()

      return user

    return None
Ejemplo n.º 17
0
Archivo: backend.py Proyecto: yjkim/hue
class LdapBackend(object):
  """
  Authentication backend that uses LDAP to authenticate logins.
  The first user to login will become the superuser.
  """
  def __init__(self):
    # Delegate to django_auth_ldap.LDAPBackend
    self._backend = LDAPBackend()

    ldap_settings.AUTH_LDAP_SERVER_URI = desktop.conf.LDAP.LDAP_URL.get()
    if ldap_settings.AUTH_LDAP_SERVER_URI is None:
      LOG.warn("Could not find LDAP URL required for authentication.")
      return None

    nt_domain = desktop.conf.LDAP.NT_DOMAIN.get()
    if nt_domain is None:
      pattern = desktop.conf.LDAP.LDAP_USERNAME_PATTERN.get()
      pattern = pattern.replace('<username>', '%(user)s')
      ldap_settings.AUTH_LDAP_USER_DN_TEMPLATE = pattern
    else:
      # %(user)s is a special string that will get replaced during the authentication process
      ldap_settings.AUTH_LDAP_USER_DN_TEMPLATE = "%(user)s@" + nt_domain

    # Certificate-related config settings
    if desktop.conf.LDAP.LDAP_CERT.get():
      ldap_settings.AUTH_LDAP_START_TLS = desktop.conf.LDAP.USE_START_TLS.get()
      ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
      ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, desktop.conf.LDAP.LDAP_CERT.get())
    else:
      ldap_settings.AUTH_LDAP_START_TLS = False
      ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

  def authenticate(self, username=None, password=None):
    # Do this check up here, because the auth call creates a django user upon first login per user
    is_super = False
    if not UserProfile.objects.filter(creation_method=str(UserProfile.CreationMethod.EXTERNAL)).exists():
      # If there are no LDAP users already in the system, the first one will
      # become a superuser
      is_super = True
    elif User.objects.filter(username=username).exists():
      # If the user already exists, we shouldn't change its superuser
      # privileges. However, if there's a naming conflict with a non-external
      # user, we should do the safe thing and turn off superuser privs.
      existing_user = User.objects.get(username=username)
      existing_profile = get_profile(existing_user)
      if existing_profile.creation_method == str(UserProfile.CreationMethod.EXTERNAL):
        is_super = User.objects.get(username=username).is_superuser
    elif not desktop.conf.LDAP.CREATE_USERS_ON_LOGIN.get():
      return None

    try:
      user = self._backend.authenticate(username, password)
    except ImproperlyConfigured, detail:
      LOG.warn("LDAP was not properly configured: %s", detail)
      return None

    if user is not None and user.is_active:
      profile = get_profile(user)
      profile.creation_method = UserProfile.CreationMethod.EXTERNAL
      profile.save()
      user.is_superuser = is_super
      user = rewrite_user(user)

      default_group = get_default_user_group()
      if default_group is not None:
        user.groups.add(default_group)
        user.save()

      return user

    return None
Ejemplo n.º 18
0
class LdapBackend(object):
    """
  Authentication backend that uses LDAP to authenticate logins.
  The first user to login will become the superuser.
  """
    def __init__(self):
        # Delegate to django_auth_ldap.LDAPBackend
        self._backend = LDAPBackend()

        ldap_settings.AUTH_LDAP_SERVER_URI = desktop.conf.LDAP.LDAP_URL.get()
        if ldap_settings.AUTH_LDAP_SERVER_URI is None:
            LOG.warn("Could not find LDAP URL required for authentication.")
            return None

        # New Search/Bind Auth
        base_dn = desktop.conf.LDAP.BASE_DN.get()
        user_name_attr = desktop.conf.LDAP.USERS.USER_NAME_ATTR.get()

        if desktop.conf.LDAP.BIND_DN.get():
            bind_dn = desktop.conf.LDAP.BIND_DN.get()
            ldap_settings.AUTH_LDAP_BIND_DN = bind_dn
            bind_password = desktop.conf.LDAP.BIND_PASSWORD.get()
            ldap_settings.AUTH_LDAP_BIND_PASSWORD = bind_password

        search_bind_results = LDAPSearch(base_dn, ldap.SCOPE_SUBTREE,
                                         "(" + user_name_attr + "=%(user)s)")

        ldap_settings.AUTH_LDAP_USER_SEARCH = search_bind_results

        # Certificate-related config settings
        if desktop.conf.LDAP.LDAP_CERT.get():
            ldap_settings.AUTH_LDAP_START_TLS = desktop.conf.LDAP.USE_START_TLS.get(
            )
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,
                            desktop.conf.LDAP.LDAP_CERT.get())
        else:
            ldap_settings.AUTH_LDAP_START_TLS = False
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

    def authenticate(self, username=None, password=None):
        # Do this check up here, because the auth call creates a django user upon first login per user
        is_super = False
        if not UserProfile.objects.filter(creation_method=str(
                UserProfile.CreationMethod.EXTERNAL)).exists():
            # If there are no LDAP users already in the system, the first one will
            # become a superuser
            is_super = True
        elif User.objects.filter(username=username).exists():
            # If the user already exists, we shouldn't change its superuser
            # privileges. However, if there's a naming conflict with a non-external
            # user, we should do the safe thing and turn off superuser privs.
            existing_user = User.objects.get(username=username)
            existing_profile = get_profile(existing_user)
            if existing_profile.creation_method == str(
                    UserProfile.CreationMethod.EXTERNAL):
                is_super = User.objects.get(username=username).is_superuser
        elif not desktop.conf.LDAP.CREATE_USERS_ON_LOGIN.get():
            return None

        try:
            user = self._backend.authenticate(username, password)
        except ImproperlyConfigured, detail:
            LOG.warn("LDAP was not properly configured: %s", detail)
            return None

        if user is not None and user.is_active:
            profile = get_profile(user)
            profile.creation_method = UserProfile.CreationMethod.EXTERNAL
            profile.save()
            user.is_superuser = is_super
            user = rewrite_user(user)

            default_group = get_default_user_group()
            if default_group is not None:
                user.groups.add(default_group)
                user.save()

            return user

        return None