Search in sources :

Example 16 with OnmsUser

use of org.opennms.netmgt.model.OnmsUser in project opennms by OpenNMS.

the class SpringSecurityUserDaoImplIT method testGetByUsernameTempUser.

@Test
@DirtiesContext
public void testGetByUsernameTempUser() throws Exception {
    final OnmsUser newUser = new OnmsUser("tempuser");
    newUser.setPassword("18126E7BD3F84B3F3E4DF094DEF5B7DE");
    m_userManager.save(newUser);
    final SpringSecurityUser user = ((SpringSecurityUserDao) m_springSecurityDao).getByUsername("tempuser");
    assertNotNull("user object should not be null", user);
    assertEquals("OnmsUser name", "tempuser", user.getUsername());
    assertEquals("Full name", null, user.getFullName());
    assertEquals("Comments", null, user.getComments());
    assertEquals("Password", "18126E7BD3F84B3F3E4DF094DEF5B7DE", user.getPassword());
    Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
    assertNotNull("authorities should not be null", authorities);
    assertEquals("authorities size", 1, authorities.size());
    assertContainsAuthority(Authentication.ROLE_USER, authorities);
    assertNoWarningsOrGreater();
}
Also used : OnmsUser(org.opennms.netmgt.model.OnmsUser) Test(org.junit.Test) DirtiesContext(org.springframework.test.annotation.DirtiesContext)

Example 17 with OnmsUser

use of org.opennms.netmgt.model.OnmsUser in project opennms by OpenNMS.

the class SpringSecurityUserDaoImpl method getByUsername.

/* (non-Javadoc)
     * @see org.opennms.web.springframework.security.SpringSecurityUserDao#getByUsername(java.lang.String)
     */
@Override
public SpringSecurityUser getByUsername(String username) {
    reloadIfNecessary();
    final OnmsUser user = m_users.get(username);
    if (user == null) {
        return null;
    }
    final SpringSecurityUser springUser = new SpringSecurityUser(user);
    springUser.setAuthorities(getAuthoritiesByUsername(username));
    return springUser;
}
Also used : OnmsUser(org.opennms.netmgt.model.OnmsUser)

Example 18 with OnmsUser

use of org.opennms.netmgt.model.OnmsUser in project opennms by OpenNMS.

the class UserRestService method addRole.

@PUT
@Path("{userCriteria}/roles/{roleName}")
public Response addRole(@Context final SecurityContext securityContext, @PathParam("userCriteria") final String userCriteria, @PathParam("roleName") final String roleName) {
    writeLock();
    try {
        if (!hasEditRights(securityContext)) {
            throw getException(Status.BAD_REQUEST, "User {} does not have write access to users!", securityContext.getUserPrincipal().getName());
        }
        if (!Authentication.isValidRole(roleName)) {
            throw getException(Status.BAD_REQUEST, "Invalid role {}!", roleName);
        }
        final OnmsUser user = getOnmsUser(userCriteria);
        LOG.debug("addRole: updating user {}", user);
        boolean modified = false;
        if (!user.getRoles().contains(roleName)) {
            user.getRoles().add(roleName);
            modified = true;
        }
        if (modified) {
            LOG.debug("addRole: user {} updated", user);
            try {
                m_userManager.save(user);
            } catch (final Throwable t) {
                throw getException(Status.INTERNAL_SERVER_ERROR, t);
            }
            return Response.noContent().build();
        }
        return Response.notModified().build();
    } finally {
        writeUnlock();
    }
}
Also used : OnmsUser(org.opennms.netmgt.model.OnmsUser) Path(javax.ws.rs.Path) PUT(javax.ws.rs.PUT)

Example 19 with OnmsUser

use of org.opennms.netmgt.model.OnmsUser in project opennms by OpenNMS.

the class SpringSecurityUserDaoImpl method parseUsers.

/**
 * Parses the users.
 *
 * <p>Convenience method for parsing the users.xml file.</p>
 * <p>This method is synchronized so only one thread at a time
 * can parse the users.xml file and create the <code>principal</code>
 * instance variable.</p>
 *
 * @throws DataRetrievalFailureException the data retrieval failure exception
 */
