Search in sources :

Example 96 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class BuiltinUsers method getApiToken.

@GET
@Path("{username}/api-token")
public Response getApiToken(@PathParam("username") String username, @QueryParam("password") String password) {
    boolean disabled = true;
    boolean lookupAllowed = settingsSvc.isTrueForKey(SettingsServiceBean.Key.AllowApiTokenLookupViaApi, false);
    if (lookupAllowed) {
        disabled = false;
    }
    if (disabled) {
        return error(Status.FORBIDDEN, "This API endpoint has been disabled.");
    }
    BuiltinUser u = null;
    if (retrievingApiTokenViaEmailEnabled) {
        u = builtinUserSvc.findByUsernameOrEmail(username);
    } else {
        u = builtinUserSvc.findByUserName(username);
    }
    if (u == null)
        return badRequest("Bad username or password");
    boolean passwordOk = PasswordEncryption.getVersion(u.getPasswordEncryptionVersion()).check(password, u.getEncryptedPassword());
    if (!passwordOk)
        return badRequest("Bad username or password");
    AuthenticatedUser authUser = authSvc.lookupUser(BuiltinAuthenticationProvider.PROVIDER_ID, u.getUserName());
    ApiToken t = authSvc.findApiTokenByUser(authUser);
    return (t != null) ? ok(t.getTokenString()) : notFound("User " + username + " does not have an API token");
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 97 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class BuiltinUsers method internalSave.

private Response internalSave(BuiltinUser user, String password, String key) {
    String expectedKey = settingsSvc.get(API_KEY_IN_SETTINGS);
    if (expectedKey == null) {
        return error(Status.SERVICE_UNAVAILABLE, "Dataverse config issue: No API key defined for built in user management");
    }
    if (!expectedKey.equals(key)) {
        return badApiKey(key);
    }
    ActionLogRecord alr = new ActionLogRecord(ActionLogRecord.ActionType.BuiltinUser, "create");
    try {
        if (password != null) {
            user.updateEncryptedPassword(PasswordEncryption.get().encrypt(password), PasswordEncryption.getLatestVersionNumber());
        }
        // Make sure the identifier is unique
        if ((builtinUserSvc.findByUserName(user.getUserName()) != null) || (authSvc.identifierExists(user.getUserName()))) {
            return error(Status.BAD_REQUEST, "username '" + user.getUserName() + "' already exists");
        }
        user = builtinUserSvc.save(user);
        AuthenticatedUser au = authSvc.createAuthenticatedUser(new UserRecordIdentifier(BuiltinAuthenticationProvider.PROVIDER_ID, user.getUserName()), user.getUserName(), user.getDisplayInfo(), false);
        /**
         * @todo Move this to
         * AuthenticationServiceBean.createAuthenticatedUser
         */
        boolean rootDataversePresent = false;
        try {
            Dataverse rootDataverse = dataverseSvc.findRootDataverse();
            if (rootDataverse != null) {
                rootDataversePresent = true;
            }
        } catch (Exception e) {
            logger.info("The root dataverse is not present. Don't send a notification to dataverseAdmin.");
        }
        if (rootDataversePresent) {
            userNotificationSvc.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
        }
        ApiToken token = new ApiToken();
        token.setTokenString(java.util.UUID.randomUUID().toString());
        token.setAuthenticatedUser(au);
        Calendar c = Calendar.getInstance();
        token.setCreateTime(new Timestamp(c.getTimeInMillis()));
        c.roll(Calendar.YEAR, 1);
        token.setExpireTime(new Timestamp(c.getTimeInMillis()));
        authSvc.save(token);
        JsonObjectBuilder resp = Json.createObjectBuilder();
        resp.add("user", json(user));
        resp.add("authenticatedUser", json(au));
        resp.add("apiToken", token.getTokenString());
        alr.setInfo("builtinUser:" + user.getUserName() + " authenticatedUser:" + au.getIdentifier());
        return ok(resp);
    } catch (EJBException ejbx) {
        alr.setActionResult(ActionLogRecord.Result.InternalError);
        alr.setInfo(alr.getInfo() + "// " + ejbx.getMessage());
        if (ejbx.getCausedByException() instanceof IllegalArgumentException) {
            return error(Status.BAD_REQUEST, "Bad request: can't save user. " + ejbx.getCausedByException().getMessage());
        } else {
            logger.log(Level.WARNING, "Error saving user: ", ejbx);
            return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + ejbx.getMessage());
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Error saving user", e);
        alr.setActionResult(ActionLogRecord.Result.InternalError);
        alr.setInfo(alr.getInfo() + "// " + e.getMessage());
        return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + e.getMessage());
    } finally {
        actionLogSvc.log(alr);
    }
}
Also used : UserRecordIdentifier(edu.harvard.iq.dataverse.authorization.UserRecordIdentifier) Calendar(java.util.Calendar) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) Timestamp(java.sql.Timestamp) EJBException(javax.ejb.EJBException) Date(java.util.Date) ActionLogRecord(edu.harvard.iq.dataverse.actionlogging.ActionLogRecord) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) JsonObjectBuilder(javax.json.JsonObjectBuilder) EJBException(javax.ejb.EJBException)

