public void testOrgDefautRegistrationToken() throws Exception {
    User user = UserTestUtils.findNewUser("testUser", "testOrg", true);
    Org orig = user.getOrg();
    orig.setName("org created by OrgFactory test: " + TestUtils.randomString());
    // build the channels set
    Channel channel1 = ChannelFactoryTest.createTestChannel(orig);
    flushAndEvict(channel1);
    orig.addOwnedChannel(channel1);
    orig = OrgFactory.save(orig);
    assertTrue(orig.getId().longValue() > 0);

    assertNull(orig.getToken());
    ActivationKey key = ActivationKeyTest.createTestActivationKey(user);
    // Token is hidden behind activation key so we have to look it up
    // manually:
    Token token = TokenFactory.lookupById(key.getId());
    orig.setToken(token);
    orig = OrgFactory.save(orig);
    Long origId = orig.getId();
    flushAndEvict(orig);

    Org lookup = OrgFactory.lookupById(origId);
    assertEquals(token.getId(), lookup.getToken().getId());
    lookup.setToken(null);
    flushAndEvict(lookup);

    lookup = OrgFactory.lookupById(origId);
    assertNull(lookup.getToken());
  }
Example #2
0
  private void setPageSize() {
    int tmp = -1;
    RequestContext rctx = new RequestContext((HttpServletRequest) pageContext.getRequest());
    User user = rctx.getLoggedInUser();
    if (user != null) {
      tmp = user.getPageSize();
      if (tmp > 0) {
        pageSize = tmp;
      }
    }
    if (pageSize < 1) {
      pageSize = 10;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) pageContext.getRequest();

    if (PageSizeDecorator.pageWidgetSelected(httpRequest, getUniqueName())) {
      int size = PageSizeDecorator.getSelectedPageSize(httpRequest, getUniqueName());
      List<Integer> pageSizes = PageSizeDecorator.getPageSizes();
      if (size < 1 || size > pageSizes.get(pageSizes.size() - 1)) {
        return;
      } else {
        pageSize = size;
      }
    }
  }
Example #3
0
  /**
   * In this test we actually return an HttpServletRequest so this code can be reused by other tests
   * to Login a user and get the Request (with session) that appears logged in. In order for this
   * test to be executed by JUnit we have to wrap its call in the above method with a void return
   * type.
   *
   * @throws Exception
   */
  public HttpServletRequest loginUserIntoSessionTest() throws Exception {
    LoginAction action = new LoginAction();
    User u = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName());
    ActionMapping mapping = new ActionMapping();
    mapping.addForwardConfig(new ActionForward("loggedin", "path", false));
    PxtCookieManager pcm = new PxtCookieManager();
    RhnMockDynaActionForm form = new RhnMockDynaActionForm("loginForm");
    RhnMockHttpServletRequest request = new RhnMockHttpServletRequest();
    RhnMockHttpServletResponse response = new RhnMockHttpServletResponse();

    RequestContext requestContext = new RequestContext(request);

    MockHttpSession mockSession = new MockHttpSession();
    mockSession.setupGetAttribute("url_bounce", null);
    mockSession.setupGetAttribute("request_method", "GET");
    request.setSession(mockSession);
    request.setupServerName("mymachine.rhndev.redhat.com");
    WebSession s = requestContext.getWebSession();
    request.addCookie(pcm.createPxtCookie(s.getId(), request, 10));

    form.set("username", u.getLogin());
    /**
     * Since we know testUser's password is "password", just set that here. using u.getPassword()
     * will fail when we're using encrypted passwords.
     */
    form.set("password", "password");
    form.set("request_method", "POST");

    ActionForward rc = action.execute(mapping, form, request, response);

    assertNull(rc);
    return request;
  }
  public void testStore() {
    Org org = UserTestUtils.findNewOrg("testorg");

    String login = TestUtils.randomString();
    command.setLogin(login);
    command.setPassword("password");
    command.setEmail("*****@*****.**");
    command.setPrefix("Dr.");
    command.setFirstNames("Chuck Norris");
    command.setLastName("Texas Ranger");
    command.setOrg(org);
    command.setCompany("Test company");

    Object[] errors = command.validate();
    assertEquals(0, errors.length);

    command.storeNewUser();

    Long uid = command.getUser().getId();
    assertNotNull(uid);

    User result = UserFactory.lookupById(uid);
    assertEquals(login, result.getLogin());
    assertEquals(PageSizeDecorator.getDefaultPageSize(), result.getPageSize());
  }
