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
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 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 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 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 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 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 '/')
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 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 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 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 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 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)
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 __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 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 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 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()
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 get_queryset(self): if settings.LDAP_ENABLED and 'username' in self.request.query_params: if LDAPBackend is None: raise StackdioConfigException('LDAP is enabled, but django_auth_ldap isn\'t ' 'installed. Please install django_auth_ldap') # Try populating the user first LDAPBackend().populate_user(self.request.query_params['username']) return super(UserListAPIView, self).get_queryset()
def _find_inactive_users(): for user in User.objects.filter(is_active=True): ldap_user = LDAPBackend().populate_user(user.username) if ldap_user is None: user.is_active = False user.save() logger.info(f'User {user.username} was set to inactive.')
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 clean_old_password(self): from django_auth_ldap.backend import LDAPBackend old_password = self.cleaned_data["old_password"] u = LDAPBackend().authenticate(self.user.username, old_password) if u is None: raise forms.ValidationError(_("Incorrect password")) return old_password
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 populate_members(): """fetch all members, sort them and populate the Django database""" for m in sorted(all_members()): member = LDAPBackend().populate_user(m) if member: print('Populated: %s' % member) else: print('Not found: %s' % m)
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 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 handle(self, *args, **options): filter_string = options.get('filter', DEFAULT_FILTER) ldap_backend = LDAPBackend() ldap_user = _LDAPUser(backend=ldap_backend, username='') ldap_connection = ldap_user.connection # Initialize the LDAP controls for paging. # Note that we pass '' for the cookie because on first iteration, it starts out empty. ldap_controls = SimplePagedResultsControl(True, size=PAGE_SIZE, cookie='') while True: # Send search request # If you leave out the ATTRLIST it'll return all attributes which you have permissions to access. # You may want to adjust the scope level as well # (perhaps "ldap.SCOPE_SUBTREE", but it can reduce performance if you don't need it). message_id = ldap_connection.search_ext( base=settings.AUTH_LDAP_USER_SEARCH.base_dn, scope=ldap.SCOPE_SUBTREE, filterstr=filter_string, serverctrls=[ldap_controls]) # Pull the results from the search request rtype, rdata, rmsgid, server_controls = ldap_connection.result3( message_id) rdata = settings.AUTH_LDAP_USER_SEARCH._process_results(rdata) # Each "rdata" is a tuple of the form (dn, attrs), where dn is a string containing the # DN (distinguished name) of the entry, and attrs is a dictionary containing the attributes associated # with the entry. The keys of attrs are strings, and the associated values are lists of strings. for distinguished_name, attributes in rdata: username = "".join(attributes['uid']) print(f"{username} \t| {distinguished_name}") print(attributes) # Look through the returned controls and find the page controls. # This will also have our returned cookie which we need to make the next search request. page_controls = [ control for control in server_controls if control.controlType == SimplePagedResultsControl.controlType ] if not page_controls: print('Warning: Server ignores RFC 2696 control.') break # Ok, we did find the page control, yank the cookie from it and insert it into the control for our # next search. If however there is no cookie, we are done! cookie = page_controls[0].cookie ldap_controls.cookie = cookie if not cookie: break