Example usage for com.amazonaws.services.identitymanagement.model User getUserName

List of usage examples for com.amazonaws.services.identitymanagement.model User getUserName

Introduction

In this page you can find the example usage for com.amazonaws.services.identitymanagement.model User getUserName.

Prototype


public String getUserName() 

Source Link

Document

The friendly name identifying the user.

Usage

From source file:aws.example.iam.ListUsers.java

License:Open Source License

public static void main(String[] args) {

    final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient();

    boolean done = false;

    while (!done) {
        ListUsersRequest request = new ListUsersRequest();
        ListUsersResult response = iam.listUsers(request);

        for (User user : response.getUsers()) {
            System.out.format("Retrieved user %s", user.getUserName());
        }//from  w w  w  . j  ava  2s. c o m

        request.setMarker(response.getMarker());

        if (!response.getIsTruncated()) {
            done = true;
        }
    }
}

From source file:ch.cyberduck.core.iam.AmazonIdentityConfiguration.java

License:Open Source License

@Override
public void create(final String username, final String policy, final LoginCallback prompt)
        throws BackgroundException {
    if (log.isInfoEnabled()) {
        log.info(String.format("Create user %s with policy %s", username, policy));
    }/*from  ww w.j a va 2s .c om*/
    this.authenticated(new Authenticated<Void>() {
        @Override
        public Void call() throws BackgroundException {
            // Create new IAM credentials
            final AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(
                    new com.amazonaws.auth.AWSCredentials() {
                        @Override
                        public String getAWSAccessKeyId() {
                            return host.getCredentials().getUsername();
                        }

                        @Override
                        public String getAWSSecretKey() {
                            return host.getCredentials().getPassword();
                        }
                    }, configuration);
            try {
                // Create new IAM credentials
                User user;
                try {
                    user = client.createUser(new CreateUserRequest().withUserName(username)).getUser();
                } catch (EntityAlreadyExistsException e) {
                    user = client.getUser(new GetUserRequest().withUserName(username)).getUser();
                }
                final CreateAccessKeyResult key = client
                        .createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName()));
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Created access key %s for user %s", key, username));
                }
                // Write policy document to get read access
                client.putUserPolicy(new PutUserPolicyRequest(user.getUserName(), "Policy", policy));
                // Map virtual user name to IAM access key
                final String id = key.getAccessKey().getAccessKeyId();
                if (log.isInfoEnabled()) {
                    log.info(String.format("Map user %s to access key %s",
                            String.format("%s%s", prefix, username), id));
                }
                PreferencesFactory.get().setProperty(String.format("%s%s", prefix, username), id);
                // Save secret
                PasswordStoreFactory.get().addPassword(host.getProtocol().getScheme(), host.getPort(),
                        host.getHostname(), id, key.getAccessKey().getSecretAccessKey());
            } catch (AmazonClientException e) {
                throw new AmazonServiceExceptionMappingService().map("Cannot write user configuration", e);
            } finally {
                client.shutdown();
            }
            return null;
        }
    }, prompt);
}

From source file:com.denismo.aws.iam.LDAPIAMPoller.java

License:Apache License

private void populateUsersFromIAM() {
    AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials);

    try {//from w  ww .ja va2  s.co  m
        ListUsersResult res = client.listUsers();
        Set<String> allUsers = new HashSet<String>();
        while (true) {
            for (User user : res.getUsers()) {
                try {
                    Collection<Group> groups = client
                            .listGroupsForUser(new ListGroupsForUserRequest(user.getUserName())).getGroups();
                    Group primaryGroup = groups.size() > 0 ? groups.iterator().next() : null;
                    if (primaryGroup == null) {
                        LOG.warn("Unable to determine primary group for " + user.getUserName());
                        continue;
                    }
                    Entry groupEntry = getExistingGroup(primaryGroup);
                    if (groupEntry == null) {
                        LOG.warn("Unable to retrieve matching group entry for group "
                                + primaryGroup.getGroupName() + " user " + user.getUserName());
                        continue;
                    }
                    addUser(user, getUserAccessKey(client, user), groupEntry);
                    updateGroups(groups, user);
                    allUsers.add(user.getUserName());
                    LOG.info("Added user " + user.getUserName());
                } catch (Throwable e) {
                    LOG.error("Exception processing user " + user.getUserName(), e);
                }
            }
            if (res.isTruncated()) {
                res = client.listUsers(new ListUsersRequest().withMarker(res.getMarker()));
            } else {
                break;
            }
        }
        removeDeletedUsers(allUsers);
    } finally {
        client.shutdown();
    }
}