Example #5
0
  public void testDisabledUser() {
    LoginAction action = new LoginAction();
    User u = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName());
    UserManager.disableUser(u, u);

    ActionMapping mapping = new ActionMapping();
    mapping.addForwardConfig(new ActionForward("failure", "path", false));
    PxtCookieManager pcm = new PxtCookieManager();
    RhnMockDynaActionForm form = new RhnMockDynaActionForm("loginForm");
    RhnMockHttpServletRequest request = new RhnMockHttpServletRequest();
    RhnMockHttpServletResponse response = new RhnMockHttpServletResponse();

    RequestContext requestContext = new RequestContext(request);

    request.setSession(new MockHttpSession());
    request.setupServerName("mymachine.rhndev.redhat.com");
    WebSession s = requestContext.getWebSession();
    request.addCookie(pcm.createPxtCookie(s.getId(), request, 10));

    form.set("username", u.getLogin());
    /**
     * Since we know testUser's password is "password", just set that here. using u.getPassword()
     * will fail when we're using encrypted passwords.
     */
    form.set("password", "password");

    ActionForward rc = action.execute(mapping, form, request, response);

    assertEquals("failure", rc.getName());
  }
  private void initialize(Long selectedHostServerId, Long selectedTargetServerId, User userIn) {

    log.debug(
        "Initializing with selectedHostServerId="
            + selectedHostServerId
            + ", selectedTargetServerId="
            + selectedTargetServerId);
    this.setPackagesToInstall(new LinkedList());

    // There must always be a host server present.

    Server hServer = ServerFactory.lookupByIdAndOrg(selectedHostServerId, userIn.getOrg());
    assert (hServer != null);
    this.setHostServer(hServer);

    // There may or may not be a target server present.  If so, then look it up in
    // the database.  Otherwise, we'll create the target server later.

    if (selectedTargetServerId != null) {
      this.setTargetServer(ServerFactory.lookupByIdAndOrg(selectedTargetServerId, userIn.getOrg()));
    }

    this.setUser(userIn);
    networkInterface = "";
  }
Example #7
0
  /**
   * Removes a role from the given user
   *
   * @param loggedInUser The current user
   * @param login The login for the user you would like to remove the role from
   * @param role The role you would like to remove from the user
   * @return Returns 1 if successful (exception otherwise)
   * @throws FaultException A FaultException is thrown if the user doesn't have access to lookup the
   *     user corresponding to login or if the user does not exist.
   * @xmlrpc.doc Remove a role from a user.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User login name to update.")
   * @xmlrpc.param #param_desc("string", "role", "Role label to remove. Can be any of:
   *     satellite_admin, org_admin, channel_admin, config_admin, system_group_admin,
   *     activation_key_admin, or monitoring_admin.")
   * @xmlrpc.returntype #return_int_success()
   */
  public int removeRole(User loggedInUser, String login, String role) throws FaultException {
    validateRoleInputs(role, loggedInUser);

    if (RoleFactory.SAT_ADMIN.getLabel().equals(role)) {
      return modifySatAdminRole(loggedInUser, login, false);
    }

    ensureOrgAdmin(loggedInUser);
    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);

    /*
     * Perform some error checking here... we need to make sure that this
     * isn't the last org_admin in the org trying to remove org_admin
     * status from himself.
     */
    if (role.equals(RoleFactory.ORG_ADMIN.getLabel())
        && target.hasRole(RoleFactory.ORG_ADMIN)
        && target.getOrg().numActiveOrgAdmins() <= 1) {
      throw new PermissionCheckFailureException();
    }

    // Retrieve the role object corresponding to the role label passed in and
    // remove from user
    Role r = RoleFactory.lookupByLabel(role);
    target.removePermanentRole(r);

    UserManager.storeUser(target);
    return 1;
  }
  public void testCustomDataKeys() {
    User user = UserTestUtils.findNewUser("testuser", "testorg");
    Org org = user.getOrg();

    Set keys = org.getCustomDataKeys();
    int sizeBefore = keys.size();

    CustomDataKey key = CustomDataKeyTest.createTestCustomDataKey(user);
    assertFalse(keys.contains(key));
    assertFalse(org.hasCustomDataKey(key.getLabel()));
    assertFalse(org.hasCustomDataKey("foo" + System.currentTimeMillis()));
    assertFalse(org.hasCustomDataKey(null));

    org.addCustomDataKey(key);

    keys = org.getCustomDataKeys();
    int sizeAfter = keys.size();

    assertTrue(keys.contains(key));
    assertTrue(sizeBefore < sizeAfter);
    assertTrue(org.hasCustomDataKey(key.getLabel()));

    CustomDataKey key2 = OrgFactory.lookupKeyByLabelAndOrg(key.getLabel(), org);
    assertNotNull(key2);

    key2 = OrgFactory.lookupKeyByLabelAndOrg(null, org);
    assertNull(key2);
  }
  private void setupExpectations(RhnMockDynaActionForm form, User user) {

    form.addExpectedProperty("uid", user.getId());
    form.addExpectedProperty("firstNames", user.getFirstNames());
    form.addExpectedProperty("lastName", user.getLastName());
    form.addExpectedProperty("title", user.getTitle());
    form.addExpectedProperty("prefix", user.getPrefix());
  }
Example #10
0
  /**
   * Returns the last logged in time of the given user.
   *
   * @param loggedInUser The current user in user.
   * @param login The login of the user.
   * @return last logged in time
   * @throws UserNeverLoggedInException if the given user has never logged in.
   * @xmlrpc.doc Returns the time user last logged in.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User's login name.")
   * @xmlrpc.returntype dateTime.iso8601
   */
  public Date getLoggedInTime(User loggedInUser, String login) throws UserNeverLoggedInException {

    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);
    Date d = target.getLastLoggedIn();
    if (d != null) {
      return d;
    }
    throw new UserNeverLoggedInException();
  }
