• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.get_profile函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中useradmin.models.get_profile函数的典型用法代码示例。如果您正苦于以下问题:Python get_profile函数的具体用法?Python get_profile怎么用?Python get_profile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_profile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_useradmin_ldap_integration

def test_useradmin_ldap_integration():
    reset_all_users()
    reset_all_groups()

    # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection
    ldap_access.CACHED_LDAP_CONN = LdapTestConnection()

    # Try importing a user
    import_ldap_user("larry", import_by_dn=False)
    larry = User.objects.get(username="larry")
    assert_true(larry.first_name == "Larry")
    assert_true(larry.last_name == "Stooge")
    assert_true(larry.email == "[email protected]")
    assert_true(get_profile(larry).creation_method == str(UserProfile.CreationMethod.EXTERNAL))

    # Should be a noop
    sync_ldap_users()
    sync_ldap_groups()
    assert_equal(len(User.objects.all()), 1)
    assert_equal(len(Group.objects.all()), 0)

    # Should import a group, but will only sync already-imported members
    import_ldap_group("Test Administrators", import_members=False, import_by_dn=False)
    assert_equal(len(User.objects.all()), 1)
    assert_equal(len(Group.objects.all()), 1)
    test_admins = Group.objects.get(name="Test Administrators")
    assert_equal(len(test_admins.user_set.all()), 1)
    assert_equal(test_admins.user_set.all()[0].username, larry.username)

    # Import all members of TestUsers
    import_ldap_group("TestUsers", import_members=True, import_by_dn=False)
    test_users = Group.objects.get(name="TestUsers")
    assert_true(LdapGroup.objects.filter(group=test_users).exists())
    assert_equal(len(test_users.user_set.all()), 3)

    ldap_access.CACHED_LDAP_CONN.remove_user_group_for_test("moe", "TestUsers")
    import_ldap_group("TestUsers", import_members=False, import_by_dn=False)
    assert_equal(len(test_users.user_set.all()), 2)
    assert_equal(len(User.objects.get(username="moe").groups.all()), 0)

    ldap_access.CACHED_LDAP_CONN.add_user_group_for_test("moe", "TestUsers")
    import_ldap_group("TestUsers", import_members=False, import_by_dn=False)
    assert_equal(len(test_users.user_set.all()), 3)
    assert_equal(len(User.objects.get(username="moe").groups.all()), 1)

    # Make sure that if a Hue user already exists with a naming collision, we
    # won't overwrite any of that user's information.
    hue_user = User.objects.create(username="otherguy", first_name="Different", last_name="Guy")
    import_ldap_user("otherguy", import_by_dn=False)
    hue_user = User.objects.get(username="otherguy")
    assert_equal(get_profile(hue_user).creation_method, str(UserProfile.CreationMethod.HUE))
    assert_equal(hue_user.first_name, "Different")

    # Make sure Hue groups with naming collisions don't get marked as LDAP groups
    hue_group = Group.objects.create(name="OtherGroup")
    hue_group.user_set.add(hue_user)
    hue_group.save()
    import_ldap_group("OtherGroup", import_members=False, import_by_dn=False)
    assert_false(LdapGroup.objects.filter(group=hue_group).exists())
    assert_true(hue_group.user_set.filter(username=hue_user.username).exists())
开发者ID:kthguru,项目名称:hue,代码行数:60,代码来源:tests.py


示例2: test_useradmin_ldap_user_integration

def test_useradmin_ldap_user_integration():
  reset_all_users()
  reset_all_groups()

  # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection
  ldap_access.CACHED_LDAP_CONN = LdapTestConnection()

  # Try importing a user
  import_ldap_users('larry', import_by_dn=False)
  larry = User.objects.get(username='larry')
  assert_true(larry.first_name == 'Larry')
  assert_true(larry.last_name == 'Stooge')
  assert_true(larry.email == '[email protected]')
  assert_true(get_profile(larry).creation_method == str(UserProfile.CreationMethod.EXTERNAL))

  # Should be a noop
  sync_ldap_users()
  sync_ldap_groups()
  assert_equal(len(User.objects.all()), 1)
  assert_equal(len(Group.objects.all()), 0)

  # Make sure that if a Hue user already exists with a naming collision, we
  # won't overwrite any of that user's information.
  hue_user = User.objects.create(username='otherguy', first_name='Different', last_name='Guy')
  import_ldap_users('otherguy', import_by_dn=False)
  hue_user = User.objects.get(username='otherguy')
  assert_equal(get_profile(hue_user).creation_method, str(UserProfile.CreationMethod.HUE))
  assert_equal(hue_user.first_name, 'Different')
