Example usage for org.springframework.security.access.hierarchicalroles RoleHierarchy getReachableGrantedAuthorities

List of usage examples for org.springframework.security.access.hierarchicalroles RoleHierarchy getReachableGrantedAuthorities

Introduction

In this page you can find the example usage for org.springframework.security.access.hierarchicalroles RoleHierarchy getReachableGrantedAuthorities.

Prototype

public Collection<? extends GrantedAuthority> getReachableGrantedAuthorities(
        Collection<? extends GrantedAuthority> authorities);

Source Link

Document

Returns an array of all reachable authorities.

Usage

From source file:org.opendatakit.persistence.table.OdkTablesUserInfoTable.java

public static synchronized final OdkTablesUserInfoTable getOdkTablesUserInfo(String uriUser,
        Set<GrantedAuthority> grants, CallingContext callingContext) throws ODKDatastoreException,
        ODKTaskLockException, ODKEntityPersistException, ODKOverQuotaException, PermissionDeniedException {
    Datastore ds = callingContext.getDatastore();

    OdkTablesUserInfoTable prototype = OdkTablesUserInfoTable.assertRelation(callingContext);

    Log log = LogFactory.getLog(FileManifestManager.class);

    log.info("TablesUserPermissionsImpl: " + uriUser);

    RoleHierarchy roleHierarchy = (RoleHierarchy) callingContext.getHierarchicalRoleRelationships();
    Collection<? extends GrantedAuthority> roles = roleHierarchy.getReachableGrantedAuthorities(grants);
    boolean hasSynchronize = roles
            .contains(new SimpleGrantedAuthority(GrantedAuthorityName.ROLE_SYNCHRONIZE_TABLES.name()));
    boolean hasSuperUser = roles
            .contains(new SimpleGrantedAuthority(GrantedAuthorityName.ROLE_SUPER_USER_TABLES.name()));
    boolean hasAdminister = roles
            .contains(new SimpleGrantedAuthority(GrantedAuthorityName.ROLE_ADMINISTER_TABLES.name()));

    if (hasSynchronize || hasSuperUser || hasAdminister) {

        String uriForUser = null;
        String externalUID = null;

        if (uriUser.equals(User.ANONYMOUS_USER)) {
            externalUID = User.ANONYMOUS_USER;
            uriForUser = User.ANONYMOUS_USER;
        } else {//w  w  w  .  j  a  va2  s .com

            RegisteredUsersTable user = RegisteredUsersTable.getUserByUri(uriUser, ds,
                    callingContext.getCurrentUser());
            // Determine the external UID that will identify this user
            externalUID = null;
            if (user.getUsername() != null) {
                externalUID = SecurityConsts.USERNAME_COLON + user.getUsername();
            }
            uriForUser = uriUser;
        }

        OdkTablesUserInfoTable odkTablesUserInfo = null;
        odkTablesUserInfo = OdkTablesUserInfoTable.getCurrentUserInfo(uriForUser, callingContext);
        if (odkTablesUserInfo == null) {
            //
            // GAIN LOCK
            OdkTablesLockTemplate tablesUserPermissions = new OdkTablesLockTemplate(externalUID,
                    ODKTablesTaskLockType.TABLES_USER_PERMISSION_CREATION,
                    OdkTablesLockTemplate.DelayStrategy.SHORT, callingContext);
            try {
                tablesUserPermissions.acquire();
                // attempt to re-fetch the record.
                // If this succeeds, then we had multiple suitors; the other one beat
                // us.
                odkTablesUserInfo = OdkTablesUserInfoTable.getCurrentUserInfo(uriForUser, callingContext);
                if (odkTablesUserInfo != null) {
                    return odkTablesUserInfo;
                }
                // otherwise, create a record
                odkTablesUserInfo = ds.createEntityUsingRelation(prototype, callingContext.getCurrentUser());
                odkTablesUserInfo.setUriUser(uriForUser);
                odkTablesUserInfo.setOdkTablesUserId(externalUID);
                odkTablesUserInfo.persist(callingContext);
                return odkTablesUserInfo;
            } finally {
                tablesUserPermissions.release();
            }
        } else {
            return odkTablesUserInfo;
        }
    } else {
        throw new PermissionDeniedException("User does not have access to ODK Tables");
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java

private static Collection<GrantedAuthority> findInferredAuthorities(
        final Collection<GrantedAuthority> granted) {
    RoleHierarchy roleHierarchy = getBean("roleHierarchy");
    Collection<GrantedAuthority> reachable = roleHierarchy.getReachableGrantedAuthorities(granted);
    if (reachable == null) {
        return Collections.emptyList();
    }//from   w  w w .  j  ava  2 s. c  om
    return reachable;
}

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

private static Collection<? extends GrantedAuthority> findInferredAuthorities(
        final Collection<GrantedAuthority> granted) {
    RoleHierarchy roleHierarchy = getBean("roleHierarchy");
    Collection<? extends GrantedAuthority> reachable = roleHierarchy.getReachableGrantedAuthorities(granted);
    if (reachable == null) {
        return Collections.emptyList();
    }//from   w ww. ja  v  a2s. com
    return reachable;
}

From source file:org.opendatakit.aggregate.servlet.GetGrantedRolesServlet.java

/**
 * Handler for HTTP Get request that returns the list of roles assigned to this user.
 * /*from   ww w.ja va  2  s . com*/
 * Assumed to return a entity body that is a JSON serialization of a list.
 *
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    Set<GrantedAuthority> grants = cc.getCurrentUser().getDirectAuthorities();
    RoleHierarchy rh = (RoleHierarchy) cc.getBean(SecurityBeanDefs.ROLE_HIERARCHY_MANAGER);
    Collection<? extends GrantedAuthority> roles = rh.getReachableGrantedAuthorities(grants);
    ArrayList<String> roleNames = new ArrayList<String>();
    for (GrantedAuthority a : roles) {
        if (a.getAuthority().startsWith(GrantedAuthorityName.ROLE_PREFIX)) {
            roleNames.add(a.getAuthority());
        }
    }

    resp.addHeader(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION);
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Credentials", "true");
    resp.addHeader(HttpHeaders.HOST, cc.getServerURL());
    resp.setContentType(HtmlConsts.RESP_TYPE_JSON);
    resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE);

    PrintWriter out = resp.getWriter();
    out.write(mapper.writeValueAsString(roleNames));
    out.flush();

    resp.setStatus(HttpStatus.SC_OK);
}