Example #11
0
  private Long create(DynaActionForm form, ActionErrors errors, RequestContext ctx) {

    User loggedInUser = ctx.getCurrentUser();
    Long cid = null;

    // handle submission
    // why can't I just pass in a dictionary? sigh, there are
    // times where python would make this SOOOO much easier.
    CreateChannelCommand ccc = new CreateChannelCommand();
    ccc.setArchLabel((String) form.get("arch"));
    ccc.setChecksumLabel((String) form.get("checksum"));
    ccc.setLabel((String) form.get("label"));
    ccc.setName((String) form.get("name"));
    ccc.setSummary((String) form.get("summary"));
    ccc.setDescription(StringUtil.nullIfEmpty((String) form.get("description")));
    ccc.setParentLabel(null);
    ccc.setUser(loggedInUser);
    ccc.setGpgKeyId(StringUtil.nullIfEmpty((String) form.get("gpg_key_id")));
    ccc.setGpgKeyUrl(StringUtil.nullIfEmpty((String) form.get("gpg_key_url")));
    ccc.setGpgKeyFp(StringUtil.nullIfEmpty((String) form.get("gpg_key_fingerprint")));
    ccc.setMaintainerName(StringUtil.nullIfEmpty((String) form.get("maintainer_name")));
    ccc.setMaintainerEmail(StringUtil.nullIfEmpty((String) form.get("maintainer_email")));
    ccc.setMaintainerPhone(StringUtil.nullIfEmpty((String) form.get("maintainer_phone")));
    ccc.setSupportPolicy(StringUtil.nullIfEmpty((String) form.get("support_policy")));
    ccc.setAccess((String) form.get("org_sharing"));

    String parent = (String) form.get("parent");
    if (parent == null || parent.equals("")) {
      ccc.setParentId(null);
    } else {
      ccc.setParentId(Long.valueOf(parent));
    }

    try {
      Channel c = ccc.create();
      String sharing = (String) form.get("per_user_subscriptions");
      c.setGloballySubscribable(
          (sharing != null) && ("all".equals(sharing)), loggedInUser.getOrg());
      c = (Channel) ChannelFactory.reload(c);
      cid = c.getId();
    } catch (InvalidGPGFingerprintException borg) {
      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("edit.channel.invalidgpgfp"));
    } catch (InvalidGPGKeyException dukat) {
      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("edit.channel.invalidgpgkey"));
    } catch (InvalidGPGUrlException khan) {
      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("edit.channel.invalidgpgurl"));
    } catch (InvalidChannelNameException ferengi) {
      handleChannelNameException(errors, ferengi);
    } catch (InvalidChannelLabelException q) {
      handleChannelLabelException(errors, q);
    } catch (IllegalArgumentException iae) {
      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(iae.getMessage()));
    }

    return cid;
  }