开发者ID:joey,项目名称:hue,代码行数:28,代码来源:tests.py


示例3: update_user

  def update_user(self, user, attributes, attribute_mapping, force_save=False):
    # 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=user.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.
      user = User.objects.get(username=user.username)
      existing_profile = get_profile(user)
      if existing_profile.creation_method == str(UserProfile.CreationMethod.EXTERNAL):
        is_super = user.is_superuser

    user = super(SAML2Backend, self).update_user(user, attributes, attribute_mapping, force_save)

    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
开发者ID:chiehwen,项目名称:hue,代码行数:33,代码来源:backend.py


示例4: test_group_permissions

def test_group_permissions():
    reset_all_users()
    reset_all_groups()

    # Get ourselves set up with a user and a group
    c = make_logged_in_client(username="test", is_superuser=True)
    Group.objects.create(name="test-group")
    test_user = User.objects.get(username="test")
    test_user.groups.add(Group.objects.get(name="test-group"))
    test_user.save()

    # Make sure that a superuser can always access applications
    response = c.get("/useradmin/users")
    assert_true("Hue Users" in response.content)

    assert_true(len(GroupPermission.objects.all()) == 0)
    c.post(
        "/useradmin/groups/edit/test-group",
        dict(
            name="test-group",
            members=[User.objects.get(username="test").pk],
            permissions=[HuePermission.objects.get(app="useradmin", action="access").pk],
            save="Save",
        ),
        follow=True,
    )
    assert_true(len(GroupPermission.objects.all()) == 1)

    # Now test that we have limited access
    c1 = make_logged_in_client(username="nonadmin", is_superuser=False)
    response = c1.get("/useradmin/users")
    assert_true("You do not have permission to access the Useradmin application." in response.content)

    # Add the non-admin to a group that should grant permissions to the app
    test_user = User.objects.get(username="nonadmin")
    test_user.groups.add(Group.objects.get(name="test-group"))
    test_user.save()

    # Check that we have access now
    response = c1.get("/useradmin/users")
    assert_true(get_profile(test_user).has_hue_permission("access", "useradmin"))
    assert_true("Hue Users" in response.content)

    # Make sure we can't modify permissions
    response = c1.get("/useradmin/permissions/edit/useradmin/access")
    assert_true("must be a superuser to change permissions" in response.content)

    # And revoke access from the group
    c.post(
        "/useradmin/permissions/edit/useradmin/access",
        dict(app="useradmin", priv="access", groups=[], save="Save"),
        follow=True,
    )
    assert_true(len(GroupPermission.objects.all()) == 0)
    assert_false(get_profile(test_user).has_hue_permission("access", "useradmin"))

    # We should no longer have access to the app
    response = c1.get("/useradmin/users")
    assert_true("You do not have permission to access the Useradmin application." in response.content)
开发者ID:kthguru,项目名称:hue,代码行数:59,代码来源:tests.py


示例5: test_useradmin_ldap_user_integration

