Example usage for java.security Principal Principal

List of usage examples for java.security Principal Principal

Introduction

In this page you can find the example usage for java.security Principal Principal.

Prototype

Principal

Source Link

Usage

From source file:org.sakaiproject.kernel.user.servlet.CreateSakaiGroupServlet.java

@Override
protected void handleOperation(SlingHttpServletRequest request, HtmlResponse response,
        List<Modification> changes) throws RepositoryException {

    // check that the submitted parameter values have valid values.
    final String principalName = request.getParameter(SlingPostConstants.RP_NODE_NAME);
    if (principalName == null) {
        throw new RepositoryException("Group name was not submitted");
    }// w w w.  jav  a 2 s.co m

    if (!principalName.startsWith("g-")) {
        throw new RepositoryException("Group names must begin with 'g-'");
    }

    // check for allow create Group
    boolean allowCreateGroup = false;
    User currentUser = null;
    try {
        Session currentSession = request.getResourceResolver().adaptTo(Session.class);
        UserManager um = AccessControlUtil.getUserManager(currentSession);
        currentUser = (User) um.getAuthorizable(currentSession.getUserID());
        if (currentUser.isAdmin()) {
            LOGGER.debug("User is an admin ");
            allowCreateGroup = true;
        } else {
            LOGGER.debug("Checking for membership of one of {} ", Arrays.toString(authorizedGroups));
            PrincipalManager principalManager = AccessControlUtil.getPrincipalManager(currentSession);
            PrincipalIterator pi = principalManager
                    .getGroupMembership(principalManager.getPrincipal(currentSession.getUserID()));
            Set<String> groups = new HashSet<String>();
            for (; pi.hasNext();) {
                groups.add(pi.nextPrincipal().getName());
            }

            for (String groupName : authorizedGroups) {
                if (groups.contains(groupName)) {
                    allowCreateGroup = true;
                    break;
                }

                // TODO: move this nasty hack into the PrincipalManager dynamic groups need to
                // be in the principal manager for this to work.
                if ("authenticated".equals(groupName)
                        && !SecurityConstants.ADMIN_ID.equals(currentUser.getID())) {
                    allowCreateGroup = true;
                    break;
                }

                // just check via the user manager for dynamic resolution.
                Group group = (Group) um.getAuthorizable(groupName);
                LOGGER.debug("Checking for group  {} {} ", groupName, group);
                if (group != null && group.isMember(currentUser)) {
                    allowCreateGroup = true;
                    LOGGER.debug("User is a member  of {} {} ", groupName, group);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.warn("Failed to determin if the user is an admin, assuming not. Cause: " + ex.getMessage());
        allowCreateGroup = false;
    }

    if (!allowCreateGroup) {
        LOGGER.debug("User is not allowed to create groups ");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN, "User is not allowed to create groups");
        return;
    }

    Session session = getSession();

    try {
        UserManager userManager = AccessControlUtil.getUserManager(session);
        Authorizable authorizable = userManager.getAuthorizable(principalName);

        if (authorizable != null) {
            // principal already exists!
            throw new RepositoryException(
                    "A principal already exists with the requested name: " + principalName);
        } else {
            Map<String, RequestProperty> reqProperties = collectContent(request, response);

            Group group = userManager.createGroup(new Principal() {
                public String getName() {
                    return principalName;
                }
            }, PathUtils.getUserPrefix(principalName, DEFAULT_HASH_LEVELS));

            String groupPath = AuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PREFIX + group.getID();
            response.setPath(groupPath);
            response.setLocation(externalizePath(request, groupPath));
            response.setParentLocation(
                    externalizePath(request, AuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PATH));
            changes.add(Modification.onCreated(groupPath));

            // write content from form
            writeContent(session, group, reqProperties, changes);

            // update the group memberships, although this uses session from the request, it
            // only
            // does so for finding authorizables, so its ok that we are using an admin session
            // here.
            updateGroupMembership(session, request, group, changes);
            updateOwnership(session, request, group, new String[] { currentUser.getID() }, changes);

            try {
                for (UserPostProcessor userPostProcessor : postProcessorTracker.getProcessors()) {
                    userPostProcessor.process(session, request, changes);
                }
            } catch (Exception e) {
                LOGGER.warn(e.getMessage(), e);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
            if (session.hasPendingChanges()) {
                session.save();
            }

        }
    } catch (RepositoryException re) {
        throw new RepositoryException("Failed to create new group.", re);
    } finally {
        ungetSession(session);
    }
}

From source file:org.sakaiproject.nakamura.personal.PersonalAuthorizablePostProcessor.java

/**
 * Set access controls on the new User or Group node according to the profile
 * preference configuration property./*from  www.  java2  s.  c om*/
 *
 * @param node
 * @param session
 * @param authorizable
 * @throws RepositoryException
 */
private void initializeAccess(Node node, Session session, Authorizable authorizable)
        throws RepositoryException {
    String nodePath = node.getPath();
    PrincipalManager principalManager = AccessControlUtil.getPrincipalManager(session);
    Principal everyone = principalManager.getEveryone();
    Principal anon = new Principal() {
        public String getName() {
            return UserConstants.ANON_USERID;
        }
    };
    // KERN-886 : Depending on the profile preference we set some ACL's on the profile.
    if (UserConstants.ANON_USERID.equals(authorizable.getID())) {
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, anon, new String[] { JCR_READ }, null,
                null, null);
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, everyone, new String[] { JCR_READ },
                null, null, null);
    } else if (VISIBILITY_PUBLIC.equals(visibilityPreference)) {
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, anon, new String[] { JCR_READ }, null,
                null, null);
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, everyone, new String[] { JCR_READ },
                null, null, null);
    } else if (VISIBILITY_LOGGED_IN.equals(visibilityPreference)) {
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, anon, null, new String[] { JCR_READ },
                null, null);
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, everyone, new String[] { JCR_READ },
                null, null, null);
    } else if (VISIBILITY_PRIVATE.equals(visibilityPreference)) {
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, anon, null, new String[] { JCR_READ },
                null, null);
        AccessControlUtil.replaceAccessControlEntry(session, nodePath, everyone, null,
                new String[] { JCR_READ }, null, null);
    }
}