From source file:org.opendatakit.api.users.RoleService.java

@GET
@ApiOperation(response = String.class, responseContainer = "List", value = "Returns list of roles granted to the currently authenticated (or anonymous) user.")
@Path("granted")
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
public Response getGranted(@Context ServletContext sc, @Context HttpServletRequest req,
        @Context HttpHeaders httpHeaders) throws IOException {

    Set<GrantedAuthority> grants = callingContext.getCurrentUser().getDirectAuthorities();
    RoleHierarchy rh = (RoleHierarchy) callingContext.getHierarchicalRoleRelationships();
    Collection<? extends GrantedAuthority> roles = rh.getReachableGrantedAuthorities(grants);
    ArrayList<String> roleNames = new ArrayList<String>();
    for (GrantedAuthority a : roles) {
        if (a.getAuthority().startsWith(GrantedAuthorityName.ROLE_PREFIX)) {
            roleNames.add(a.getAuthority());
        }/*w w  w.  j  a v  a  2s  . c om*/
    }

    // Need to set host header?  original has     
    // resp.addHeader(HttpHeaders.HOST, cc.getServerURL());

    return Response.ok(mapper.writeValueAsString(roleNames)).encoding(BasicConsts.UTF8_ENCODE)
            .type(MediaType.APPLICATION_JSON)
            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}

From source file:org.opendatakit.security.server.SecurityServiceUtil.java