def test_useradmin_ldap_user_integration():
  done = []
  try:
    reset_all_users()
    reset_all_groups()

    # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection
    ldap_access.CACHED_LDAP_CONN = LdapTestConnection()

    # Try importing a user
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'lårry', sync_groups=False, import_by_dn=False)
    larry = User.objects.get(username='lårry')
    assert_true(larry.first_name == 'Larry')
    assert_true(larry.last_name == 'Stooge')
    assert_true(larry.email == '[email protected]')
    assert_true(get_profile(larry).creation_method == str(UserProfile.CreationMethod.EXTERNAL))

    # Should be a noop
    sync_ldap_users(ldap_access.CACHED_LDAP_CONN)
    sync_ldap_groups(ldap_access.CACHED_LDAP_CONN)
    assert_equal(User.objects.all().count(), 1)
    assert_equal(Group.objects.all().count(), 0)

    # Make sure that if a Hue user already exists with a naming collision, we
    # won't overwrite any of that user's information.
    hue_user = User.objects.create(username='otherguy', first_name='Different', last_name='Guy')
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'otherguy', sync_groups=False, import_by_dn=False)
    hue_user = User.objects.get(username='otherguy')
    assert_equal(get_profile(hue_user).creation_method, str(UserProfile.CreationMethod.HUE))
    assert_equal(hue_user.first_name, 'Different')

    # Make sure LDAP groups exist or they won't sync
    import_ldap_groups(ldap_access.CACHED_LDAP_CONN, 'TestUsers', import_members=False, import_members_recursive=False, sync_users=False, import_by_dn=False)
    import_ldap_groups(ldap_access.CACHED_LDAP_CONN, 'Test Administrators', import_members=False, import_members_recursive=False, sync_users=False, import_by_dn=False)
    # Try importing a user and sync groups
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'curly', sync_groups=True, import_by_dn=False)
    curly = User.objects.get(username='curly')
    assert_equal(curly.first_name, 'Curly')
    assert_equal(curly.last_name, 'Stooge')
    assert_equal(curly.email, '[email protected]')
    assert_equal(get_profile(curly).creation_method, str(UserProfile.CreationMethod.EXTERNAL))
    assert_equal(2, curly.groups.all().count(), curly.groups.all())

    reset_all_users()
    reset_all_groups()
  finally:
    for finish in done:
      finish()
开发者ID:neiodavince,项目名称:hue,代码行数:48,代码来源:test_ldap_deprecated.py


示例6: dt_login

def dt_login(request):
  redirect_to = request.REQUEST.get('next', '/')
  is_first_login_ever = first_login_ever()
  backend_names = get_backend_names()
  is_active_directory = 'LdapBackend' in backend_names and ( bool(LDAP.NT_DOMAIN.get()) or bool(LDAP.LDAP_SERVERS.get()) )

  if is_active_directory:
    UserCreationForm = auth_forms.LdapUserCreationForm
    AuthenticationForm = auth_forms.LdapAuthenticationForm
  else:
    UserCreationForm = auth_forms.UserCreationForm
    AuthenticationForm = auth_forms.AuthenticationForm

  if request.method == 'POST':
    request.audit = {
      'operation': 'USER_LOGIN',
      'username': request.POST.get('username')
    }

    # For first login, need to validate user info!
    first_user_form = is_first_login_ever and UserCreationForm(data=request.POST) or None
    first_user = first_user_form and first_user_form.is_valid()

    if first_user or not is_first_login_ever:
      auth_form = AuthenticationForm(data=request.POST)

      if auth_form.is_valid():
        # Must login by using the AuthenticationForm.
        # It provides 'backends' on the User object.
        user = auth_form.get_user()
        userprofile = get_profile(user)

        login(request, user)

        if request.session.test_cookie_worked():
          request.session.delete_test_cookie()

        if is_first_login_ever or 'AllowAllBackend' in backend_names or 'LdapBackend' in backend_names:
          # Create home directory for first user.
          try:
            ensure_home_directory(request.fs, user.username)
          except (IOError, WebHdfsException), e:
            LOG.error(_('Could not create home directory.'), exc_info=e)
            request.error(_('Could not create home directory.'))

        if require_change_password(userprofile):
          return HttpResponseRedirect(urlresolvers.reverse('useradmin.views.edit_user', kwargs={'username': user.username}))

        userprofile.first_login = False
        userprofile.save()

        msg = 'Successful login for user: %s' % user.username
        request.audit['operationText'] = msg
        access_warn(request, msg)
        return HttpResponseRedirect(redirect_to)
      else:
        request.audit['allowed'] = False
        msg = 'Failed login for user: %s' % request.POST.get('username')
        request.audit['operationText'] = msg
        access_warn(request, msg)