Example #12
0
  /**
   * Returns default system groups for the given login.
   *
   * @param loggedInUser The current user in user.
   * @param login The login for the user whose Default ServerGroup list is sought.
   * @return default system groups for the given login
   * @xmlrpc.doc Returns a user's list of default system groups.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User's login name.")
   * @xmlrpc.returntype #array() #struct("system group") #prop("int", "id") #prop("string", "name")
   *     #prop("string", "description") #prop("int", "system_count") #prop_desc("int", "org_id",
   *     "Organization ID for this system group.") #struct_end() #array_end()
   */
  public Object[] listDefaultSystemGroups(User loggedInUser, String login) {
    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);
    Set<Long> ids = target.getDefaultSystemGroupIds();

    List<ServerGroup> sgs = new ArrayList(ids.size());
    for (Long id : ids) {
      sgs.add(ServerGroupFactory.lookupByIdAndOrg(id, target.getOrg()));
    }
    return sgs.toArray();
  }
 /**
  * Delete a snippet.
  *
  * @param sessionKey the session key
  * @param name the name of the snippet
  * @return 1 for success 0 for not
  * @xmlrpc.doc Delete the specified snippet. If the snippet is not found, 0 is returned.
  * @xmlrpc.param #param("string", "sessionKey")
  * @xmlrpc.param #param("string", "name")
  * @xmlrpc.returntype #return_int_success()
  */
 public int delete(String sessionKey, String name) {
   User loggedInUser = getLoggedInUser(sessionKey);
   verifyKSAdmin(loggedInUser);
   CobblerSnippet snip = CobblerSnippet.loadEditableIfExists(name, loggedInUser.getOrg());
   if (snip != null) {
     snip.delete();
     return 1;
   }
   return 0;
 }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext context = new RequestContext(request);
    User user = context.getCurrentUser();

    long cid = context.getRequiredParam("cid");
    Channel chan = ChannelFactory.lookupByIdAndUser(cid, user);
    request.setAttribute("channel_name", chan.getName());
    request.setAttribute("cid", chan.getId());

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(RequestContext.CID, chan.getId().toString());

    ListSessionSetHelper helper = new ListSessionSetHelper(this, request, params);

    if (!context.isSubmitted()) {
      List<ContentSource> result = getResult(context);
      Set<String> preSelect = new HashSet<String>();
      for (int i = 0; i < result.size(); i++) {
        ContentSource src = result.get(i);
        if (src.getChannels().contains(chan)) {
          preSelect.add(src.getId().toString());
        }
      }
      helper.preSelect(preSelect);
    }

    helper.ignoreEmptySelection();
    helper.execute();

    if (helper.isDispatched()) {
      Set<ContentSource> foo = chan.getSources();
      foo.clear();
      Set<String> set = helper.getSet();
      for (String id : set) {
        Long sgid = Long.valueOf(id);
        ContentSource tmp = ChannelFactory.lookupContentSource(sgid, user.getOrg());
        foo.add(tmp);
      }

      ChannelFactory.save(chan);

      StrutsDelegate strutsDelegate = getStrutsDelegate();
      strutsDelegate.saveMessage(
          "channel.edit.repo.updated", new String[] {chan.getName()}, request);

      return strutsDelegate.forwardParams(mapping.findForward("success"), params);
    }

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
Example #15
0
  /**
   * Migrate systems from one organization to another. If executed by a Satellite administrator, the
   * systems will be migrated from their current organization to the organization specified by the
   * toOrgId. If executed by an organization administrator, the systems must exist in the same
   * organization as that administrator and the systems will be migrated to the organization
   * specified by the toOrgId. In any scenario, the origination and destination organizations must
   * be defined in a trust.
   *
   * @param sessionKey User's session key.
   * @param toOrgId destination organization ID.
   * @param sids System IDs.
   * @return list of systems migrated.
   * @throws FaultException A FaultException is thrown if: - The user performing the request is not
   *     an organization administrator - The user performing the request is not a satellite
   *     administrator, but the from org id is different than the user's org id. - The from and to
   *     org id provided are the same. - One or more of the servers provides do not exist - The
   *     origination or destination organization does not exist - The user is not defined in the
   *     destination organization's trust
   * @xmlrpc.doc Migrate systems from one organization to another. If executed by a Satellite
   *     administrator, the systems will be migrated from their current organization to the
   *     organization specified by the toOrgId. If executed by an organization administrator, the
   *     systems must exist in the same organization as that administrator and the systems will be
   *     migrated to the organization specified by the toOrgId. In any scenario, the origination and
   *     destination organizations must be defined in a trust.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("int", "toOrgId", "ID of the organization where the system(s) will be
   *     migrated to.")
   * @xmlrpc.param #array_single("int", "systemId")
   * @xmlrpc.returntype #array_single("int", "serverIdMigrated")
   */
  public Object[] migrateSystems(String sessionKey, Integer toOrgId, List<Integer> sids)
      throws FaultException {

    // the user executing the request must at least be an org admin to perform
    // a system migration
    User admin = getOrgAdmin(sessionKey);

    Org toOrg = verifyOrgExists(toOrgId);

    List<Server> servers = new LinkedList<Server>();

    for (Integer sid : sids) {
      Long serverId = new Long(sid.longValue());
      Server server = null;
      try {
        server = ServerFactory.lookupById(serverId);

        // throw a no_such_system exception if the server was not found.
        if (server == null) {
          throw new NoSuchSystemException("No such system - sid[" + sid + "]");
        }
      } catch (LookupException e) {
        throw new NoSuchSystemException("No such system - sid[" + sid + "]");
      }
      servers.add(server);

      // As a pre-requisite to performing the actual migration, verify that each
      // server that is planned for migration passes the criteria that follows.
      // If any of the servers fails that criteria, none will be migrated.

      // unless the user is a satellite admin, they are not permitted to migrate
      // systems from an org that they do not belong to
      if ((!admin.hasRole(RoleFactory.SAT_ADMIN)) && (!admin.getOrg().equals(server.getOrg()))) {
        throw new PermissionCheckFailureException(server);
      }

      // do not allow the user to migrate systems to/from the same org.  doing so
      // would essentially remove entitlements, channels...etc from the systems
      // being migrated.
      if (toOrg.equals(server.getOrg())) {
        throw new MigrationToSameOrgException(server);
      }

      // if the originating org is not defined within the destination org's trust
      // the migration should not be permitted.
      if (!toOrg.getTrustedOrgs().contains(server.getOrg())) {
        throw new OrgNotInTrustException(server);
      }
    }

    List<Long> serversMigrated = MigrationManager.migrateServers(admin, toOrg, servers);
    return serversMigrated.toArray();
  }
Example #16
0
  /**
   * Deletes a user
   *
   * @param loggedInUser The current user
   * @param login The login for the user you would like to delete
   * @return Returns 1 if successful (exception otherwise)
   * @throws FaultException A FaultException is thrown if the user doesn't have access to lookup the
   *     user corresponding to login or if the user does not exist.
   * @xmlrpc.doc Delete a user.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User login name to delete.")
   * @xmlrpc.returntype #return_int_success()
   */
  public int delete(User loggedInUser, String login) throws FaultException {
    ensureOrgAdmin(loggedInUser);
    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);

    try {
      UserManager.deleteUser(loggedInUser, target.getId());
    } catch (DeleteSatAdminException e) {
      throw new DeleteUserException("user.cannot.delete.last.sat.admin");
    }

    return 1;
  }