From source file:com.denismo.aws.iam.LDAPIAMPoller.java

License:Apache License

private String getUserAccessKey(AmazonIdentityManagementClient client, User user) {
    ListAccessKeysResult res = client/*from   w w w  .  j  av a2s  . c  o  m*/
            .listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName()));
    for (AccessKeyMetadata meta : res.getAccessKeyMetadata()) {
        if ("Active".equals(meta.getStatus())) {
            return meta.getAccessKeyId();
        }
    }
    return null;
}

From source file:com.denismo.aws.iam.LDAPIAMPoller.java

License:Apache License

private void addUser(User user, String accessKey, Entry group) throws LdapException {
    if (accessKey == null) {
        if (AWSIAMAuthenticator.getConfig().isSecretKeyLogin()) {
            LOG.info("User " + user.getUserName() + " has no active access keys");
            return;
        } else {/*  ww w. j a v  a  2s. c  o  m*/
            accessKey = "";
        }
    }
    Entry existingUser = getExistingUser(user);
    if (existingUser != null) {
        directory.getAdminSession().modify(existingUser.getDn(),
                new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "accessKey", accessKey),
                new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "gidNumber",
                        group.get("gidNumber").getString()));
        return;
    }

    DefaultEntry ent = new DefaultEntry(directory.getSchemaManager(),
            directory.getDnFactory().create(String.format(USER_FMT, user.getUserName())));
    ent.put(SchemaConstants.OBJECT_CLASS_AT, "posixAccount", "shadowAccount", "iamaccount");
    ent.put("accessKey", accessKey);
    ent.put("uid", user.getUserName());
    ent.put(SchemaConstants.ENTRY_CSN_AT, directory.getCSN().toString());
    ent.put(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
    ent.put("cn", user.getUserName());
    ent.put("uidNumber", allocateUserID(user.getArn()));
    if (group != null) {
        ent.put("gidNumber", group.get("gidNumber").getString());
    } else {
        ent.put("gidNumber", "1001");
    }
    ent.put("shadowLastChange", "10877");
    ent.put("shadowExpire", "-1");
    ent.put("shadowInactive", "-1");
    ent.put("shadowFlag", "0");
    ent.put("shadowWarning", "7");
    ent.put("shadowMin", "0");
    ent.put("shadowMax", "999999");
    ent.put("loginshell", "/bin/bash");
    ent.put("homedirectory", "/home/" + user.getUserName());
    ent.put("accountNumber", getAccountNumber(user.getArn()));
    add(ent);
}

From source file:com.denismo.aws.iam.LDAPIAMPoller.java

License:Apache License

private void updateGroups(Collection<Group> groups, User user) {
    Set<String> groupNames = new HashSet<String>();
    for (Group group : groups) {
        groupNames.add(group.getGroupName());
    }//from  w w  w .j  ava2 s . co  m
    Collection<Entry> allGroups = getAllEntries(groupsDN, "iamgroup");
    String userUid = user.getUserName();
    LOG.info("Updating groups for " + userUid);
    for (Entry group : allGroups) {
        LOG.info("Looking at group " + group.getDn());
        try {
            List<Modification> modifications = new ArrayList<Modification>();
            if (groupNames.contains(group.get(SchemaConstants.CN_AT).getString())) {
                if (!group.contains("memberUid", userUid)) {
                    modifications.add(
                            new DefaultModification(ModificationOperation.ADD_ATTRIBUTE, "memberUid", userUid));
                }
            } else {
                if (group.contains("memberUid", userUid)) {
                    modifications.add(new DefaultModification(ModificationOperation.REMOVE_ATTRIBUTE,
                            "memberUid", userUid));
                }
            }
            if (!modifications.isEmpty()) {
                LOG.info("Will modify group with " + modifications);
                directory.getAdminSession().modify(group.getDn(), modifications);
            }
        } catch (LdapException e) {
            LOG.error("Unable to update users in group " + group.getDn());
        }
    }
}

From source file:com.denismo.aws.iam.LDAPIAMPoller.java

License:Apache License

private Entry getExistingUser(User user) throws LdapException {
    LookupOperationContext lookupContext = new LookupOperationContext(directory.getAdminSession(),
            directory.getDnFactory().create(String.format(USER_FMT, user.getUserName())),
            SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES);

    try {// www.  j ava 2 s .  co m
        Entry userEntry = directory.getPartitionNexus().lookup(lookupContext);
        if (userEntry != null && userEntry.hasObjectClass("iamaccount")) {
            return userEntry;
        }
    } catch (LdapNoSuchObjectException e) {
        // Fallthrough
    }
    return null;
}