开发者ID:shobull,项目名称:hue,代码行数:60,代码来源:views.py


示例7: check_auth

  def check_auth(self, username, password):
    if pam.authenticate(username, password, desktop.conf.AUTH.PAM_SERVICE.get()):
      is_super = False
      if User.objects.count() == 0:
        is_super = True

      try:
        user = User.objects.get(username=username)
      except User.DoesNotExist:
        user = find_or_create_user(username, 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

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

          user.save()

      user = rewrite_user(user)
      return user

    return None
开发者ID:9629831527,项目名称:hue,代码行数:26,代码来源:backend.py


示例8: authenticate

  def authenticate(self, username=None, password=None, server=None):
    self.add_ldap_config_for_server(server)

    username_filter_kwargs = ldap_access.get_ldap_user_kwargs(username)

    # 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_filter_kwargs).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_filter_kwargs)
      existing_profile = get_profile(existing_user)
      if existing_profile.creation_method == str(UserProfile.CreationMethod.EXTERNAL):
        is_super = User.objects.get(**username_filter_kwargs).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
开发者ID:9629831527,项目名称:hue,代码行数:27,代码来源:backend.py


示例9: authenticate

  def authenticate(self, username, password):
    username = desktop.conf.AUTH.FORCE_USERNAME_LOWERCASE.get() and username.lower() or username

    if pam.authenticate(username, password, desktop.conf.AUTH.PAM_SERVICE.get()):
      is_super = False
      if User.objects.count() == 0:
        is_super = True

      try:
        if desktop.conf.AUTH.IGNORE_USERNAME_CASE.get():
          user = User.objects.get(username__iexact=username)
        else:
          user = User.objects.get(username=username)
      except User.DoesNotExist:
        user = find_or_create_user(username, 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

          ensure_has_a_group(user)

          user.save()

      user = rewrite_user(user)
      return user

    return None
开发者ID:alvarocantador,项目名称:hue,代码行数:29,代码来源:backend.py


示例10: authenticate

  def authenticate(self, access_token):
    username = access_token['screen_name']
    password = access_token['oauth_token_secret']

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:

    	if not UserProfile.objects.filter(creation_method=str(UserProfile.CreationMethod.EXTERNAL)).exists():
            is_super=True
    	else:
            is_super=False

      # Could save oauth_token detail in the user profile here
    	user = find_or_create_user(username, password)
    
    	profile = get_profile(user)
    	profile.creation_method = UserProfile.CreationMethod.EXTERNAL
    	profile.save()

    	user.is_superuser = is_super
    	user.save()

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

    return user
开发者ID:dominikgehl,项目名称:hue,代码行数:28,代码来源:backend.py


示例11: _import_ldap_user

def _import_ldap_user(username, import_by_dn=False):
  """
  Import a user from LDAP. If import_by_dn is true, this will import the user by
  the distinguished name, rather than the configured username attribute.
  """
  conn = ldap_access.get_connection()
  user_info = conn.find_user(username, import_by_dn)
  if user_info is None:
    LOG.warn("Could not get LDAP details for user %s" % (username,))
    return None

  user, created = User.objects.get_or_create(username=user_info['username'])
  profile = get_profile(user)
  if not created and profile.creation_method == str(UserProfile.CreationMethod.HUE):
    # This is a Hue user, and shouldn't be overwritten
    LOG.warn('There was a naming conflict while importing user %s' % (username,))
    return None

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

  if 'first' in user_info:
    user.first_name = user_info['first']
  if 'last' in user_info:
    user.last_name = user_info['last']
  if 'email' in user_info:
    user.email = user_info['email']

  profile.creation_method = UserProfile.CreationMethod.EXTERNAL
  profile.save()
  user.save()

  return user
开发者ID:DatalakeInc,项目名称:hortonworks-sandbox,代码行数:34,代码来源:views.py


示例12: test_useradmin_ldap_user_integration

def test_useradmin_ldap_user_integration():
  reset_all_users()
  reset_all_groups()

  # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection
  ldap_access.CACHED_LDAP_CONN = LdapTestConnection()

  # Try importing a user
  import_ldap_users('lårry', sync_groups=False, import_by_dn=False)
  larry = User.objects.get(username='lårry')
  assert_true(larry.first_name == 'Larry')
  assert_true(larry.last_name == 'Stooge')
  assert_true(larry.email == '[email protected]')
  assert_true(get_profile(larry).creation_method == str(UserProfile.CreationMethod.EXTERNAL))

  # Should be a noop
  sync_ldap_users()
  sync_ldap_groups()
  assert_equal(User.objects.all().count(), 1)
  assert_equal(Group.objects.all().count(), 0)

  # Make sure that if a Hue user already exists with a naming collision, we
  # won't overwrite any of that user's information.
  hue_user = User.objects.create(username='otherguy', first_name='Different', last_name='Guy')
  import_ldap_users('otherguy', sync_groups=False, import_by_dn=False)
  hue_user = User.objects.get(username='otherguy')
  assert_equal(get_profile(hue_user).creation_method, str(UserProfile.CreationMethod.HUE))
  assert_equal(hue_user.first_name, 'Different')

  # Try importing a user and sync groups
  import_ldap_users('curly', sync_groups=True, import_by_dn=False)
  curly = User.objects.get(username='curly')
  assert_equal(curly.first_name, 'Curly')
  assert_equal(curly.last_name, 'Stooge')
  assert_equal(curly.email, '[email protected]')
  assert_equal(get_profile(curly).creation_method, str(UserProfile.CreationMethod.EXTERNAL))
  assert_equal(2, curly.groups.all().count(), curly.groups.all())

  reset_all_users()
  reset_all_groups()

  # Test import case sensitivity
  reset = desktop.conf.LDAP.IGNORE_USERNAME_CASE.set_for_testing(True)
  import_ldap_users('Lårry', sync_groups=False, import_by_dn=False)
  assert_false(User.objects.filter(username='Lårry').exists())
  assert_true(User.objects.filter(username='lårry').exists())
  reset()
开发者ID:elisbyberi,项目名称:hue,代码行数:47,代码来源:tests.py


示例13: getuser

 def getuser(self, **options):
   try:
     return User.objects.get(id=1)
   except User.DoesNotExist:
     form = SuperUserChangeForm(
       {
         "username": DEFAULT_USER.get(),
         "password1": DEFAULT_USER_PASSWORD.get(),
         "password2": DEFAULT_USER_PASSWORD.get(),
         "ensure_home_directory": True,
         "is_active": True,
         "is_superuser": True,
       }
     )
     instance = form.save()
     get_profile(instance)
     return User.objects.get(username=DEFAULT_USER.get())
开发者ID:OpenPOWER-BigData,项目名称:HDP-hue,代码行数:17,代码来源:create_sandbox_user.py


示例14: test_get_profile

def test_get_profile():
  # Ensure profiles are created after get_profile is called.
  reset_all_users()
  reset_all_groups()
  c = make_logged_in_client(username='test', password='test', is_superuser=True)
  assert_equal(0, UserProfile.objects.count())
  p = get_profile(User.objects.get(username='test'))
  assert_equal(1, UserProfile.objects.count())
开发者ID:hwl-py,项目名称:hue,代码行数:8,代码来源:tests.py


示例15: _import_ldap_users_info

def _import_ldap_users_info(connection, user_info, sync_groups=False, import_by_dn=False):
  """
  Import user_info found through ldap_access.find_users.
  """
  imported_users = []
  for ldap_info in user_info:
    # Extra validation in case import by DN and username has spaces or colons
    validate_username(ldap_info['username'])

    user, created = ldap_access.get_or_create_ldap_user(username=ldap_info['username'])
    profile = get_profile(user)
    if not created and profile.creation_method == str(UserProfile.CreationMethod.HUE):
      # This is a Hue user, and shouldn't be overwritten
      LOG.warn(_('There was a naming conflict while importing user %(username)s') % {
        'username': ldap_info['username']
      })
      return None

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

    if 'first' in ldap_info:
      user.first_name = ldap_info['first']
    if 'last' in ldap_info:
      user.last_name = ldap_info['last']
    if 'email' in ldap_info:
      user.email = ldap_info['email']

    profile.creation_method = UserProfile.CreationMethod.EXTERNAL
    profile.save()
    user.save()
    imported_users.append(user)

    # sync groups
    if sync_groups and 'groups' in ldap_info:
      old_groups = set(user.groups.all())
      new_groups = set()
      # Skip if 'memberOf' or 'isMemberOf' are not set
      for group_dn in ldap_info['groups']:
        group_ldap_info = connection.find_groups(group_dn, find_by_dn=True, scope=ldap.SCOPE_BASE)
        for group_info in group_ldap_info:
          # Add only if user isn't part of group.
          if not user.groups.filter(name=group_info['name']).exists():
            groups = import_ldap_groups(connection, group_info['dn'], import_members=False, import_members_recursive=False, sync_users=False, import_by_dn=True)
            if groups:
              new_groups.update(groups)

      # Remove out of date groups
      remove_groups = old_groups - new_groups
      remove_ldap_groups = LdapGroup.objects.filter(group__in=remove_groups)
      remove_groups_filtered = [ldapgroup.group for ldapgroup in remove_ldap_groups]
      user.groups.filter(group__in=remove_groups_filtered).delete()
      user.groups.add(*new_groups)
      Group.objects.filter(group__in=remove_groups_filtered).delete()
      remove_ldap_groups.delete()

  return imported_users
开发者ID:bitsom,项目名称:hue,代码行数:58,代码来源:views.py


示例16: authenticate

  def authenticate(self, username=None):
    username = self.clean_username(username)
    is_super = False
    if User.objects.count() == 0:
      is_super = True

    try:
      user = User.objects.get(username=username)
    except User.DoesNotExist:
      user = find_or_create_user(username, 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

        ensure_has_a_group(user)

        user.save()

    user = rewrite_user(user)
    return user
开发者ID:GitHublong,项目名称:hue,代码行数:22,代码来源:backend.py


示例17: test_useradmin_ldap_user_integration

def test_useradmin_ldap_user_integration():
  if is_live_cluster():
    raise SkipTest('HUE-2897: Skipping because DB may not support unicode')

  done = []

  # Set to nonsensical value just to force new config usage.
  # Should continue to use cached connection.
  done.append(desktop.conf.LDAP.LDAP_SERVERS.set_for_testing(get_nonsense_config()))

  try:
    reset_all_users()
    reset_all_groups()

    # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection
    ldap_access.CACHED_LDAP_CONN = LdapTestConnection()

    # Try importing a user
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'lårry', sync_groups=False, import_by_dn=False)
    larry = User.objects.get(username='lårry')
    assert_true(larry.first_name == 'Larry')
    assert_true(larry.last_name == 'Stooge')
    assert_true(larry.email == '[email protected]')
    assert_true(get_profile(larry).creation_method == str(UserProfile.CreationMethod.EXTERNAL))

    # Should be a noop
    sync_ldap_users(ldap_access.CACHED_LDAP_CONN)
    sync_ldap_groups(ldap_access.CACHED_LDAP_CONN)
    assert_equal(User.objects.all().count(), 1)
    assert_equal(Group.objects.all().count(), 0)

    # Make sure that if a Hue user already exists with a naming collision, we
    # won't overwrite any of that user's information.
    hue_user = User.objects.create(username='otherguy', first_name='Different', last_name='Guy')
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'otherguy', sync_groups=False, import_by_dn=False)
    hue_user = User.objects.get(username='otherguy')
    assert_equal(get_profile(hue_user).creation_method, str(UserProfile.CreationMethod.HUE))
    assert_equal(hue_user.first_name, 'Different')

    # Make sure LDAP groups exist or they won't sync
    import_ldap_groups(ldap_access.CACHED_LDAP_CONN, 'TestUsers', import_members=False, import_members_recursive=False, sync_users=False, import_by_dn=False)
    import_ldap_groups(ldap_access.CACHED_LDAP_CONN, 'Test Administrators', import_members=False, import_members_recursive=False, sync_users=False, import_by_dn=False)
    # Try importing a user and sync groups
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'curly', sync_groups=True, import_by_dn=False)
    curly = User.objects.get(username='curly')
    assert_equal(curly.first_name, 'Curly')
    assert_equal(curly.last_name, 'Stooge')
    assert_equal(curly.email, '[email protected]')
    assert_equal(get_profile(curly).creation_method, str(UserProfile.CreationMethod.EXTERNAL))
    assert_equal(2, curly.groups.all().count(), curly.groups.all())

    reset_all_users()
    reset_all_groups()

    # Test import case sensitivity
    done.append(desktop.conf.LDAP.IGNORE_USERNAME_CASE.set_for_testing(True))
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'Lårry', sync_groups=False, import_by_dn=False)
    assert_false(User.objects.filter(username='Lårry').exists())
    assert_true(User.objects.filter(username='lårry').exists())

    # Test lower case
    User.objects.filter(username__iexact='Rock').delete()
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'Rock', sync_groups=False, import_by_dn=False)
    assert_false(User.objects.filter(username='Rock').exists())
    assert_true(User.objects.filter(username='rock').exists())

    done.append(desktop.conf.LDAP.FORCE_USERNAME_LOWERCASE.set_for_testing(True))

    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'Rock', sync_groups=False, import_by_dn=False)
    assert_false(User.objects.filter(username='Rock').exists())
    assert_true(User.objects.filter(username='rock').exists())

    User.objects.filter(username='Rock').delete()
    import_ldap_users(ldap_access.CACHED_LDAP_CONN, 'Rock', sync_groups=False, import_by_dn=False)
    assert_false(User.objects.filter(username='Rock').exists())
    assert_true(User.objects.filter(username='rock').exists())
  finally:
    for finish in done:
      finish()