Example 98 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class UserServiceBean method retrieveRolesForUsers.

/**
 * Attempt to retrieve all the user roles in 1 query
 * Consider putting limits on this -- e.g. no more than 1,000 user identifiers or something similar
 *
 * @param userIdentifierList
 * @return
 */
private HashMap<String, List<String>> retrieveRolesForUsers(List<Object[]> userObjectList) {
    // Iterate through results, retrieving only the assignee identifiers
    // Note: userInfo[1], the assigneeIdentifier, cannot be null in the database
    // 
    List<String> userIdentifierList = userObjectList.stream().map(userInfo -> (String) userInfo[1]).collect(Collectors.toList());
    List<Integer> databaseIds = userObjectList.stream().map(userInfo -> (Integer) userInfo[0]).collect(Collectors.toList());
    if ((userIdentifierList == null) || (userIdentifierList.isEmpty())) {
        return null;
    }
    // -------------------------------------------------
    // Prepare a string to use within the SQL "a.assigneeidentifier IN (....)" clause
    // 
    // Note: This is not ideal but .setParameter was failing with attempts using:
    // 
    // Collection<String>, List<String>, String[]
    // 
    // This appears to be due to the JDBC driver or Postgres.  In this case SQL
    // injection isn't possible b/c the list of assigneeidentifier strings comes
    // from a previous query
    // 
    // Add '@' to each identifier and delimit the list by ","
    // -------------------------------------------------
    String identifierListString = userIdentifierList.stream().filter(x -> !Strings.isNullOrEmpty(x)).map(x -> "'@" + x + "'").collect(Collectors.joining(", "));
    // -------------------------------------------------
    // Create/Run the query to find directly assigned roles
    // -------------------------------------------------
    String qstr = "SELECT distinct a.assigneeidentifier,";
    qstr += " d.name";
    qstr += " FROM roleassignment a,";
    qstr += " dataverserole d";
    qstr += " WHERE d.id = a.role_id";
    qstr += " AND a.assigneeidentifier IN (" + identifierListString + ")";
    qstr += " ORDER by a.assigneeidentifier, d.name;";
    Query nativeQuery = em.createNativeQuery(qstr);
    List<Object[]> dbRoleResults = nativeQuery.getResultList();
    if (dbRoleResults == null) {
        return null;
    }
    HashMap<String, List<String>> userRoleLookup = new HashMap<>();
    String userIdentifier;
    String userRole;
    for (Object[] dbResultRow : dbRoleResults) {
        userIdentifier = UserUtil.getStringOrNull(dbResultRow[0]);
        userRole = UserUtil.getStringOrNull(dbResultRow[1]);
        if ((userIdentifier != null) && (userRole != null)) {
            // should never be null
            List<String> userRoleList = userRoleLookup.getOrDefault(userIdentifier, new ArrayList<String>());
            if (!userRoleList.contains(userRole)) {
                userRoleList.add(userRole);
                userRoleLookup.put(userIdentifier, userRoleList);
            }
        }
    }
    // And now the roles assigned via groups:
    // 1. One query for selecting all the groups to which these users may belong:
    HashMap<String, List<String>> groupsLookup = new HashMap<>();
    String idListString = StringUtils.join(databaseIds, ",");
    // A *RECURSIVE* native query, that finds all the groups that the specified
    // users are part of, BOTH by direct inclusion, AND via parent groups:
    qstr = "WITH RECURSIVE group_user AS ((" + " SELECT distinct g.groupalias, g.id, u.useridentifier" + "  FROM explicitgroup g, explicitgroup_authenticateduser e, authenticateduser u" + "  WHERE e.explicitgroup_id = g.id " + "   AND u.id IN (" + idListString + ")" + "   AND u.id = e.containedauthenticatedusers_id)" + "  UNION\n" + "   SELECT p.groupalias, p.id, c.useridentifier" + "    FROM group_user c, explicitgroup p, explicitgroup_explicitgroup e" + "    WHERE e.explicitgroup_id = p.id" + "     AND e.containedexplicitgroups_id = c.id)" + "SELECT distinct groupalias, useridentifier FROM group_user;";
    // System.out.println("qstr: " + qstr);
    nativeQuery = em.createNativeQuery(qstr);
    List<Object[]> groupResults = nativeQuery.getResultList();
    if (groupResults == null) {
        return userRoleLookup;
    }
    String groupIdentifiers = null;
    for (Object[] group : groupResults) {
        String alias = UserUtil.getStringOrNull(group[0]);
        String user = UserUtil.getStringOrNull(group[1]);
        if (alias != null) {
            alias = "&explicit/" + alias;
            if (groupIdentifiers == null) {
                groupIdentifiers = "'" + alias + "'";
            } else {
                groupIdentifiers += ", '" + alias + "'";
            }
            List<String> groupUserList = groupsLookup.getOrDefault(alias, new ArrayList<String>());
            if (!groupUserList.contains(user)) {
                groupUserList.add(user);
                groupsLookup.put(alias, groupUserList);
            }
        }
    }
    if (groupIdentifiers == null) {
        return userRoleLookup;
    }
    qstr = "SELECT distinct a.assigneeidentifier,";
    qstr += " d.name";
    qstr += " FROM roleassignment a,";
    qstr += " dataverserole d";
    qstr += " WHERE d.id = a.role_id";
    qstr += " AND a.assigneeidentifier IN (";
    qstr += groupIdentifiers;
    qstr += ") ORDER by a.assigneeidentifier, d.name;";
    // System.out.println("qstr: " + qstr);
    nativeQuery = em.createNativeQuery(qstr);
    dbRoleResults = nativeQuery.getResultList();
    if (dbRoleResults == null) {
        return userRoleLookup;
    }
    for (Object[] dbResultRow : dbRoleResults) {
        String groupIdentifier = UserUtil.getStringOrNull(dbResultRow[0]);
        String groupRole = UserUtil.getStringOrNull(dbResultRow[1]);
        if ((groupIdentifier != null) && (groupRole != null)) {
            // should never be null
            List<String> groupUserList = groupsLookup.get(groupIdentifier);
            if (groupUserList != null) {
                for (String groupUserIdentifier : groupUserList) {
                    groupUserIdentifier = "@" + groupUserIdentifier;
                    // System.out.println("Group user: "+groupUserIdentifier);
                    List<String> userRoleList = userRoleLookup.getOrDefault(groupUserIdentifier, new ArrayList<String>());
                    if (!userRoleList.contains(groupRole)) {
                        // System.out.println("User Role: "+groupRole);
                        userRoleList.add(groupRole);
                        userRoleLookup.put(groupUserIdentifier, userRoleList);
                    }
                }
            }
        }
    }
    return userRoleLookup;
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Stateless(javax.ejb.Stateless) UserUtil(edu.harvard.iq.dataverse.userdata.UserUtil) StringUtils(org.apache.commons.lang.StringUtils) Date(java.util.Date) IndexServiceBean(edu.harvard.iq.dataverse.search.IndexServiceBean) Timestamp(java.sql.Timestamp) HashMap(java.util.HashMap) EntityManager(javax.persistence.EntityManager) PersistenceContext(javax.persistence.PersistenceContext) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) List(java.util.List) Query(javax.persistence.Query) Strings(org.ocpsoft.common.util.Strings) Named(javax.inject.Named) EJB(javax.ejb.EJB) Query(javax.persistence.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List)

Example 99 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class RoleAssigneeServiceBean method getAssigneeAndRoleIdListFor.

public List<Object[]> getAssigneeAndRoleIdListFor(MyDataFilterParams filterParams) {
    if (filterParams == null) {
        throw new NullPointerException("Cannot be null! filterParams must be an instance of MyDataFilterParams");
    }
    AuthenticatedUser au = filterParams.getAuthenticatedUser();
    List<Long> roleIdList = filterParams.getRoleIds();
    if (au.getUserIdentifier() == null) {
        return null;
    }
    String roleAssigneeIdentifier = "@" + au.getUserIdentifier();
    // remove spaces from string
    roleAssigneeIdentifier = roleAssigneeIdentifier.replaceAll("\\s", "");
    List<String> userExplicitGroups = getUserExplicitGroups(au);
    List<String> userRunTimeGroups = getUserRuntimeGroups(filterParams.getDataverseRequest());
    String identifierClause = " WHERE r.assigneeIdentifier= '" + roleAssigneeIdentifier + "'";
    if (userExplicitGroups != null || userRunTimeGroups != null) {
        identifierClause = getGroupIdentifierClause(roleAssigneeIdentifier, userExplicitGroups, userRunTimeGroups);
    }
    String qstr = "SELECT r.definitionpoint_id, r.role_id";
    qstr += " FROM RoleAssignment r";
    qstr += identifierClause;
    qstr += getRoleIdListClause(roleIdList);
    qstr += ";";
    msg("qstr: " + qstr);
    return em.createNativeQuery(qstr).getResultList();
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 100 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class RoleAssigneeServiceBean method getRoleIdsFor.

public List<Object[]> getRoleIdsFor(DataverseRequest dataverseRequest, List<Long> dvObjectIdList) {
    if (dataverseRequest == null) {
        throw new NullPointerException("dataverseRequest cannot be null!");
    }
    AuthenticatedUser au = dataverseRequest.getAuthenticatedUser();
    if (au.getUserIdentifier() == null) {
        return null;
    }
    String roleAssigneeIdentifier = "@" + au.getUserIdentifier();
    // remove spaces from string
    roleAssigneeIdentifier = roleAssigneeIdentifier.replaceAll("\\s", "");
    List<String> userGroups = getUserExplicitGroups(au);
    List<String> userRunTimeGroups = getUserRuntimeGroups(dataverseRequest);
    String identifierClause = " WHERE r.assigneeIdentifier= '" + roleAssigneeIdentifier + "'";
    if (userGroups != null || userRunTimeGroups != null) {
        identifierClause = getGroupIdentifierClause(roleAssigneeIdentifier, userGroups, userRunTimeGroups);
    }
    String qstr = "SELECT r.definitionpoint_id, r.role_id";
    qstr += " FROM RoleAssignment r";
    qstr += identifierClause;
    qstr += getDvObjectIdListClause(dvObjectIdList);
    qstr += ";";
    return em.createNativeQuery(qstr).getResultList();
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Aggregations

AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)125 Dataverse (edu.harvard.iq.dataverse.Dataverse)24 Timestamp (java.sql.Timestamp)24 Date (java.util.Date)24 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)23 Dataset (edu.harvard.iq.dataverse.Dataset)22 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)21 Path (javax.ws.rs.Path)19 EJBException (javax.ejb.EJBException)16 ArrayList (java.util.ArrayList)14 User (edu.harvard.iq.dataverse.authorization.users.User)13 DataFile (edu.harvard.iq.dataverse.DataFile)11 IOException (java.io.IOException)11 JsonObjectBuilder (javax.json.JsonObjectBuilder)11 POST (javax.ws.rs.POST)11 Test (org.junit.Test)11 BuiltinUser (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)10 SwordError (org.swordapp.server.SwordError)10 DataverseRole (edu.harvard.iq.dataverse.authorization.DataverseRole)8 PermissionException (edu.harvard.iq.dataverse.engine.command.exception.PermissionException)8