private void parseUsers() throws DataRetrievalFailureException {
    final HashMap<String, OnmsUser> users = new HashMap<String, OnmsUser>();
    final Map<String, List<GrantedAuthority>> roles = new HashMap<String, List<GrantedAuthority>>();
    try {
        for (final OnmsUser user : m_userManager.getOnmsUserList()) {
            final String username = user.getUsername();
            users.put(username, user);
            if (!roles.containsKey(username)) {
                roles.put(username, new LinkedList<GrantedAuthority>());
            }
            for (final String role : user.getRoles()) {
                if (Authentication.isValidRole(role)) {
                    roles.get(username).add(getAuthority(role));
                    if (Authentication.ROLE_ADMIN.equals(role)) {
                        roles.get(username).add(getAuthority(Authentication.ROLE_USER));
                    }
                }
            }
        }
    } catch (final Throwable t) {
        throw new DataRetrievalFailureException("Unable to get user list.", t);
    }
    LOG.debug("Loaded the users.xml file with {} users", users.size());
    m_usersLastModified = m_userManager.getLastModified();
    m_users = users;
    m_roles = roles;
}
Also used : HashMap(java.util.HashMap) OnmsUser(org.opennms.netmgt.model.OnmsUser) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) List(java.util.List) LinkedList(java.util.LinkedList) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException)

Example 20 with OnmsUser

use of org.opennms.netmgt.model.OnmsUser in project opennms by OpenNMS.

the class MagicUsersMigratorOffline method execute.

/* (non-Javadoc)
     * @see org.opennms.upgrade.api.OnmsUpgrade#execute()
     */