Example #17
0
 /**
  * Adds a role to the given user
  *
  * @param loggedInUser The current user
  * @param login The login for the user you would like to add the role to
  * @param role The role you would like to give the user
  * @return Returns 1 if successful (exception otherwise)
  * @throws FaultException A FaultException is thrown if the user doesn't have access to lookup the
  *     user corresponding to login or if the user does not exist.
  * @xmlrpc.doc Adds a role to a user.
  * @xmlrpc.param #param("string", "sessionKey")
  * @xmlrpc.param #param_desc("string", "login", "User login name to update.")
  * @xmlrpc.param #param_desc("string", "role", "Role label to add. Can be any of: satellite_admin,
  *     org_admin, channel_admin, config_admin, system_group_admin, activation_key_admin, or
  *     monitoring_admin.")
  * @xmlrpc.returntype #return_int_success()
  */
 public int addRole(User loggedInUser, String login, String role) throws FaultException {
   validateRoleInputs(role, loggedInUser);
   if (RoleFactory.SAT_ADMIN.getLabel().equals(role)) {
     return modifySatAdminRole(loggedInUser, login, true);
   }
   User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);
   // Retrieve the role object corresponding to the role label passed in and
   // add to user
   Role r = RoleFactory.lookupByLabel(role);
   target.addPermanentRole(r);
   UserManager.storeUser(target);
   return 1;
 }
Example #18
0
  /**
   * Lists the roles for a user
   *
   * @param loggedInUser The current user
   * @param login The login for the user you want to get the roles for
   * @return Returns a list of roles for the user specified by login
   * @throws FaultException A FaultException is thrown if the user doesn't have access to lookup the
   *     user corresponding to login or if the user does not exist.
   * @xmlrpc.doc Returns a list of the user's roles.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User's login name.")
   * @xmlrpc.returntype #array_single("string", "(role label)")
   */
  public Object[] listRoles(User loggedInUser, String login) throws FaultException {
    // Get the logged in user
    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);
    List roles = new ArrayList(); // List of role labels to return

    // Loop through the target users roles and stick the labels into the ArrayList
    Set roleObjects = target.getPermanentRoles();
    for (Iterator itr = roleObjects.iterator(); itr.hasNext(); ) {
      Role r = (Role) itr.next();
      roles.add(r.getLabel());
    }

    return roles.toArray();
  }
  public void testPerformExecute() throws Exception {
    UserEditSetupAction action = new UserEditSetupAction();
    ActionHelper sah = new ActionHelper();
    sah.setUpAction(action);
    sah.getRequest().setRequestURL("foo");

    User user = sah.getUser();
    user.setTitle("Test title");
    // Lets add some roles
    Iterator it = UserFactory.IMPLIEDROLES.iterator();
    user.addPermanentRole(RoleFactory.ORG_ADMIN);
    while (it.hasNext()) {
      Role cr = (Role) it.next();
      user.getOrg().addRole(cr);
      user.addPermanentRole(cr);
    }

    setupExpectations(sah.getForm(), sah.getUser());

    // Below we test to make sure that some of
    // the strings in the form are localized
    TestUtils.enableLocalizationDebugMode();
    try {
      sah.executeAction();

      // verify the dyna form got the right values we expected.
      sah.getForm().verify();

      assertEquals(sah.getUser().getLastLoggedIn(), sah.getRequest().getAttribute("lastLoggedIn"));
      // Verify some more intensive stuff
      assertNotNull(sah.getRequest().getAttribute("adminRoles"));
      assertNotNull(sah.getRequest().getAttribute("regularRoles"));
      List<UserRoleStatusBean> regularRoles =
          (List<UserRoleStatusBean>) sah.getRequest().getAttribute("regularRoles");
      assertEquals(5, regularRoles.size());
      UserRoleStatusBean lv = regularRoles.get(0);
      assertTrue(TestUtils.isLocalized(lv.getName()));
      assertEquals(true, lv.isDisabled());
      assertNotNull(sah.getRequest().getAttribute("disabledRoles"));
      assertTrue(sah.getRequest().getAttribute("user") instanceof User);

      // If we have pam setup where we're testing, make sure displaypam was set
      String pamAuthService = Config.get().getString(ConfigDefaults.WEB_PAM_AUTH_SERVICE);
      if (pamAuthService != null && pamAuthService.trim().length() > 0) {
        assertNotNull(sah.getRequest().getAttribute("displaypam"));
      }
    } finally {
      TestUtils.disableLocalizationDebugMode();
    }
  }
