Search in sources :

Example 1 with RunIfSecurityEnabled

use of org.craftercms.security.annotations.RunIfSecurityEnabled in project engine by craftercms.

the class CrafterPageAccessManager method checkAccess.

/**
     * Checks if the user has sufficient rights to access the specified page:
     *
     * <ol>
     *     <li>If the page doesn't contain any required role, no authentication is needed.</li>
     *     <li>If the page has the role "Anonymous", no authentication is needed.</li>
     *     <li>If the page has the role "Authenticated", just authentication is needed.</li>
     *     <li>If the page has any other the roles, the user needs to have any of those roles.</li>
     * </ol>
     */
@RunIfSecurityEnabled
public void checkAccess(SiteItem page) throws AuthenticationRequiredException, AccessDeniedException {
    String pageUrl = page.getStoreUrl();
    Profile profile = null;
    Authentication auth = SecurityUtils.getCurrentAuthentication();
    if (auth != null) {
        profile = auth.getProfile();
    }
    List<String> authorizedRoles = getAuthorizedRolesForPage(page);
    if (CollectionUtils.isNotEmpty(authorizedRoles) && !containsRole("anonymous", authorizedRoles)) {
        // If profile == null it is anonymous
        if (profile == null) {
            throw new AuthenticationRequiredException("User is anonymous but page '" + pageUrl + "' requires authentication");
        }
        if (!containsRole("authenticated", authorizedRoles) && !profile.hasAnyRole(authorizedRoles)) {
            throw new AccessDeniedException("User '" + profile.getUsername() + "' is not authorized " + "to view page '" + pageUrl + "'");
        }
    }
}
Also used : AccessDeniedException(org.craftercms.security.exception.AccessDeniedException) Authentication(org.craftercms.security.authentication.Authentication) AuthenticationRequiredException(org.craftercms.security.exception.AuthenticationRequiredException) Profile(org.craftercms.profile.api.Profile) RunIfSecurityEnabled(org.craftercms.security.annotations.RunIfSecurityEnabled)

Aggregations

Profile (org.craftercms.profile.api.Profile)1 RunIfSecurityEnabled (org.craftercms.security.annotations.RunIfSecurityEnabled)1 Authentication (org.craftercms.security.authentication.Authentication)1 AccessDeniedException (org.craftercms.security.exception.AccessDeniedException)1 AuthenticationRequiredException (org.craftercms.security.exception.AuthenticationRequiredException)1