开发者ID:neiodavince,项目名称:hue,代码行数:79,代码来源:test_ldap.py


示例18: get_profile

      LOG.warn("Create users when they login with their LDAP credentials is turned off")
      return None

    try:
      allowed_group = self.check_ldap_access_groups(server, username)
      if allowed_group:
        user = self._backend.authenticate(username, password)
      else:
        LOG.warn("%s not in an allowed login group" % username)
        return None
    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.name
      profile.save()
      user.is_superuser = is_super
      user = rewrite_user(user)

      ensure_has_a_group(user)

      if desktop.conf.LDAP.SYNC_GROUPS_ON_LOGIN.get():
        self.import_groups(server, user)

    return user

  def get_user(self, user_id):
    user = self._backend.get_user(user_id)
    user = rewrite_user(user)
开发者ID:cloudera,项目名称:hue,代码行数:31,代码来源:backend.py


示例19: test_useradmin_ldap_user_integration

def test_useradmin_ldap_user_integration():
    done = []
    try:
        reset_all_users()
        reset_all_groups()

        # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection
        ldap_access.CACHED_LDAP_CONN = LdapTestConnection()

        # Try importing a user
        import_ldap_users("lårry", sync_groups=False, import_by_dn=False)
        larry = User.objects.get(username="lårry")
        assert_true(larry.first_name == "Larry")
        assert_true(larry.last_name == "Stooge")
        assert_true(larry.email == "[email protected]")
        assert_true(get_profile(larry).creation_method == str(UserProfile.CreationMethod.EXTERNAL))

        # Should be a noop
        sync_ldap_users()
        sync_ldap_groups()
        assert_equal(User.objects.all().count(), 1)
        assert_equal(Group.objects.all().count(), 0)

        # Make sure that if a Hue user already exists with a naming collision, we
        # won't overwrite any of that user's information.
        hue_user = User.objects.create(username="otherguy", first_name="Different", last_name="Guy")
        import_ldap_users("otherguy", sync_groups=False, import_by_dn=False)
        hue_user = User.objects.get(username="otherguy")
        assert_equal(get_profile(hue_user).creation_method, str(UserProfile.CreationMethod.HUE))
        assert_equal(hue_user.first_name, "Different")

        # Try importing a user and sync groups
        import_ldap_users("curly", sync_groups=True, import_by_dn=False)
        curly = User.objects.get(username="curly")
        assert_equal(curly.first_name, "Curly")
        assert_equal(curly.last_name, "Stooge")
        assert_equal(curly.email, "[email protected]")
        assert_equal(get_profile(curly).creation_method, str(UserProfile.CreationMethod.EXTERNAL))
        assert_equal(2, curly.groups.all().count(), curly.groups.all())

        reset_all_users()
        reset_all_groups()

        # Test import case sensitivity
        done.append(desktop.conf.LDAP.IGNORE_USERNAME_CASE.set_for_testing(True))
        import_ldap_users("Lårry", sync_groups=False, import_by_dn=False)
        assert_false(User.objects.filter(username="Lårry").exists())
        assert_true(User.objects.filter(username="lårry").exists())

        # Test lower case
        User.objects.filter(username__iexact="Rock").delete()
        import_ldap_users("Rock", sync_groups=False, import_by_dn=False)
        assert_true(User.objects.filter(username="Rock").exists())
        assert_false(User.objects.filter(username="rock").exists())

        done.append(desktop.conf.LDAP.FORCE_USERNAME_LOWERCASE.set_for_testing(True))

        import_ldap_users("Rock", sync_groups=False, import_by_dn=False)
        assert_true(User.objects.filter(username="Rock").exists())
        assert_false(User.objects.filter(username="rock").exists())

        User.objects.filter(username="Rock").delete()
        import_ldap_users("Rock", sync_groups=False, import_by_dn=False)
        assert_false(User.objects.filter(username="Rock").exists())
        assert_true(User.objects.filter(username="rock").exists())
    finally:
        for finish in done:
            finish()