Example #20
0
  /**
   * Creates a new user
   *
   * @param loggedInUser The current user
   * @param desiredLogin The login for the new user
   * @param desiredPassword The password for the new user
   * @param firstName The first name of the new user
   * @param lastName The last name of the new user
   * @param email The email address for the new user
   * @param usePamAuth Should this user authenticate via PAM?
   * @return Returns 1 if successful (exception otherwise)
   * @throws FaultException A FaultException is thrown if the loggedInUser doesn't have permissions
   *     to create new users in thier org.
   * @xmlrpc.doc Create a new user.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "desiredLogin", "Desired login name, will fail if already
   *     in use.")
   * @xmlrpc.param #param("string", "desiredPassword")
   * @xmlrpc.param #param("string", "firstName")
   * @xmlrpc.param #param("string", "lastName")
   * @xmlrpc.param #param_desc("string", "email", "User's e-mail address.")
   * @xmlrpc.param #param_desc("int", "usePamAuth", "1 if you wish to use PAM authentication for
   *     this user, 0 otherwise.")
   * @xmlrpc.returntype #return_int_success()
   */
  public int create(
      User loggedInUser,
      String desiredLogin,
      String desiredPassword,
      String firstName,
      String lastName,
      String email,
      Integer usePamAuth)
      throws FaultException {
    // Logged in user must be an org admin and we must be on a sat to do this.
    ensureOrgAdmin(loggedInUser);
    ensurePasswordOrPamAuth(usePamAuth, desiredPassword);

    boolean pamAuth = BooleanUtils.toBoolean(usePamAuth, new Integer(1), new Integer(0));

    if (pamAuth) {
      desiredPassword = getDefaultPasswordForPamAuth();
    }

    CreateUserCommand command = new CreateUserCommand();
    command.setUsePamAuthentication(pamAuth);
    command.setLogin(desiredLogin);
    command.setPassword(desiredPassword);
    command.setFirstNames(firstName);
    command.setLastName(lastName);
    command.setEmail(email);
    command.setOrg(loggedInUser.getOrg());
    command.setCompany(loggedInUser.getCompany());

    // Validate the user to be
    ValidatorError[] errors = command.validate();
    if (errors.length > 0) {
      StringBuilder errorString = new StringBuilder();
      LocalizationService ls = LocalizationService.getInstance();
      // Build a sane error message here
      for (int i = 0; i < errors.length; i++) {
        ValidatorError err = errors[i];
        errorString.append(ls.getMessage(err.getKey(), err.getValues()));
        if (i != errors.length - 1) {
          errorString.append(" :: ");
        }
      }
      // Throw a BadParameterException with our message string
      throw new BadParameterException(errorString.toString());
    }

    command.storeNewUser();
    return 1;
  }
Example #21
0
  private int enableAccess(User loggedInUser, String channelLabel, Integer orgId, boolean enable)
      throws FaultException {
    Channel channel = lookupChannelByLabel(loggedInUser, channelLabel);
    verifyChannelAdmin(loggedInUser, channel);

    if (!loggedInUser.getOrg().equals(channel.getOrg())) {
      // users are not allowed to alter properties for a channel that is in a
      // different org
      throw new NotPermittedByOrgException(
          loggedInUser.getOrg().getId().toString(),
          channel.getLabel(),
          channel.getOrg().getId().toString());
    }

    // protected mode only for modifying individual orgs
    if (!channel.getAccess().equals(Channel.PROTECTED)) {
      throw new InvalidChannelAccessException(channel.getAccess());
    }

    Org org = OrgFactory.lookupById(orgId.longValue());
    if (org == null) {
      throw new NoSuchOrgException(orgId.toString());
    }

    // need to validate that the org provided is in the list of orgs that may
    // be granted access
    List<OrgChannelDto> orgs = OrgManager.orgChannelTrusts(channel.getId(), loggedInUser.getOrg());
    boolean orgInTrust = false;

    for (OrgChannelDto orgDto : orgs) {
      if (orgDto.getId().equals(new Long(orgId))) {
        orgInTrust = true;
        break;
      }
    }

    if (orgInTrust) {
      if (enable) {
        channel.getTrustedOrgs().add(org);
      } else {
        channel.getTrustedOrgs().remove(org);
      }
      ChannelFactory.save(channel);
    } else {
      throw new OrgNotInTrustException(orgId);
    }

    return 1;
  }
Example #22
0
  /**
   * Toggles whether or not a user users pamAuthentication or the basic RHN db auth.
   *
   * @param loggedInUser The current user
   * @param login The login for the user you would like to change
   * @param val The value you would like to set this to (1 = true, 0 = false)
   * @return Returns 1 if successful (exception otherwise)
   * @throws FaultException A FaultException is thrown if the user doesn't have access to lookup the
   *     user corresponding to login or if the user does not exist.
   * @xmlrpc.doc Toggles whether or not a user uses PAM authentication or basic RHN authentication.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User's login name.")
   * @xmlrpc.param #param("int", "pam_value") #options() #item("1 to enable PAM authentication")
   *     #item("0 to disable.") #options_end()
   * @xmlrpc.returntype #return_int_success()
   */
  public int usePamAuthentication(User loggedInUser, String login, Integer val)
      throws FaultException {
    // Only org admins can use this method.
    ensureOrgAdmin(loggedInUser);
    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);

    if (val.equals(new Integer(1))) {
      target.setUsePamAuthentication(true);
    } else {
      target.setUsePamAuthentication(false);
    }

    UserManager.storeUser(target);

    return 1;
  }
Example #23
0
  /**
   * Return the current value of the createDefaultSystemGroup settnig
   *
   * @param loggedInUser The current user Must be org_admin.
   * @param createDefaultSystemGroup The value to set
   * @return Returns 1 if successful (exception otherwise)
   * @xmlrpc.doc Sets the value of the CreateDefaultSystemGroup setting. If True this will cause
   *     there to be a system group created (with the same name as the user) every time a new user
   *     is created, with the user automatically given permission to that system group and the
   *     system group being set as the default group for the user (so every time the user registers
   *     a system it will be placed in that system group by default). This can be useful if
   *     different users will administer different groups of servers in the same organization. Can
   *     only be called by an org_admin.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("boolean", "createDefaultSystemGruop", "True if we should
   *     automatically create system groups, false otherwise.")
   * @xmlrpc.returntype #return_int_success()
   */
  public int setCreateDefaultSystemGroup(User loggedInUser, Boolean createDefaultSystemGroup) {
    // Logged in user must be an org admin.
    ensureOrgAdmin(loggedInUser);

    loggedInUser.getOrg().getOrgConfig().setCreateDefaultSg(createDefaultSystemGroup);
    return 1;
  }
Example #24
0
  /**
   * Add ServerGroups to the list of Default System groups. The ServerGroups <strong>MUST</strong>
   * exist otherwise a IllegalArgumentException is thrown.
   *
   * @param loggedInUser The current user in user.
   * @param login The login for the user whose Default ServerGroup list will be affected.
   * @param sgNames names of ServerGroups.
   * @return Returns 1 if successful (exception otherwise)
   * @xmlrpc.doc Add system groups to user's list of default system groups.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User's login name.")
   * @xmlrpc.param #array_single("string", "serverGroupName")
   * @xmlrpc.returntype #return_int_success()
   */
  public int addDefaultSystemGroups(User loggedInUser, String login, List sgNames) {

    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);

    if (sgNames == null || sgNames.size() < 1) {
      throw new IllegalArgumentException("no servergroup names supplied");
    }

    List groups = ServerGroupFactory.listManagedGroups(target.getOrg());

    Map groupMap = new HashMap();

    // sigh.  After looking through all of the apache collections package
    // I couldn't find anything that would create a map from a list using
    // a property from the object in the list as the key. This is where
    // python would be useful.
    for (Iterator itr = groups.iterator(); itr.hasNext(); ) {
      ServerGroup sg = (ServerGroup) itr.next();
      groupMap.put(sg.getName(), sg);
    }

    // Doing full check of all supplied names, if one is bad
    // throw an exception, prior to altering the DefaultSystemGroup Set.
    for (Iterator itr = sgNames.iterator(); itr.hasNext(); ) {
      String name = (String) itr.next();
      ServerGroup sg = (ServerGroup) groupMap.get(name);
      if (sg == null) {
        throw new LookupServerGroupException(name);
      }
    }

    // now for the real reason we're in this method.
    Set defaults = target.getDefaultSystemGroupIds();
    for (Iterator itr = sgNames.iterator(); itr.hasNext(); ) {
      ServerGroup sg = (ServerGroup) groupMap.get(itr.next());
      if (sg != null) {
        // not a simple add to the groups.  Needs to call
        // UserManager as DataSource is being used.
        defaults.add(sg.getId());
      }
    }

    UserManager.setDefaultSystemGroupIds(target, defaults);
    UserManager.storeUser(target);

    return 1;
  }
  /**
   * Setup the system for provisioning with cobbler.
   *
   * @param mapping ActionMapping for struts
   * @param form DynaActionForm representing the form
   * @param ctx RequestContext request context
   * @param response HttpServletResponse response object
   * @param step WizardStep what step are we on?
   * @return ActionForward struts action forward
   * @throws Exception if something goes amiss
   */
  public ActionForward runFourth(
      ActionMapping mapping,
      DynaActionForm form,
      RequestContext ctx,
      HttpServletResponse response,
      WizardStep step)
      throws Exception {

    log.debug("runFourth");
    if (!validateFirstSelections(form, ctx)) {
      return runFirst(mapping, form, ctx, response, step);
    }
    Long sid = (Long) form.get(RequestContext.SID);
    String cobblerId = form.getString(RequestContext.COBBLER_ID);

    log.debug("runFourth.cobblerId: " + cobblerId);

    User user = ctx.getCurrentUser();
    Server server = SystemManager.lookupByIdAndUser(sid, user);

    Map params = new HashMap();
    params.put(RequestContext.SID, sid);

    log.debug("Creating cobbler system record");
    org.cobbler.Profile profile =
        org.cobbler.Profile.lookupById(CobblerXMLRPCHelper.getConnection(user), cobblerId);

    KickstartData data =
        KickstartFactory.lookupKickstartDataByCobblerIdAndOrg(user.getOrg(), profile.getUid());

    if (showDiskWarning(data, form)) {
      form.set(NEXT_ACTION, "fourth");
      return mapping.findForward("fifth");
    }

    CobblerSystemCreateCommand cmd =
        new CobblerSystemCreateCommand(server, profile.getName(), data);
    cmd.store();
    log.debug("cobbler system record created.");
    String[] args = new String[2];
    args[0] = server.getName();
    args[1] = profile.getName();
    createMessage(ctx.getRequest(), "kickstart.schedule.cobblercreate", args);
    return getStrutsDelegate().forwardParams(mapping.findForward("cobbler-success"), params);
  }
  public void testSelectAll() throws Exception {
    BaseSystemListAction action = createAction();
    ActionHelper ah = new ActionHelper();
    ah.setUpAction(action);
    ah.setupProcessPagination();

    User user = ah.getUser();
    user.addPermanentRole(RoleFactory.ORG_ADMIN);
    UserManager.storeUser(user);
    ah.getRequest().setupAddParameter("items_on_page", (String[]) null);
    ah.getRequest().setupAddParameter("items_selected", (String[]) null);
    ah.executeAction("selectall");
    // This test only ensures that 'Select All' doesn't blow up.
    // To really test that something got selected, we would have to create an
    // appropriate system for each of the subclasses. The fact that the set cleaner
    // doesn't clean servers that should stay in the set is already tested by
    // testAddOne()
  }
  public void testPostProcessValidSession() {
    User user = UserTestUtils.findNewUser("testUser", "testOrg");
    // create a web session indicating a logged in user.
    WebSession s = WebSessionFactory.createSession();
    s.setWebUserId(user.getId());
    assertNotNull(s);
    WebSessionFactory.save(s);
    assertNotNull(s.getId());

    String[] args = {s.getKey()};

    lip.before(new XmlRpcInvocation(10, "handler", "method", null, Arrays.asList(args), writer));
    Object rc =
        lip.after(
            new XmlRpcInvocation(10, "handler", "method", null, Arrays.asList(args), writer),
            "returnthis");
    assertEquals("returnthis", rc);
    assertEquals("", writer.toString());
  }
 /**
  * Returns the kickstart schedule command
  *
  * @param form the dyna aciton form
  * @param ctx the request context
  * @param scheduleTime the schedule time
  * @param host the host url.
  * @return the Ks schedule command
  */
 protected KickstartScheduleCommand getScheduleCommand(
     DynaActionForm form, RequestContext ctx, Date scheduleTime, String host) {
   String cobblerId = form.getString(RequestContext.COBBLER_ID);
   User user = ctx.getCurrentUser();
   KickstartScheduleCommand cmd;
   KickstartData data =
       KickstartFactory.lookupKickstartDataByCobblerIdAndOrg(user.getOrg(), cobblerId);
   if (data != null) {
     cmd =
         new KickstartScheduleCommand(
             (Long) form.get(RequestContext.SID), data, ctx.getCurrentUser(), scheduleTime, host);
   } else {
     org.cobbler.Profile profile =
         org.cobbler.Profile.lookupById(CobblerXMLRPCHelper.getConnection(user), cobblerId);
     cmd =
         KickstartScheduleCommand.createCobblerScheduleCommand(
             (Long) form.get(RequestContext.SID), profile.getName(), user, scheduleTime, host);
   }
   return cmd;
 }
  public void testListAllKeys() throws Exception {
    // Setup
    User otherOrg = UserTestUtils.findNewUser("testUser", "cryptoOrg", true);
    CryptoKey key = CryptoTest.createTestKey(otherOrg.getOrg());
    KickstartFactory.saveCryptoKey(key);
    flushAndEvict(key);

    // Test
    CryptoKeysHandler handler = new CryptoKeysHandler();

    List allKeys = handler.listAllKeys(XmlRpcTestUtils.getSessionKey(otherOrg));

    // Verify
    assertNotNull(allKeys);
    assertEquals(allKeys.size(), 1);

    CryptoKeyDto dto = (CryptoKeyDto) allKeys.get(0);
    assertEquals(key.getDescription(), dto.getDescription());
    assertEquals(key.getOrg().getId(), dto.getOrgId());
  }