/**
 * Get the complete set of granted authorities (ROLE and RUN_AS grants) this user possesses.
 * //from w w  w  .j av  a2s  .  c  o m
 * @param cc
 * @return
 * @throws ODKDatastoreException
 */
public static TreeSet<GrantedAuthorityName> getCurrentUserSecurityInfo(CallingContext cc)
        throws ODKDatastoreException {
    User user = cc.getCurrentUser();
    TreeSet<GrantedAuthorityName> authorities = new TreeSet<GrantedAuthorityName>();
    if (user.isAnonymous()) {
        RoleHierarchy hierarchy = cc.getHierarchicalRoleRelationships();
        Set<GrantedAuthority> badGrants = new TreeSet<GrantedAuthority>();
        // The assigned groups are the specialGroup that this user defines
        // (i.e., anonymous or daemon) plus all directly-assigned assignable
        // permissions.
        GrantedAuthority specialAuth = new SimpleGrantedAuthority(
                GrantedAuthorityName.USER_IS_ANONYMOUS.name());

        Collection<? extends GrantedAuthority> auths = hierarchy
                .getReachableGrantedAuthorities(Collections.singletonList(specialAuth));
        for (GrantedAuthority auth : auths) {
            GrantedAuthorityName name = mapName(auth, badGrants);
            if (name != null && !GrantedAuthorityName.permissionsCanBeAssigned(auth.getAuthority())) {
                authorities.add(name);
            }
        }
        removeBadGrantedAuthorities(badGrants, cc);
    } else {
        RegisteredUsersTable t;
        t = RegisteredUsersTable.getUserByUri(user.getUriUser(), cc.getDatastore(), user);

        Datastore ds = cc.getDatastore();
        RoleHierarchy hierarchy = (RoleHierarchy) cc.getHierarchicalRoleRelationships();
        Set<GrantedAuthority> grants = UserGrantedAuthority.getGrantedAuthorities(user.getUriUser(), ds, user);
        Set<GrantedAuthority> badGrants = new TreeSet<GrantedAuthority>();
        TreeSet<GrantedAuthorityName> groups = new TreeSet<GrantedAuthorityName>();
        for (GrantedAuthority grant : grants) {
            GrantedAuthorityName name = mapName(grant, badGrants);
            if (name != null) {
                if (GrantedAuthorityName.permissionsCanBeAssigned(grant.getAuthority())) {
                    groups.add(name);
                } else {
                    authorities.add(name);
                }
            }
        }
        Collection<? extends GrantedAuthority> auths = hierarchy.getReachableGrantedAuthorities(grants);
        for (GrantedAuthority auth : auths) {
            GrantedAuthorityName name = mapName(auth, badGrants);
            if (name != null && !GrantedAuthorityName.permissionsCanBeAssigned(auth.getAuthority())) {
                authorities.add(name);
            }
        }
        removeBadGrantedAuthorities(badGrants, cc);
    }
    return authorities;
}

From source file:org.opendatakit.security.server.SecurityServiceUtil.java

public static void setAuthenticationLists(UserSecurityInfo userInfo, String uriUser, CallingContext cc)
        throws ODKDatastoreException {
    Datastore ds = cc.getDatastore();/*from w w  w .ja v a  2 s  .c  o m*/
    User user = cc.getCurrentUser();
    RoleHierarchy hierarchy = (RoleHierarchy) cc.getHierarchicalRoleRelationships();
    Set<GrantedAuthority> grants = UserGrantedAuthority.getGrantedAuthorities(uriUser, ds, user);
    Set<GrantedAuthority> badGrants = new TreeSet<GrantedAuthority>();
    TreeSet<GrantedAuthorityName> groups = new TreeSet<GrantedAuthorityName>();
    TreeSet<GrantedAuthorityName> authorities = new TreeSet<GrantedAuthorityName>();
    for (GrantedAuthority grant : grants) {
        GrantedAuthorityName name = mapName(grant, badGrants);
        if (name != null) {
            if (GrantedAuthorityName.permissionsCanBeAssigned(grant.getAuthority())) {
                groups.add(name);
            } else {
                authorities.add(name);
            }
        }
    }
    Collection<? extends GrantedAuthority> auths = hierarchy.getReachableGrantedAuthorities(grants);
    for (GrantedAuthority auth : auths) {
        GrantedAuthorityName name = mapName(auth, badGrants);
        if (name != null && !GrantedAuthorityName.permissionsCanBeAssigned(auth.getAuthority())) {
            authorities.add(name);
        }
    }
    userInfo.setAssignedUserGroups(groups);
    userInfo.setGrantedAuthorities(authorities);
    removeBadGrantedAuthorities(badGrants, cc);
}