开发者ID:jekey,项目名称:hue,代码行数:68,代码来源:tests.py


示例20: edit_user

def edit_user(request, username=None):
  """
  edit_user(request, username = None) -> reply

  @type request:        HttpRequest
  @param request:       The request object
  @type username:       string
  @param username:      Default to None, when creating a new user
  """
  if request.user.username != username and not request.user.is_superuser:
    raise PopupException(_("You must be a superuser to add or edit another user."), error_code=401)

  if username is not None:
    instance = User.objects.get(username=username)
  else:
    instance = None

  if request.user.is_superuser:
    form_class = SuperUserChangeForm
  else:
    form_class = UserChangeForm

  if request.method == 'POST':
    form = form_class(request.POST, instance=instance)
    if form.is_valid(): # All validation rules pass
      if instance is None:
        instance = form.save()
        get_profile(instance)
      else:
        if username != form.instance.username:
          raise PopupException(_("You cannot change a username."), error_code=401)
        if request.user.username == username and not form.instance.is_active:
          raise PopupException(_("You cannot make yourself inactive."), error_code=401)

        global __users_lock
        __users_lock.acquire()
        try:
          # form.instance (and instance) now carry the new data
          orig = User.objects.get(username=username)
          if orig.is_superuser:
            if not form.instance.is_superuser or not form.instance.is_active:
              _check_remove_last_super(orig)
          else:
            if form.instance.is_superuser and not request.user.is_superuser:
              raise PopupException(_("You cannot make yourself a superuser."), error_code=401)

          # All ok
          form.save()
          request.info(_('User information updated'))
        finally:
          __users_lock.release()

      # Ensure home directory is created, if necessary.
      if form.cleaned_data['ensure_home_directory']:
        try:
          ensure_home_directory(request.fs, instance.username)
        except (IOError, WebHdfsException), e:
          request.error(_('Cannot make home directory for user %s.' % instance.username))
      if request.user.is_superuser:
        return redirect(reverse(list_users))
      else:
        return redirect(reverse(edit_user, kwargs={'username': username}))
开发者ID:2013Commons,项目名称:hue,代码行数:62,代码来源:views.py



注:本文中的useradmin.models.get_profile函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.install_sample_user函数代码示例发布时间:2022-05-27
下一篇:
Python models.get_default_user_group函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap