/** * remove system group association from a user * * @param loggedInUser The current user * @param login the user's login that we want to remove the association from * @param systemGroupNames list of system group names to remove * @param setDefault if true the default group will be removed from the users's group defaults * @return 1 on success * @xmlrpc.doc Remove system groups from a user's list of assigned system groups. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param #array_single("string", "serverGroupName") * @xmlrpc.param #param_desc("boolean", "setDefault", "Should system groups also be removed from * the user's list of default system groups.") * @xmlrpc.returntype #return_int_success() */ public int removeAssignedSystemGroups( User loggedInUser, String login, List<String> systemGroupNames, Boolean setDefault) { ensureUserRole(loggedInUser, RoleFactory.ORG_ADMIN); if (setDefault) { removeDefaultSystemGroups(loggedInUser, login, systemGroupNames); } User user = UserManager.lookupUser(loggedInUser, login); ServerGroupManager manager = ServerGroupManager.getInstance(); // Iterate once to lookup the server groups and avoid removing some when // an exception will only be thrown later: List<ManagedServerGroup> groups = new LinkedList<ManagedServerGroup>(); for (String name : systemGroupNames) { ManagedServerGroup sg = null; try { sg = manager.lookup(name, user); } catch (LookupException e) { throw new InvalidServerGroupException(); } groups.add(sg); } for (ManagedServerGroup sg : groups) { UserManager.revokeServerGroupPermission(user, sg.getId().longValue()); } return 1; }
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()); }
/** * 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; }
/** * Returns all roles that are assignable to a given user * * @return all the role labels that are assignable to a user. */ private Set<String> getAssignableRoles(User user) { Set<String> assignableRoles = new LinkedHashSet<String>(); for (Role r : UserManager.listRolesAssignableBy(user)) { assignableRoles.add(r.getLabel()); } return assignableRoles; }
/** * 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; }
/** * Enable a user * * @param loggedInUser The current user * @param login The login for the user you would like to enable * @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 Enable a user. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User login name to enable.") * @xmlrpc.returntype #return_int_success() */ public int enable(User loggedInUser, String login) throws FaultException { ensureOrgAdmin(loggedInUser); User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); UserManager.enableUser(loggedInUser, target); return 1; }
/** * Lookup a Package by the id, in the context of a given org. Does security check to verify that * the org has access to the package. * * @param id of the Package to search for * @param org the org which much have access to the package * @return the Package found */ public static Package lookupByIdAndOrg(Long id, Org org) { if (!UserManager.verifyPackageAccess(org, id)) { // User doesn't have access to the package... return null as if it // doesn't exist. return null; } Package pkg = lookupById(id); return pkg; }
/** * Lists the users in the org. * * @param loggedInUser The current user * @return Returns a list of userids and logins * @throws FaultException A FaultException is thrown if the loggedInUser doesn't have permissions * to list the users in their org. * @xmlrpc.doc Returns a list of users in your organization. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.returntype #array() $UserSerializer #array_end() */ public List listUsers(User loggedInUser) throws FaultException { // Get the logged in user try { List users = UserManager.usersInOrg(loggedInUser); return users; } catch (PermissionException e) { throw new PermissionCheckFailureException(); } }
/** * 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; }
/** * Handles the vagaries related to granting or revoking sat admin role * * @param loggedInUser the logged in user * @param login the login of the user who needs to be granted/revoked sat admin role * @param grant true if granting the role to the login, false for revoking... * @return 1 if it success.. Ofcourse error on failure.. */ private int modifySatAdminRole(User loggedInUser, String login, boolean grant) { ensureUserRole(loggedInUser, RoleFactory.SAT_ADMIN); SatManager manager = SatManager.getInstance(); User user = UserFactory.lookupByLogin(login); if (grant) { manager.grantSatAdminRoleTo(user, loggedInUser); } else { manager.revokeSatAdminRoleFrom(user, loggedInUser); } UserManager.storeUser(user); return 1; }
/** * 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; }
/** * 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; }
/** * Log a user into the site and create the user's session. * * @param username User's login name. * @param password User's unencrypted password. * @param request HttpServletRequest for this action. * @param response HttpServletResponse for this action. * @return Any action error messages that may have occurred. */ private User loginUser( String username, String password, HttpServletRequest request, HttpServletResponse response, ActionErrors e) { User user = null; try { user = UserManager.loginUser(username, password); } catch (LoginException ex) { e.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ex.getMessage())); } return user; }
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() }
/** * Add to the user's list of assigned system groups. * * @param loggedInUser The current user * @param login User to modify. * @param sgNames List of server group Names. * @param setDefault True to also add groups to the user's default system groups. * @return Returns 1 if successful (exception thrown otherwise) * @xmlrpc.doc Add system groups to user's list of assigned system groups. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param #array_single("string", "serverGroupName") * @xmlrpc.param #param_desc("boolean", "setDefault", "Should system groups also be added to * user's list of default system groups.") * @xmlrpc.returntype #return_int_success() */ public int addAssignedSystemGroups( User loggedInUser, String login, List sgNames, Boolean setDefault) { User targetUser = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); if (sgNames == null || sgNames.size() < 1) { throw new IllegalArgumentException("no servergroup names supplied"); } // Iterate once just to make sure all the server groups exist. Done to // prevent adding a bunch of valid groups and then throwing an exception // when coming across one that doesn't exist. List<ManagedServerGroup> groups = new LinkedList<ManagedServerGroup>(); for (Iterator it = sgNames.iterator(); it.hasNext(); ) { String serverGroupName = (String) it.next(); // Make sure the server group exists: ServerGroupManager manager = ServerGroupManager.getInstance(); ManagedServerGroup group; try { group = manager.lookup(serverGroupName, loggedInUser); } catch (LookupException e) { throw new InvalidServerGroupException(); } groups.add(group); } // Now do the actual add: for (ManagedServerGroup group : groups) { UserManager.grantServerGroupPermission(targetUser, group.getId()); } // Follow up with a call to addDefaultSystemGroups if setDefault is true: if (setDefault.booleanValue()) { addDefaultSystemGroups(loggedInUser, login, sgNames); } return 1; }
public void testAddOne() throws Exception { BaseSystemListAction action = createAction(); ActionHelper ah = new ActionHelper(); ah.setUpAction(action); ah.setupProcessPagination(); User user = ah.getUser(); user.addPermanentRole(RoleFactory.ORG_ADMIN); // Create a server that can be put in the set. Note that the // server is not set up entirely right for subclasses, which would // only display servers with certain attributes, e.g. a satellite. // But this test is only concerned with keeping a server in the set // w/o having it cleaned up by the set cleaner Server server = ServerFactoryTest.createTestServer( user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled()); UserManager.storeUser(user); String sid = server.getId().toString(); ah.getRequest().setupAddParameter("items_on_page", (String[]) null); ah.getRequest().setupAddParameter("items_selected", new String[] {sid}); ah.executeAction("updatelist"); RhnSetActionTest.verifyRhnSetData(ah.getUser(), RhnSetDecl.SYSTEMS, 1); }
/** {@inheritDoc} */ @Override public ActionForward execute( ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) { RequestContext requestContext = new RequestContext(request); User user = requestContext.getCurrentUser(); long cid = requestContext.getRequiredParam(RequestContext.CID); Channel chan = ChannelFactory.lookupByIdAndUser(cid, user); String syncType = request.getParameter(SYNC_TYPE); if (!UserManager.verifyChannelAdmin(user, chan)) { throw new PermissionException(RoleFactory.CHANNEL_ADMIN); } if (chan.getOrg() == null) { throw new PermissionCheckFailureException(); } String selectedChan = request.getParameter(SELECTED_CHANNEL); request.setAttribute(RequestContext.CID, chan.getId()); request.setAttribute(CHANNEL_NAME, chan.getName()); if (requestContext.wasDispatched("channel.jsp.package.mergebutton")) { Map<String, Object> params = new HashMap<String, Object>(); params.put(RequestContext.CID, cid); params.put(OTHER_ID, selectedChan); params.put(SYNC_TYPE, syncType); return getStrutsDelegate() .forwardParams(mapping.findForward(RhnHelper.CONFIRM_FORWARD), params); } // selected channel id long scid = 0; String sname = ""; // If a channel isn't selected, select one smartly if (selectedChan == null) { if (chan.isCloned()) { scid = chan.getOriginal().getId(); } } else if (!NO_PACKAGES.equals(selectedChan)) { scid = Long.parseLong(selectedChan); } // Add Red Hat Base Channels, and custom base channels to the list, and if one // is selected, select it List<SelectableChannel> chanList = findChannels(user, scid); DataResult result = null; if (scid != 0) { sname = ChannelFactory.lookupByIdAndUser(scid, user).getName(); result = PackageManager.comparePackagesBetweenChannels(cid, scid); TagHelper.bindElaboratorTo(listName, result.getElaborator(), request); } request.setAttribute(CHANNEL_LIST, chanList); request.setAttribute(OTHER_CHANNEL, sname); request.setAttribute(SYNC_TYPE, syncType); request.setAttribute(ListTagHelper.PARENT_URL, request.getRequestURI()); request.setAttribute(RequestContext.PAGE_LIST, result); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); }
private void setupForm(HttpServletRequest request, DynaActionForm form) { RequestContext ctx = new RequestContext(request); prepDropdowns(ctx); Long cid = ctx.getParamAsLong("cid"); if (cid != null) { Channel c = ChannelManager.lookupByIdAndUser(cid, ctx.getCurrentUser()); if (!UserManager.verifyChannelAdmin(ctx.getCurrentUser(), c)) { throw new PermissionException(RoleFactory.CHANNEL_ADMIN); } form.set("name", c.getName()); form.set("summary", c.getSummary()); form.set("description", c.getDescription()); form.set("org_sharing", c.getAccess()); form.set("gpg_key_url", c.getGPGKeyUrl()); form.set("gpg_key_id", c.getGPGKeyId()); form.set("gpg_key_fingerprint", c.getGPGKeyFp()); form.set("maintainer_name", c.getMaintainerName()); form.set("maintainer_phone", c.getMaintainerPhone()); form.set("maintainer_email", c.getMaintainerEmail()); form.set("support_policy", c.getSupportPolicy()); if (c.getChecksumTypeLabel() == null) { form.set("checksum", null); } else { form.set("checksum", c.getChecksumTypeLabel()); } if (c.isGloballySubscribable(ctx.getCurrentUser().getOrg())) { form.set("per_user_subscriptions", "all"); } else { form.set("per_user_subscriptions", "selected"); } if (c.getParentChannel() != null) { request.setAttribute("parent_name", c.getParentChannel().getName()); request.setAttribute("parent_id", c.getParentChannel().getId()); } else { request.setAttribute( "parent_name", LocalizationService.getInstance().getMessage("generic.jsp.none")); } if (c.getSources().isEmpty()) { request.setAttribute("last_sync", ""); } else { String lastSync = LocalizationService.getInstance().getMessage("channel.edit.repo.neversynced"); if (c.getLastSynced() != null) { lastSync = LocalizationService.getInstance().formatCustomDate(c.getLastSynced()); } request.setAttribute("last_sync", lastSync); if (!ChannelManager.getLatestSyncLogFiles(c).isEmpty()) { request.setAttribute( "log_url", DownloadManager.getChannelSyncLogDownloadPath(c, ctx.getCurrentUser())); } } request.setAttribute("channel_label", c.getLabel()); request.setAttribute("channel_name", c.getName()); request.setAttribute("channel_arch", c.getChannelArch().getName()); request.setAttribute("channel_arch_label", c.getChannelArch().getLabel()); } else { // default settings String channelName = LocalizationService.getInstance().getMessage("frontend.actions.channels.manager.create"); request.setAttribute("channel_name", channelName); form.set("org_sharing", "private"); form.set("per_user_subscriptions", "all"); form.set("checksum", "sha1"); } }
/** {@inheritDoc} */ @Override 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 params = new HashMap(); params.put(RequestContext.CID, chan.getId().toString()); ListHelper helper = new ListHelper(this, request, params); helper.execute(); TaskomaticApi taskomatic = new TaskomaticApi(); String oldCronExpr; try { oldCronExpr = taskomatic.getRepoSyncSchedule(chan, user); } catch (TaskomaticApiException except) { params.put("inactive", true); request.setAttribute("inactive", true); createErrorMessage(request, "repos.jsp.message.taskomaticdown", null); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } RecurringEventPicker picker = RecurringEventPicker.prepopulatePicker(request, "date", oldCronExpr); if (context.isSubmitted()) { StrutsDelegate strutsDelegate = getStrutsDelegate(); // check user permissions first if (!UserManager.verifyChannelAdmin(user, chan)) { createErrorMessage(request, "frontend.actions.channels.manager.add.permsfailure", null); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } if (chan.getSources().isEmpty()) { createErrorMessage(request, "repos.jsp.channel.norepos", null); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } try { if (context.wasDispatched("repos.jsp.button-sync")) { // schedule one time repo sync taskomatic.scheduleSingleRepoSync(chan, user); createSuccessMessage(request, "message.syncscheduled", chan.getName()); } else if (context.wasDispatched("schedule.button")) { if ((picker.isDisabled() || StringUtils.isEmpty(picker.getCronEntry())) && oldCronExpr != null) { taskomatic.unscheduleRepoSync(chan, user); createSuccessMessage(request, "message.syncschedule.disabled", chan.getName()); } else if (!StringUtils.isEmpty(picker.getCronEntry())) { Date date = taskomatic.scheduleRepoSync(chan, user, picker.getCronEntry()); createSuccessMessage(request, "message.syncscheduled", chan.getName()); } } } catch (TaskomaticApiException e) { if (e.getMessage().contains("InvalidParamException")) { createErrorMessage(request, "repos.jsp.message.invalidcron", picker.getCronEntry()); } else { createErrorMessage(request, "repos.jsp.message.schedulefailed", null); } return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } Map forwardParams = new HashMap(); forwardParams.put("cid", chan.getId()); return getStrutsDelegate().forwardParams(mapping.findForward("success"), forwardParams); } return mapping.findForward(RhnHelper.DEFAULT_FORWARD); }