From source file:org.opendatakit.security.server.SecurityServiceUtil.java

public static void setAuthenticationListsForSpecialUser(UserSecurityInfo userInfo,
        GrantedAuthorityName specialGroup, CallingContext cc) throws DatastoreFailureException {
    RoleHierarchy hierarchy = (RoleHierarchy) cc.getHierarchicalRoleRelationships();
    Set<GrantedAuthority> badGrants = new TreeSet<GrantedAuthority>();
    // The assigned groups are the specialGroup that this user defines
    // (i.e., anonymous or daemon) plus all directly-assigned assignable
    // permissions.
    TreeSet<GrantedAuthorityName> groups = new TreeSet<GrantedAuthorityName>();
    TreeSet<GrantedAuthorityName> authorities = new TreeSet<GrantedAuthorityName>();
    groups.add(specialGroup);/*from   ww  w  .j  a  v a  2  s  .c o  m*/
    GrantedAuthority specialAuth = new SimpleGrantedAuthority(specialGroup.name());
    try {
        Set<GrantedAuthority> auths = GrantedAuthorityHierarchyTable
                .getSubordinateGrantedAuthorities(specialAuth, cc);
        for (GrantedAuthority auth : auths) {
            GrantedAuthorityName name = mapName(auth, badGrants);
            if (name != null) {
                groups.add(name);
            }
        }
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        throw new DatastoreFailureException("Unable to retrieve granted authorities of " + specialGroup.name());
    }

    Collection<? extends GrantedAuthority> auths = hierarchy
            .getReachableGrantedAuthorities(Collections.singletonList(specialAuth));
    for (GrantedAuthority auth : auths) {
        GrantedAuthorityName name = mapName(auth, badGrants);
        if (name != null && !GrantedAuthorityName.permissionsCanBeAssigned(auth.getAuthority())) {
            authorities.add(name);
        }
    }
    userInfo.setAssignedUserGroups(groups);
    userInfo.setGrantedAuthorities(authorities);
    try {
        removeBadGrantedAuthorities(badGrants, cc);
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
    }
}

From source file:org.opendatakit.aggregate.odktables.security.OdkTablesUserInfoTable.java

