def import_from_username(self, username, set_pi=False): ldap_backend = LDAPBackend() user = ldap_backend.populate_user(username) if set_pi: g = Group.objects.get(name=GroupConstants.VIP.value) user.groups.add(g)
def populate_db(self): connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) connection.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) filter_ = '(&(uid=*))' # Customize this if necessary. ldap_users = connection.search_s(settings.BASE_DN, ldap.SCOPE_SUBTREE, filter_) connection.unbind() for ldap_user in ldap_users: username = ldap_user[1]['uid'][0].decode('UTF-8') if not User.objects.filter(username=username).exists(): logger.info('Adding new user %s...' % username) user = LDAPBackend().populate_user( ldap_user[1]['uid'][0].decode('UTF-8')) user.is_active = True # Add a single group to the user. # When group information is not stored as part of the user info, # code needs to be modified. try: groups = ldap_user[1]['group'] except KeyError: logger.info( 'User could not be added to a group and won\'t be able to ' 'purchase anything.') continue groups = [g.decode('UTF-8') for g in groups] self.add_user_to_group(user, groups) user.save()
def handle_noargs(self, **options): # Get LDAP backend ldap = LDAPBackend() for user in User.objects.all(): # Check if user is an LDAP user if not user.has_usable_password(): # Populate user details print "Refreshing '" + user.username + "' ", if ldap.populate_user(user.username): print "Success!" # User found and populated # Make sure this account is activated user.is_active = True user.save() else: print "Not found" # User account not found in LDAP # This means that the user either no longer exists # or no longer has privilages to access the CMS # We must deactivate their account to prevent them # from recieving notification emails # Make sure this account is deactivated user.is_active = False user.save()
def form_valid(self, form): data = form.cleaned_data name = data.get('name', None) #barcode = data.get('barcode', None) if name is not None: user = None try: user = User.objects.get(username=name) except: ldapobj = LDAPBackend() user = ldapobj.populate_user(name) if user is not None and not user.is_anonymous(): print("%s -> True" % name) else: print("%s -> False" % name) user.save() account = None try: account = Account.objects.get(user=user) except: account = Account(user=user, balance=0) print("Creating %s" % user) #account.barcode = barcode account.save() messages.success(self.request, "Added %s" % user) return super(AccountCreateView, self).form_valid(form)
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 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})
def get_or_create_local_user(user): """ Create a local user if the username exists in the configured LDAP server. Returns the updated or newly created local django.contrib.auth.models.User """ warnings.warn('This is most likely going to be deprecated due to upcoming' 'demerger work', PendingDeprecationWarning) # instantiate the LDAPBackend model class # magically finds the LDAP server from settings.py ldap_backend = LDAPBackend() if user.find('@') != -1: ldap_user = _LDAPUser(ldap_backend, username="") result = ldap_user.connection.search_s( "dc=corporateict,dc=domain", scope=ldap_backend.ldap.SCOPE_SUBTREE, filterstr='(mail=' + user + ')', attrlist=[str("sAMAccountName").encode('ASCII')] ) if result: user = result[0][1]["sAMAccountName"][0].lower() else: return None try: user = User.objects.get(username=user) except User.DoesNotExist: user = ldap_backend.populate_user(user) return user
def get_or_create_local_user(user): """ Create a local user if the username exists in the configured LDAP server. Returns the updated or newly created local django.contrib.auth.models.User """ warnings.warn( 'This is most likely going to be deprecated due to upcoming' 'demerger work', PendingDeprecationWarning) # instantiate the LDAPBackend model class # magically finds the LDAP server from settings.py ldap_backend = LDAPBackend() if user.find('@') != -1: ldap_user = _LDAPUser(ldap_backend, username="") result = ldap_user.connection.search_s( "dc=corporateict,dc=domain", scope=ldap_backend.ldap.SCOPE_SUBTREE, filterstr='(mail=' + user + ')', attrlist=[str("sAMAccountName").encode('ASCII')]) if result: user = result[0][1]["sAMAccountName"][0].lower() else: return None try: user = User.objects.get(username=user) except User.DoesNotExist: user = ldap_backend.populate_user(user) return user
def migrate_local_to_ldap(self, request, queryset): backend = LDAPBackend() for user in queryset: # annotate with ldap_user user = backend.get_user(user.pk) try: if user.ldap_user.dn is not None: # replace local password with an invalid one user.password = hashers.make_password(None) user.save(update_fields="password") # populate local record with LDAP values user.ldap_user.populate_user() else: self.message_user( request, _("Did not find matching LDAP record for {user}"). format(user=user.username), messages.WARNING, ) except Exception as e: logger.exception(f"User migration to LDAP account failed {e}") self.message_user( request, _("Failed to migrate {user}").format(user=user.username), messages.ERROR, )
def user_changed_hook(sender, **kwargs): username = kwargs['username'] logger.info("User Changed Hook: %s", username) user = LDAPBackend().populate_user(username) groups = set(user.ldap_user.group_names) ################################################################ # Kirby directory = Path(settings.KIRBY_ACCOUNTS_DIRECTORY) / username index_php = directory / "index.php" if groups & set([ 'genossenschaft', 'wettbewerb-jury', 'wettbewerb-externe', 'amsel-kollektiv', 'vorstand', 'mitarbeiterinnen', 'praktikantinnen' ]): if not os.path.exists(directory): os.mkdir(directory) index_php_content = KIRBY_TEMPLATE.format( fullname=user.get_full_name(), username=user.username, email=user.email, ) if not index_php.exists() or open( index_php).read() != index_php_content: with open(index_php, "w+") as fd: fd.write(index_php_content) logger.info("Created/Updated Kirby Login for %s", user.username) else: if directory.exists(): if index_php.exists(): index_php.unlink() directory.rmdir() logger.info("Deleted Kirby Login for %s", user.username)
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
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 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')
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 populate_db(self): con = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) con.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) filter_ = '(&(uid=*))' # customize this if necessary ldap_user = con.search_s(settings.BASE_DN, ldap.SCOPE_SUBTREE, filter_) con.unbind() for u in ldap_user: username = u[1]['uid'][0].decode('UTF-8') if not User.objects.filter(username=username).exists(): logger.info("Add new user '%s' from LDAP" % username) user = LDAPBackend().populate_user(u[1]['uid'][0].decode('UTF-8')) user.is_active = True # add a single group (wimi, stud, prof) to a user # has to be rewritten if group information is not stored per user # but instead each group in ldap stores its member! try: groups = u[1]['group'] # customize this except KeyError: logger.info( "User could not be added to a group and won't be able to purchase anything." ) continue groups = [g.decode('UTF-8') for g in groups] self.add_user_to_group(user, groups) user.save()
def user_sync_handler(sender, **kwargs): instance = kwargs.pop('instance', None) created = kwargs.pop('created', None) backend = LDAPBackend() if sender == User: user = backend.get_user(instance.id) sync = SynchronisingUserAdapter(user) sync.synchronise(created)
def update_users(apps, schema_editor): """ Re-populate the users to set the `domain` field """ User = apps.get_model("users", "User") backend = LDAPBackend() for user in User.objects.all(): backend.populate_user(user.username)
def update_groups_from_ldap(self, request, queryset): backend = LDAPBackend() for user in queryset: ldap_user = backend.get_user(user.pk) try: ldap_user.ldap_user._mirror_groups() except Exception: # _mirror_groups fails when ldap_user is not Active, so delete all groups user.groups.clear()
def __new__(cls, *args, **kwargs): try: from django_auth_ldap.backend import ( LDAPBackend as LDAPBackend_, LDAPSettings, ) import ldap except ModuleNotFoundError as e: if getattr(e, "name") == "django_auth_ldap": logging.error( "LDAP authentication has been configured, but django-auth-ldap is not installed." ) # Try to import `ldap_config.py` # FIXME(jathan): Have this read from `django.conf.settings` instead vs. # another config file that has to be dropped inside of the Nautobot code # deployment. try: from nautobot.core import ldap_config except (ModuleNotFoundError, ImportError) as e: if getattr(e, "name") == "ldap_config": logging.error( "LDAP configuration file not found: Check that ldap_config.py has been created." ) ldap_config = None # Once we've asserted that imports/settings work, set this backend as # usable. try: getattr(ldap_config, "AUTH_LDAP_SERVER_URI") except AttributeError: logging.error( "Required parameter AUTH_LDAP_SERVER_URI is missing from ldap_config.py." ) else: cls.is_usable = True # If the LDAP dependencies aren't set/working, just return a dummy # backend and soft fail. if not cls.is_usable: return DummyBackend() # Create a new instance of django-auth-ldap's LDAPBackend obj = LDAPBackend_() # Read LDAP configuration parameters from ldap_config.py instead of settings.py settings = LDAPSettings() for param in dir(ldap_config): if param.startswith(settings._prefix): setattr(settings, param[10:], getattr(ldap_config, param)) obj.settings = settings # Optionally disable strict certificate checking if getattr(ldap_config, "LDAP_IGNORE_CERT_ERRORS", False): ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) return obj
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)
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
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
def reset_ldap_password(username): """ Set the user's ldap password to something that can never be entered, effectively locking the account. We do not sync these passwords from django, because django_auth_ldap sets all new accounts to these passwords. """ from django_ldap_pixiedust.user import SynchronisingUserAdapter backend = LDAPBackend() user = User.objects.get(username=username) ldap_user = backend.get_user(user.id) sync = SynchronisingUserAdapter(ldap_user) sync.reset_ldap_password()
def import_all_users(self): ldap_backend = LDAPBackend() ldap_user = _LDAPUser(ldap_backend, username="") ldap_search = LDAPSearch(self.search_dn, ldap.SCOPE_SUBTREE, filterstr=self.filter, attrlist=[self.username_attribute]) results = ldap_search.execute(connection=ldap_user.connection) for result in results: if self.simple_search: search_term = result[1][self.username_attribute][0] else: search_term = result[0].split(',')[0].split('=')[1] ldap_backend.populate_user(search_term)
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
def validate_request(data, expires=600): """ validates a dictionary of request data and returns a User, ApplicationLink and token expiry time """ from swingers.sauth.models import ApplicationLink # sanity check the dictionary for key in ["client_id", "client_secret", "user_id"]: if not key in data: raise Exception("Missing Input") # set default expiry to 10 mins unless specified # 0 means never expires if "expires" in data: expires = int(data["expires"]) # Try and find the user for the user_id ldapbackend = LDAPBackend() user = data["user_id"] if User.objects.filter(username=user): user = User.objects.get(username=user) else: try: ldapbackend.populate_user(user) user = User.objects.get(username=user) except: raise Exception("Invalid user_id") # Try and find the client_id try: link = ApplicationLink.objects.get(client_name=data["client_id"], server_name=settings.SERVICE_NAME) except ApplicationLink.DoesNotExist: raise Exception("Application link does not exist") # Validate the secret if link.auth_method == ApplicationLink.AUTH_METHOD.basic: client_secret = link.secret elif "nonce" in data: if cache.get(link.secret) == data["nonce"]: raise Exception("No you can't reuse nonce's!") cache.set(link.secret, data["nonce"], expires) # client_secret should be hexdigest, hash algorithm selected based on # application link client_secret = link.get_client_secret(data["user_id"], data["nonce"]) else: raise Exception("Missing nonce") if not client_secret == data["client_secret"]: raise Exception("Invalid client_secret") return user, link, expires
def login(request): # pylint: disable=no-member body = json.loads(request.body) username = body['username'] password = body['password'] if username is None or password is None: return JsonResponse({'error': 'Contraseña o usuario vacío o nulo.'}, status=HTTP_400_BAD_REQUEST) try: user = User.objects.get(username=username) except User.DoesNotExist: return JsonResponse( { 'error': 'Error en ActasDB, usuario sin permisos en la aplicación.' }, status=HTTP_403_FORBIDDEN) user = LDAPBackend().authenticate(request, username=username, password=password) if not user: return JsonResponse( {'error': 'Error en LDAP, contraseña o usuario no válido.'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return JsonResponse({ 'token': token.key, 'group': user.groups.first().name }, status=HTTP_200_OK)
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 update_profile_data(request, employee): post_data = request.POST # check if this user exists message = '' # refreshing the data from AD user_data = LDAPBackend().populate_user(post_data['ldap-user-name']) user_profile = Profile.objects.filter(user=user_data) if not user_profile: user_profile = Profile(user=user_data) user_profile.supervisor = user_profile.user if employee.role == '2-OMAN': message = 'New Profile' else: message = 'Profile not yet created by HR' else: user_profile = user_profile[0] return { "user-profile": user_profile, "message": message, }
def creater_page(user): #Poblamos con el usuario de ldap usuario=LDAPBackend().populate_user(user) #Para los problemas de traducciones translation.activate(settings.LANGUAGE_CODE) #Para crear el namespace de la aplicacion a usar) neim = 'Blog'+str(user) usuario_config=aldryn_newsblog.cms_appconfig.NewsBlogConfig(namespace=neim,app_title=neim) #Guarda la nueva aplicacion usuario_config.save_base() #Pasos para la creacion de pagina #Para indicar el padre parent_menu=Page.objects.filter(title_set__title='Alumnos')[0] #Para crear la pagina pagina=create_page(usuario.username,'content.html','en',apphook='NewsBlogApp',apphook_namespace=usuario_config.namespace,parent=parent_menu,in_navigation=True,published=True) #Indicar un placeholder place=pagina.placeholders.get(slot="content") #Anhadir un plugin add_plugin(place,'TextPlugin','en',body='Prueba') #Configurar permisos de la pagina para un usuario #permisos=pagina.create_page_user(usuario.username,usuario.username,can_add_page=True,can_change_page=True,can_delete_page=True,can_add_pageuser=True,can_change_pageuser=True,can_delete_pageuser=True,grant_all=False) #Permisos para administracion de paginas permisos2=cms.api.assign_user_to_page(pagina,usuario,grant_all=False)
class LDAPSynchroniser(ldap.LDAPConnectionMixin): """ This provides complete database synchronisation - either from or to the LDAP server. This will synchronise every user and group. It's called by the "ldapsync" management command. """ def __init__(self): self.conn = self._get_connection() self.backend = LDAPBackend() def ldap_users(self): search = settings.ldap_settings.LDAP_PIXIEDUST_ALL_USERS for dn, attrs in search.execute(self.conn): user_id = attrs[ settings.ldap_settings.LDAP_PIXIEDUST_USERNAME_DN_ATTRIBUTE][0] yield _LDAPUser(self.backend, username=user_id) def model_users(self): return User.objects.all() def synchronise_from_ldap(self): deactivate() for user in self.ldap_users(): logger.debug("Synchronising %r" % repr(user)) user._get_or_create_user() activate_fromsettings() def synchronise_to_ldap(self): for user in self.model_users(): ldap_user = self.backend.get_user(user.id) sync = SynchronisingUserAdapter(ldap_user) logger.debug("Synchronising %r" % repr(user)) sync.synchronise_groups( ) # must happen first, because it clears groups! sync.synchronise() sync.synchronise_profile()
def contactImport(request): report = [] if request.method == 'POST': upnlist = request.POST.getlist('upn') for upn in upnlist: report.append((upn, LDAPBackend.populate_user(LDAPBackend(), upn))) else: upnlist = None if request.GET.get('filter') == None: filterform = ImportFilterForm() else: filterform = ImportFilterForm(request.GET) if filterform.is_valid(): ldapcon = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) ldapcon.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) search = settings.AUTH_LDAP_USER_FILTER res = search.execute(ldapcon, {'filter': filterform.cleaned_data['filter']}) ldapcon.unbind_s() # sort by last name, then first name res = sorted(res, key = lambda (dn,attr): attr['sn'][0] + attr['givenName'][0]) else: res = None return render(request, 'ldaplink/contactImport.html', { 'filterform': filterform, 'ldapresult': res, 'report': report, })
class LDAPSynchroniser(ldap.LDAPConnectionMixin): """ This provides complete database synchronisation - either from or to the LDAP server. This will synchronise every user and group. It's called by the "ldapsync" management command. """ def __init__(self): self.conn = self._get_connection() self.backend = LDAPBackend() def ldap_users(self): search = settings.ldap_settings.LDAP_PIXIEDUST_ALL_USERS for dn, attrs in search.execute(self.conn): user_id = attrs[settings.ldap_settings.LDAP_PIXIEDUST_USERNAME_DN_ATTRIBUTE][0] yield _LDAPUser(self.backend, username=user_id) def model_users(self): return User.objects.all() def synchronise_from_ldap(self): deactivate() for user in self.ldap_users(): logger.debug("Synchronising %r" % repr(user)) user._get_or_create_user() activate_fromsettings() def synchronise_to_ldap(self): for user in self.model_users(): ldap_user = self.backend.get_user(user.id) sync = SynchronisingUserAdapter(ldap_user) logger.debug("Synchronising %r" % repr(user)) sync.synchronise_groups() # must happen first, because it clears groups! sync.synchronise() sync.synchronise_profile()
def find_inactive_user(self): for user in User.objects.filter(is_active=True): ldap_user = LDAPBackend().populate_user(user.username) if ldap_user is None and not user.is_superuser: logger.info("User '%s' was set to inactive." % user) user.is_active = False user.save()
def authenticate(self, username, password): user = None try: user = LDAPBackend.authenticate(self, username, password) except Exception, e: LOG.exception(e)
def create_profile(sender, instance, **kwargs): try: if kwargs['created']: user_profile = UserProfile.objects.create(user=instance) user = LDAPBackend().populate_user(instance.username) if user: try: empresa = user.ldap_user.attrs['empresa'][0] except: empresa = '' matricula = 0 uid = user.ldap_user.attrs['uid'][0] displayname = user.ldap_user.attrs['displayname'][0] departmentnumber = user.ldap_user.attrs['departmentnumber'][0] cpf = user.ldap_user.attrs['cpf'][0] mail = user.ldap_user.attrs['mail'][0] user_profile.usuario = uid user_profile.matricula = matricula user_profile.nome = displayname user_profile.cr = departmentnumber user_profile.cpf = cpf user_profile.empresa = empresa user_profile.email = mail user_profile.save() except Exception as e: print('Erro Projeto[Model]=create_profile: ' +str(e))
def impersonate(request, user): managed_users = LDAP().managed_users(request.user.username) if user not in {x['username'] for x in managed_users} \ and not request.user.is_superuser: return HttpResponse('Permission denied', status=403) new_user = LDAPBackend().populate_user(user) if not new_user: return HttpResponse('Not found', status=404) logger.info(f"Impersonating {new_user}") messages.add_message(request, messages.SUCCESS, f"Du bist ab sofort als '{new_user.username}' angemeldet.") prev_path = request.META.get('HTTP_REFERER') if prev_path: request.session['_impersonate_prev_path'] = \ request.build_absolute_uri(prev_path) request.session['_impersonate'] = new_user.pk request.session.modified = True # Let's make sure... # can be used to hook up auditing of the session session_begin.send( sender=None, impersonator=request.user, impersonating=new_user, request=request ) return HttpResponseRedirect(request.POST.get('next') or prev_path or '/')
class Command(BaseCommand): help = "Ensures the Solr indexes are ready for EDD to use." backend = LDAPBackend() study_core = solr.StudySearch() user_core = solr.UserSearch() measurement_core = solr.MeasurementTypeSearch() def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) def add_arguments(self, parser): # Add all parent arguments super(Command, self).add_arguments(parser) parser.add_argument( "--force", action="store_true", default=False, dest="force", help="Forces a re-index", ) def handle(self, *args, **options): self.stdout.write("Checking user index") if options["force"] or len(self.user_core) == 0: users_qs = self.user_core.get_queryset() self.user_core.swap().clear() user_updates = map(self._copy_groups, users_qs) self.stdout.write(f"Indexing {users_qs.count()} users") self.user_core.update(user_updates) self.user_core.swap_execute() self.stdout.write("Checking studies index") if options["force"] or len(self.study_core) == 0: study_qs = self.study_core.get_queryset() self.study_core.swap().clear() self.stdout.write(f"Indexing {study_qs.count()} studies") self.study_core.update(study_qs) self.study_core.swap_execute() self.stdout.write("Checking metabolite index") if options["force"] or len(self.measurement_core) == 0: metabolite_qs = solr.MeasurementTypeSearch.get_queryset() self.measurement_core.swap().clear() self.stdout.write(f"Indexing {metabolite_qs.count()} metabolites") self.measurement_core.update(metabolite_qs) self.measurement_core.swap_execute() def _copy_groups(self, user): # Normally should use the following line: # user = self.backend.get_user(user.pk) # ... but this will save a database query _LDAPUser(self.backend, user=user) try: user.ldap_user._mirror_groups() except Exception: # _mirror_groups fails when ldap_user is not Active user.groups.clear() return user
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
def _get_profile_user(username): '''Find the :class:`~django.contrib.auth.models.User` and :class:`~openemory.accounts.models.UserProfile` for a specified username, for use in profile pages. The specified ``username`` must exist as an :class:`~openemory.accounts.models.EsdPerson`; if the corresponding :class:`~openemory.accounts.models.UserProfile` does not yet exist, it will be initialized from LDAP. Raises a :class:`django.http.Http404` if any of the models cannot be found or created. Helper method for profile views (:meth:`rdf_profile` and :meth:`profile`). ''' # FIXME: It made sense in the past to require an EsdPerson for every # User/UserProfile. As of 2012-03-06, this shouldn't be so important. # At some point we should make this work if the User and UserProfile # exist (assuming profile.has_profile_page()) even if the EsdPerson # doesn't. # retrieve the ESD db record for the requested user esdperson = get_object_or_404(EsdPerson, netid=username.upper()) # get the corresponding local profile & user try: profile = esdperson.profile() user = profile.user # 404 if the user exists but should not have a profile page # (check against UserProfile if there is one, for local profile override) if not profile.has_profile_page(): raise Http404 except UserProfile.DoesNotExist: # if local account doesn't exist, make sure ESD indicates the # user should have a profile before proceeding if not esdperson.has_profile_page(): raise Http404 # local account doesn't exist but user should have a profile: # attempt to init local user & profile backend = EmoryLDAPBackend() user_dn, user = backend.find_user(username) if not user: raise Http404 profile = user.userprofile return user, profile
def create_account(self): uname = create_login_credentials(self) pprint("Creating account for "+uname) dn = create_ad_account(self, uname) if dn is not False: add_to_ad_group(group_dn=settings.LIPAD_LDAP_GROUP_DN, user_dn=dn) profile = LDAPBackend().populate_user(uname) profile.organization_type = self.organization_type profile.save() if profile is None: pprint("Account was not created") raise Http404 self.update_profile_details(uname=uname, profile = profile) else: raise Http404
def init_ldap_user(request): '''Use django-auth-ldap to initialize a new user account from LDAP.''' netid = request.POST.get('netid', None) if netid is None: messages.error(request, 'No netid found in request') else: # use django-auth-ldap to create an ldap-based user acccount user = LDAPBackend().populate_user(netid) if user is None: messages.error(request, 'User %s not found' % netid) else: # NOTE: using "populate" here because could be a new # record OR an updated one messages.success(request, 'Populated user %s (%s)' % \ (netid, user.get_full_name())) # redirect to user changelist app, model = settings.AUTH_USER_MODEL.lower().split('.') location = reverse('admin:%s_%s_changelist' % (app, model)) return HttpResponseSeeOtherRedirect(location)
def handle(self, *args, **kwargs): if len(args) <= 0: return for arg in args: ldapobj = LDAPBackend() user = ldapobj.populate_user(arg) if user is not None and not user.is_anonymous(): self.stdout.write("%s -> True" % arg) else: self.stdout.write("%s -> False" % arg) account = Account.objects.filter(user=user) if len(account) == 1: self.stdout.write("Reconciling %s ... " % user, ending='') #We have an account. account[0].reconcile() account[0].save() self.stdout.write("$ %s / due %s" % (account[0].balance_dollars, account[0].special_due)) else: self.stdout.write("Creating %s" % user) account = Account(user=user, balance=0) account.save()
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 get_attributes(user, definitions=None, source=None, **kwargs): ''' Return attributes dictionnary Dictionnary format: attributes = dict() data_from_source = list() a1 = dict() a1['oid'] = definition_name Or a1['definition'] = definition_name definition may be the definition name like 'gn' or an alias like 'givenName' Or a1['name'] = attribute_name_in_ns a1['namespace'] = ns_name a1['values'] = list_of_values data_from_source.append(a1) ... data_from_source.append(a2) attributes[source_name] = data_from_source First attempt on 'definition' key. Else, definition is searched by 'name' and 'namespece' keys. ''' if not user: logger.error('get_attributes: No user provided') return None logger.debug('get_attributes: Searching attributes for user %s' \ % user) from authentic2.attribute_aggregator.models import LdapSource sources = None if source: logger.debug('get_attributes: The required source is %s' % source) try: sources = [source.ldapsource] logger.debug('get_attributes: The source is an LDAP source!') except: logger.debug('get_attributes: \ The required source is not a LDAP one') return None else: sources = LdapSource.objects.all() if not sources: logger.debug('get_attributes: No LDAP source configured') return None attributes = dict() for source in sources: logger.debug('get_attributes: The LDAP source is known as %s' \ % source.name) identifier = None ''' Check if the user is authenticated by LDAP. If it is, grab the user dn from the LDAPUser object ''' try: from django_auth_ldap.backend import LDAPBackend backend = LDAPBackend() u = backend.get_user(user.id) dn = u.ldap_user.dn if not dn: logger.debug('get_attributes: \ User not logged with LDAP') else: logger.debug('get_attributes: \ User logged with dn %s' % dn) '''is it logged in that source?''' logger.debug('get_attributes: \ Is the user logged with the source %s?' % source.name) try: l = ldap.open(source.server) l.protocol_version = ldap.VERSION3 username = source.user password = source.password if username and password: l.simple_bind(username, password) ldap_result_id = \ l.search(dn, ldap.SCOPE_BASE, attrlist=['objectClass']) result_type, result_data = l.result(ldap_result_id, 0) logger.debug('get_attributes: Yes it is, result %s %s' \ % (result_type, result_data)) identifier = dn except ldap.LDAPError, err: logger.debug('get_attributes: \ User dn %s unknown in %s or error %s' \ % (dn, source.name, str(err))) except Exception, err: logger.error('get_attributes: \ Error working with the LDAP backend %s' %str(err)) if not identifier: identifier = get_user_alias_in_source(user, source) if not identifier: logger.error('get_attributes: \ No user identifier known into that source') else: logger.debug('get_attributes: \ the user is known as %s in source %s' \ % (identifier, source.name)) try: l = ldap.open(source.server) l.protocol_version = ldap.VERSION3 username = source.user password = source.password if username and password: l.simple_bind(username, password) except ldap.LDAPError, err: logger.error('get_attributes: \ an error occured at binding due to %s' % err) else:
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
#!/usr/bin/env python3 from django_auth_ldap.backend import LDAPBackend ''' SNS LDAP Authentication python manage.py shell ''' username = "******" ldapobj = LDAPBackend() user = ldapobj.populate_user(username) print(user.email) # ERROR: # [12/Jun/2015 14:15:19] WARNING [django_auth_ldap:396] Caught LDAPError while authenticating rhf: SERVER_DOWN({'info': '(unknown error code)', 'desc': "Can't contact LDAP server"},) if user is None: print("1st try failed!") ldapobj.ldap.set_option(ldapobj.ldap.OPT_X_TLS_REQUIRE_CERT, ldapobj.ldap.OPT_X_TLS_NEVER) user = ldapobj.populate_user(username) print(user.is_anonymous())
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
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
def __init__(self): self.conn = self._get_connection() self.backend = LDAPBackend()