From source file:org.sakaiproject.nakamura.site.create.TemplateBuilder.java

/**
 * //  w w w  . j a va 2 s  . com
 * @param node
 * @param map
 * @throws RepositoryException
 */
@SuppressWarnings("unchecked")
private void handleACENode(Node node, Map<String, Object> map) throws RepositoryException {
    // The name of the principial we should set an ACE for.
    Value principalName = node.getProperty("sakai:template-ace-principal").getValue();
    if (isPlaceHolder(principalName)) {
        principalName = getValue(principalName, node.getSession());
    }
    final String pName = principalName.getString();
    Principal principal = new Principal() {

        public String getName() {
            return pName;
        }
    };

    // The permissions
    // TODO allow permissions to be filled in from the json.
    Value[] grantedValue = node.getProperty("sakai:template-ace-granted").getValues();
    String[] granted = new String[grantedValue.length];
    for (int i = 0; i < grantedValue.length; i++) {
        granted[i] = grantedValue[i].getString();
    }

    Value[] deniedValue = node.getProperty("sakai:template-ace-denied").getValues();
    String[] denied = new String[deniedValue.length];
    for (int i = 0; i < deniedValue.length; i++) {
        denied[i] = deniedValue[i].getString();
    }

    // Fill in the object.
    ACE ace = new ACE();
    ace.setPrincipal(principal);
    ace.setGrantedPrivileges(granted);
    ace.setDeniedPrivileges(denied);

    // Add it to the list.
    if (map.containsKey("rep:policy")) {
        // This is not the first ACE for this path.
        ((List<ACE>) map.get("rep:policy")).add(ace);
    } else {
        // This is the first ACE for this path.
        List<ACE> lst = new ArrayList<ACE>();
        lst.add(ace);
        map.put("rep:policy", lst);
    }
}