Example #30
0
  /**
   * List the organizations associated with the given channel that may be trusted.
   *
   * @param loggedInUser The current user
   * @param channelLabel The label for the channel
   * @return List of map entries indicating the orgs available and if access is enabled.
   * @throws FaultException A FaultException is thrown if: - The sessionKey is invalid - The
   *     channelLabel is invalid - The user doesn't have channel admin permissions
   * @xmlrpc.doc List the organizations associated with the given channel that may be trusted.
   * @xmlrpc.param #session_key()
   * @xmlrpc.param #param_desc("string", "channelLabel", "label of the channel")
   * @xmlrpc.returntype #array() #struct("org") #prop("int", "org_id") #prop("string", "org_name")
   *     #prop("boolean", "access_enabled") #struct_end() #array_end()
   */
  public List list(User loggedInUser, String channelLabel) throws FaultException {

    Channel channel = lookupChannelByLabel(loggedInUser, channelLabel);
    verifyChannelAdmin(loggedInUser, channel);

    if (!loggedInUser.getOrg().equals(channel.getOrg())) {
      // users are not allowed to access properties for a channel that is in a
      // different org
      throw new NotPermittedByOrgException(
          loggedInUser.getOrg().getId().toString(),
          channel.getLabel(),
          channel.getOrg().getId().toString());
    }

    // retrieve the orgs available to be "trusted" for this channel
    List<OrgChannelDto> orgs = OrgManager.orgChannelTrusts(channel.getId(), loggedInUser.getOrg());
    // retrieve the orgs that are trusted for this channel
    Set<Org> trustedOrgs = channel.getTrustedOrgs();

    // populate a result that includes all orgs that could be trusted with a boolean
    // that indicates if the orgs is indeed trusted.
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    for (OrgChannelDto orgDto : orgs) {
      Org org = OrgFactory.lookupById(orgDto.getId());

      if (org != null) {
        Map<String, Object> entry = new HashMap<String, Object>();

        entry.put("org_id", org.getId().intValue());
        entry.put("org_name", org.getName());
        if (trustedOrgs.contains(org)) {
          entry.put("access_enabled", Boolean.TRUE);
        } else {
          entry.put("access_enabled", Boolean.FALSE);
        }
        result.add(entry);
      }
    }
    return result;
  }