From source file:com.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.IamGroupDetail.java

License:Open Source License

private void buildUI(GetGroupResult detail) {

    JTabbedPane tabs = new JTabbedPane();
    tabs.add("Group", primaryScrollPane);

    final JTable usersTable = new JTable(usersTableModel);
    JScrollPane usersScrollPane = new JScrollPane(usersTable);
    tabs.add("Users", usersScrollPane);

    this.add(tabs, BorderLayout.CENTER);

    if (detail.getGroup() != null) {

        Group group = detail.getGroup();

        if (group.getCreateDate() != null) {
            primaryTableModel.addRow(new Object[] { "Created", getDateString(group.getCreateDate()) });
        }/*from www . j  a  v  a 2 s. com*/
        if (group.getArn() != null) {
            primaryTableModel.addRow(new Object[] { "Arn", group.getArn() });
        }
        if (group.getGroupId() != null) {
            primaryTableModel.addRow(new Object[] { "Group ID", group.getGroupId() });
        }
        if (group.getGroupName() != null) {
            primaryTableModel.addRow(new Object[] { "Group Name", group.getGroupName() });
        }
        if (group.getPath() != null) {
            primaryTableModel.addRow(new Object[] { "Path", group.getPath() });
        }

        /**
         * Users
         * 
         */
        usersTableModel.addColumn("Key");
        usersTableModel.addColumn("Value");
        usersTableModel.addColumn("User Previous Value");

        List<User> users = detail.getUsers();
        if (!users.isEmpty()) {
            for (User user : users) {

                if (user.getCreateDate() != null) {
                    primaryTableModel.addRow(new Object[] { "Created", getDateString(user.getCreateDate()) });
                }
                if (user.getArn() != null) {
                    primaryTableModel.addRow(new Object[] { "Arn", user.getArn() });
                }
                if (user.getPasswordLastUsed() != null) {
                    primaryTableModel.addRow(new Object[] { "Password Last Used", user.getPasswordLastUsed() });
                }
                if (user.getPath() != null) {
                    primaryTableModel.addRow(new Object[] { "Path", user.getPath() });
                }
                if (user.getUserId() != null) {
                    primaryTableModel.addRow(new Object[] { "User Id", user.getUserId() });
                }
                if (user.getUserName() != null) {
                    primaryTableModel.addRow(new Object[] { "User Name", user.getUserName() });
                }

            }
        }
    }
}

From source file:com.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.IamUserDetail.java

License:Open Source License

private void buildUI(GetUserResult detail) {

    this.add(primaryScrollPane, BorderLayout.CENTER);

    if (detail.getUser() != null) {

        User user = detail.getUser();

        if (user.getCreateDate() != null) {
            primaryTableModel.addRow(new Object[] { "Created", getDateString(user.getCreateDate()) });
        }//  www. j  ava  2s  .  c  o  m
        if (user.getArn() != null) {
            primaryTableModel.addRow(new Object[] { "Arn", user.getArn() });
        }
        if (user.getPasswordLastUsed() != null) {
            primaryTableModel.addRow(new Object[] { "Password Last Used", user.getPasswordLastUsed() });
        }
        if (user.getPath() != null) {
            primaryTableModel.addRow(new Object[] { "Path", user.getPath() });
        }
        if (user.getUserId() != null) {
            primaryTableModel.addRow(new Object[] { "User Id", user.getUserId() });
        }
        if (user.getUserName() != null) {
            primaryTableModel.addRow(new Object[] { "User Name", user.getUserName() });
        }

    }

}

From source file:com.vb.aws.services.mt.config.MFANotEnabledUsers.java

/**
 * /*from ww  w . j a v a  2s . c  o m*/
 * @param allMFANotEnabledUsers
 * @return List<Evaluation> returns list of Evaluation objects.
 */
private List<Evaluation> createEvaluations(List<User> allMFANotEnabledUsers) {

    List<Evaluation> evaluations = new ArrayList<>();

    if (allMFANotEnabledUsers == null || allMFANotEnabledUsers.size() > 0) {

        for (User user : allMFANotEnabledUsers) {

            String userName = user.getUserName();
            Evaluation evaluation = new Evaluation();
            evaluation.setComplianceResourceId(userName);
            evaluation.setComplianceResourceType(COMPLIANCE_RESOURCE_TYPE);
            evaluation.setComplianceType(ComplianceType.NON_COMPLIANT);
            evaluation.setOrderingTimestamp(new Date());
            evaluations.add(evaluation);
        }
    }

    System.out.println("INFO : Number of evaluations : " + evaluations.size());
    return evaluations;

}