From source file:org.sakaiproject.nakamura.user.servlet.CreateSakaiGroupServlet.java

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(justification = "If there is an exception, the user is certainly not admin", value = {
        "REC_CATCH_EXCEPTION" })

protected void handleOperation(SlingHttpServletRequest request, HtmlResponse response,
        List<Modification> changes) throws RepositoryException {

    // KERN-432 dont allow anon users to access create group.
    if (SecurityConstants.ANONYMOUS_ID.equals(request.getRemoteUser())) {
        response.setStatus(403, "AccessDenied");
        return;// w  w  w . j ava 2  s. co m
    }

    // check that the submitted parameter values have valid values.
    final String principalName = request.getParameter(SlingPostConstants.RP_NODE_NAME);
    if (principalName == null) {
        throw new RepositoryException("Group name was not submitted");
    }

    NameSanitizer san = new NameSanitizer(principalName, false);
    san.validate();

    // check for allow create Group
    boolean allowCreateGroup = false;
    User currentUser = null;

    try {
        Session currentSession = request.getResourceResolver().adaptTo(Session.class);
        UserManager um = AccessControlUtil.getUserManager(currentSession);
        currentUser = (User) um.getAuthorizable(currentSession.getUserID());
        if (currentUser.isAdmin()) {
            LOGGER.debug("User is an admin ");
            allowCreateGroup = true;
        } else {
            LOGGER.debug("Checking for membership of one of {} ", Arrays.toString(authorizedGroups));
            PrincipalManager principalManager = AccessControlUtil.getPrincipalManager(currentSession);
            PrincipalIterator pi = principalManager
                    .getGroupMembership(principalManager.getPrincipal(currentSession.getUserID()));
            Set<String> groups = new HashSet<String>();
            for (; pi.hasNext();) {
                groups.add(pi.nextPrincipal().getName());
            }

            for (String groupName : authorizedGroups) {
                if (groups.contains(groupName)) {
                    allowCreateGroup = true;
                    break;
                }

                // TODO: move this nasty hack into the PrincipalManager dynamic groups need to
                // be in the principal manager for this to work.
                if ("authenticated".equals(groupName)
                        && !SecurityConstants.ADMIN_ID.equals(currentUser.getID())) {
                    allowCreateGroup = true;
                    break;
                }

                // just check via the user manager for dynamic resolution.
                Group group = (Group) um.getAuthorizable(groupName);
                LOGGER.debug("Checking for group  {} {} ", groupName, group);
                if (group != null && group.isMember(currentUser)) {
                    allowCreateGroup = true;
                    LOGGER.debug("User is a member  of {} {} ", groupName, group);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.warn("Failed to determin if the user is an admin, assuming not. Cause: " + ex.getMessage());
        allowCreateGroup = false;
    }

    if (!allowCreateGroup) {
        LOGGER.debug("User is not allowed to create groups ");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN, "User is not allowed to create groups");
        return;
    }

    Session session = getSession();

    try {
        UserManager userManager = AccessControlUtil.getUserManager(session);
        Authorizable authorizable = userManager.getAuthorizable(principalName);

        if (authorizable != null) {
            // principal already exists!
            response.setStatus(400, "A principal already exists with the requested name: " + principalName);
            return;
        } else {
            Group group = userManager.createGroup(new Principal() {
                public String getName() {
                    return principalName;
                }
            });
            String groupPath = AuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PREFIX + group.getID();
            Map<String, RequestProperty> reqProperties = collectContent(request, response, groupPath);

            response.setPath(groupPath);
            response.setLocation(externalizePath(request, groupPath));
            response.setParentLocation(
                    externalizePath(request, AuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PATH));
            changes.add(Modification.onCreated(groupPath));

            // It is not allowed to touch the rep:group-managers property directly.
            String key = SYSTEM_USER_MANAGER_GROUP_PREFIX + principalName + "/";
            reqProperties.remove(key + PROP_GROUP_MANAGERS);
            reqProperties.remove(key + PROP_GROUP_VIEWERS);

            // write content from form
            writeContent(session, group, reqProperties, changes);

            // update the group memberships, although this uses session from the request, it
            // only
            // does so for finding authorizables, so its ok that we are using an admin session
            // here.
            updateGroupMembership(request, group, changes);
            // TODO We should probably let the client decide whether the
            // current user belongs in the managers list or not.
            updateOwnership(request, group, new String[] { currentUser.getID() }, changes);

            try {
                postProcessorService.process(group, session, ModificationType.CREATE, request);
            } catch (RepositoryException e) {
                LOGGER.info("Failed to create Group  {}", e.getMessage());
                response.setStatus(HttpServletResponse.SC_CONFLICT, e.getMessage());
                return;
            } catch (Exception e) {
                LOGGER.warn(e.getMessage(), e);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                return;
            }

            // Launch an OSGi event for creating a group.
            try {
                Dictionary<String, String> properties = new Hashtable<String, String>();
                properties.put(UserConstants.EVENT_PROP_USERID, principalName);
                EventUtils.sendOsgiEvent(properties, UserConstants.TOPIC_GROUP_CREATED, eventAdmin);
            } catch (Exception e) {
                // Trap all exception so we don't disrupt the normal behaviour.
                LOGGER.error("Failed to launch an OSGi event for creating a user.", e);
            }
        }
    } catch (RepositoryException re) {
        LOGGER.info("Failed to create Group  {}", re.getMessage());
        LOGGER.debug("Failed to create Group Cause {}", re, re.getMessage());
        response.setStatus(HttpServletResponse.SC_CONFLICT, re.getMessage());
        return;
    } finally {
        ungetSession(session);
    }
}

From source file:org.vasttrafik.wso2.carbon.apimgt.portal.api.providers.AuthorizationContainerRequestFilter.java

@Override
public void filter(ContainerRequestContext requestContext) {
    final String authorization = requestContext.getHeaderString("X-JWT-Assertion");

    try {/*w  w w  .j  a  v a 2  s .c o  m*/
        final JWTClaims claims = validateToken(authorization);

        requestContext.setSecurityContext(new SecurityContext() {
            private JWTClaims jwtClaims = claims;

            @Override
            public Principal getUserPrincipal() {
                return new Principal() {
                    @Override
                    public String getName() {
                        return claims.getEndUser();
                    }
                };
            }

            @Override
            public boolean isUserInRole(String s) {
                String[] roles = jwtClaims.getUserRoles();
                for (String role : roles)
                    if (role.equalsIgnoreCase(s))
                        return true;
                return false;
            }

            @Override
            public boolean isSecure() {
                return false;
            }

            @Override
            public String getAuthenticationScheme() {
                return null;
            }
        });
    } catch (final Exception exception) {
        // Get error code
        final String message = exception.getMessage();
        Long code;

        try {
            code = Long.parseLong(message);
        } catch (Exception e) {
            code = 2003L;
        }

        // Abort
        requestContext.abortWith(ResponseUtils.notAuthorizedError(resourceBundle, code, new Object[][] {}));
    }
}

From source file:play.modules.securePermissions.Permissions.java

/**
 * Wraps the given user name in a Principal object.
 *//*from w ww  . j av  a 2s  .co  m*/
private static Principal asPrincipal(final String user) {
    final Principal principal = new Principal() {
        public String getName() {
            return user;
        }
    };
    return principal;
}

From source file:wicket.protocol.http.MockHttpServletRequest.java

/**
 * Get the user principal./*from  w ww  .j  a  v  a 2  s .  com*/
 * 
 * @return A user principal
 */
public Principal getUserPrincipal() {
    final String user = getRemoteUser();
    if (user == null) {
        return null;
    } else {
        return new Principal() {
            public String getName() {
                return user;
            }
        };
    }
}