public static synchronized final OdkTablesUserInfoTable getOdkTablesUserInfo(String uriUser,
        Set<GrantedAuthority> grants, CallingContext cc) throws ODKDatastoreException, ODKTaskLockException,
        ODKEntityPersistException, ODKOverQuotaException, PermissionDeniedException {
    Datastore ds = cc.getDatastore();// w w w.  ja  v  a 2  s  .  c o  m

    OdkTablesUserInfoTable prototype = OdkTablesUserInfoTable.assertRelation(cc);

    Log log = LogFactory.getLog(FileManifestManager.class);

    log.info("TablesUserPermissionsImpl: " + uriUser);

    RoleHierarchy rh = (RoleHierarchy) cc.getBean(SecurityBeanDefs.ROLE_HIERARCHY_MANAGER);
    Collection<? extends GrantedAuthority> roles = rh.getReachableGrantedAuthorities(grants);
    boolean hasSynchronize = roles
            .contains(new SimpleGrantedAuthority(GrantedAuthorityName.ROLE_SYNCHRONIZE_TABLES.name()));
    boolean hasAdminister = roles
            .contains(new SimpleGrantedAuthority(GrantedAuthorityName.ROLE_ADMINISTER_TABLES.name()));

    if (hasSynchronize || hasAdminister) {

        String uriForUser = null;
        String externalUID = null;

        if (uriUser.equals(User.ANONYMOUS_USER)) {
            externalUID = User.ANONYMOUS_USER;
            uriForUser = User.ANONYMOUS_USER;
        } else {

            RegisteredUsersTable user = RegisteredUsersTable.getUserByUri(uriUser, ds, cc.getCurrentUser());
            // Determine the external UID that will identify this user
            externalUID = null;
            if (user.getEmail() != null) {
                externalUID = user.getEmail();
            } else if (user.getUsername() != null) {
                externalUID = SecurityUtils.USERNAME_COLON + user.getUsername();
            }
            uriForUser = uriUser;
        }

        OdkTablesUserInfoTable odkTablesUserInfo = null;
        odkTablesUserInfo = OdkTablesUserInfoTable.getCurrentUserInfo(uriForUser, cc);
        if (odkTablesUserInfo == null) {
            //
            // GAIN LOCK
            LockTemplate tablesUserPermissions = new LockTemplate(externalUID,
                    ODKTablesTaskLockType.TABLES_USER_PERMISSION_CREATION, cc);
            try {
                tablesUserPermissions.acquire();
                // attempt to re-fetch the record.
                // If this succeeds, then we had multiple suitors; the other one beat
                // us.
                odkTablesUserInfo = OdkTablesUserInfoTable.getCurrentUserInfo(uriForUser, cc);
                if (odkTablesUserInfo != null) {
                    return odkTablesUserInfo;
                }
                // otherwise, create a record
                odkTablesUserInfo = ds.createEntityUsingRelation(prototype, cc.getCurrentUser());
                odkTablesUserInfo.setUriUser(uriForUser);
                odkTablesUserInfo.setOdkTablesUserId(externalUID);
                odkTablesUserInfo.persist(cc);
                return odkTablesUserInfo;
            } finally {
                tablesUserPermissions.release();
            }
        } else {
            return odkTablesUserInfo;
        }
    } else {
        throw new PermissionDeniedException("User does not have access to ODK Tables");
    }
}

From source file:org.opendatakit.common.security.server.SecurityServiceUtil.java

static void setAuthenticationLists(UserSecurityInfo userInfo, String uriUser, CallingContext cc)
        throws ODKDatastoreException {
    Datastore ds = cc.getDatastore();/*  w  w w  .ja  va 2 s. c om*/
    User user = cc.getCurrentUser();
    RoleHierarchy hierarchy = (RoleHierarchy) cc.getBean("hierarchicalRoleRelationships");
    Set<GrantedAuthority> grants = UserGrantedAuthority.getGrantedAuthorities(uriUser, ds, user);
    Set<GrantedAuthority> badGrants = new TreeSet<GrantedAuthority>();
    TreeSet<GrantedAuthorityName> groups = new TreeSet<GrantedAuthorityName>();
    TreeSet<GrantedAuthorityName> authorities = new TreeSet<GrantedAuthorityName>();
    for (GrantedAuthority grant : grants) {
        GrantedAuthorityName name = mapName(grant, badGrants);
        if (name != null) {
            if (GrantedAuthorityName.permissionsCanBeAssigned(grant.getAuthority())) {
                groups.add(name);
            } else {
                authorities.add(name);
            }
        }
    }
    Collection<? extends GrantedAuthority> auths = hierarchy.getReachableGrantedAuthorities(grants);
    for (GrantedAuthority auth : auths) {
        GrantedAuthorityName name = mapName(auth, badGrants);
        if (name != null && !GrantedAuthorityName.permissionsCanBeAssigned(auth.getAuthority())) {
            authorities.add(name);
        }
    }
    userInfo.setAssignedUserGroups(groups);
    userInfo.setGrantedAuthorities(authorities);
    removeBadGrantedAuthorities(badGrants, cc);
}