@Override
public void execute() throws OnmsUpgradeException {
    if (!canRun()) {
        log("Error: ignoring the execution of the task because the file magic-users.properties was not found. Maybe the task was already successfully executed before.\n");
        return;
    }
    // Parse read-only attributes
    final List<String> readOnlyUsers = new ArrayList<>();
    try {
        boolean readOnly = false;
        for (String line : Files.readAllLines(usersFile.toPath())) {
            if (line.contains("read-only")) {
                Matcher m = Pattern.compile("read-only=\"(.+)\"").matcher(line);
                if (m.find()) {
                    readOnly = Boolean.parseBoolean(m.group(1));
                }
            }
            if (line.contains("user-id")) {
                if (readOnly) {
                    Matcher m = Pattern.compile("user-id[>](.+)[<][/]user-id").matcher(line);
                    if (m.find()) {
                        log("Warning: User %s has read-only flag\n", m.group(1));
                        readOnlyUsers.add(m.group(1));
                    }
                }
                readOnly = false;
            }
        }
        if (!readOnlyUsers.isEmpty()) {
            log("Removing the read-only flags from users.xml\n");
            String content = new String(Files.readAllBytes(usersFile.toPath()), StandardCharsets.UTF_8);
            content = content.replaceAll(" read-only=\".+\"", "");
            Files.write(usersFile.toPath(), content.getBytes(StandardCharsets.UTF_8));
        }
    } catch (Exception e) {
        throw new OnmsUpgradeException("Can't fix configuration because " + e.getMessage(), e);
    }
    log("Moving security roles into users.xml...\n");
    try {
        UserFactory.init();
        UserManager userManager = UserFactory.getInstance();
        // Retrieve all the currently configured users.
        final List<OnmsUser> users = new ArrayList<>();
        for (final String userName : userManager.getUserNames()) {
            log("Loading configured user: %s...\n", userName);
            users.add(userManager.getOnmsUser(userName));
        }
        // Parse magic-users.properties
        Properties properties = new Properties();
        if (magicUsersFile.exists()) {
            properties.load(new FileInputStream(magicUsersFile));
        } else if (magicUsersFileRPM.exists()) {
            properties.load(new FileInputStream(magicUsersFileRPM));
        } else if (magicUsersFileDEB.exists()) {
            properties.load(new FileInputStream(magicUsersFileDEB));
        } else {
            throw new IllegalArgumentException("Can't find magic-users.properties, or any RPM/DEB backup of it");
        }
        // Look up for custom users and their passwords
        String[] configuredUsers = BundleLists.parseBundleList(properties.getProperty("users"));
        for (String user : configuredUsers) {
            String username = properties.getProperty("user." + user + ".username");
            String password = properties.getProperty("user." + user + ".password");
            OnmsUser newUser = new OnmsUser();
            newUser.setUsername(username);
            newUser.setFullName(user);
            newUser.setComments("This is a system user, do not delete");
            newUser.setPassword(userManager.encryptedPassword(password, true));
            newUser.setPasswordSalted(true);
            users.add(0, newUser);
        }
        // Configure security roles
        String[] configuredRoles = BundleLists.parseBundleList(properties.getProperty("roles"));
        for (final String role : configuredRoles) {
            String userList = properties.getProperty("role." + role + ".users");
            if (userList == null) {
                log("Warning: Role configuration for '%s' does not have 'users' parameter.  Expecting a 'role.%s.users' property. The role will not be usable.\n", role, role);
                continue;
            }
            String[] authUsers = BundleLists.parseBundleList(userList);
            boolean notInDefaultGroup = "true".equals(properties.getProperty("role." + role + ".notInDefaultGroup"));
            String securityRole = "ROLE_" + role.toUpperCase();
            List<String> customRoles = new ArrayList<>();
            for (final String username : authUsers) {
                OnmsUser onmsUser = getUser(users, username);
                if (onmsUser == null) {
                    log("Warning: User %s doesn't exist on users.xml, Ignoring.\n", username);
                } else {
                    addRole(onmsUser, securityRole);
                    if (!notInDefaultGroup && !securityRole.equals(Authentication.ROLE_ADMIN)) {
                        addRole(onmsUser, Authentication.ROLE_USER);
                    }
                    if (!Authentication.isValidRole(securityRole)) {
                        log("Warning: %s is a custom role.\n", securityRole);
                        customRoles.add(role);
                    }
                }
            }
            if (!customRoles.isEmpty()) {
                String roleList = StringUtils.join(customRoles, ',');
                log("Creating %s with roles: %s\n", Authentication.ROLE_CONFIGURATION_FILE, roleList);
                Properties p = new Properties();
                p.put("roles", roleList);
                File configFile = new File(ConfigFileConstants.getHome(), "etc" + File.separator + Authentication.ROLE_CONFIGURATION_FILE);
                p.store(new FileWriter(configFile), "Custom Roles");
            }
        }
        // Update users.xml
        for (final OnmsUser user : users) {
            if (readOnlyUsers.contains(user.getUsername())) {
                addRole(user, Authentication.ROLE_READONLY);
                if (!user.getRoles().contains(Authentication.ROLE_USER)) {
                    addRole(user, Authentication.ROLE_USER);
                }
            }
            userManager.save(user);
        }
    } catch (Throwable e) {
        throw new OnmsUpgradeException("Can't fix configuration because " + e.getMessage(), e);
    }
}
Also used : Matcher(java.util.regex.Matcher) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) Properties(java.util.Properties) OnmsUpgradeException(org.opennms.upgrade.api.OnmsUpgradeException) OnmsUpgradeException(org.opennms.upgrade.api.OnmsUpgradeException) FileInputStream(java.io.FileInputStream) UserManager(org.opennms.netmgt.config.UserManager) OnmsUser(org.opennms.netmgt.model.OnmsUser) File(java.io.File)

Aggregations

OnmsUser (org.opennms.netmgt.model.OnmsUser)21 Test (org.junit.Test)8 Path (javax.ws.rs.Path)5 User (org.opennms.netmgt.config.users.User)5 ArrayList (java.util.ArrayList)2 DELETE (javax.ws.rs.DELETE)2 PUT (javax.ws.rs.PUT)2 OnmsUserList (org.opennms.netmgt.model.OnmsUserList)2 DirtiesContext (org.springframework.test.annotation.DirtiesContext)2 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Properties (java.util.Properties)1 ExecutorService (java.util.concurrent.ExecutorService)1 Future (java.util.concurrent.Future)1 Matcher (java.util.regex.Matcher)1