Search in sources :

Example 1 with AuthorizedAnnotationAttributes

use of org.openmrs.annotation.AuthorizedAnnotationAttributes in project openmrs-core by openmrs.

the class AuthorizationAdvice method before.

/**
 * Allows us to check whether a user is authorized to access a particular method.
 *
 * @param method
 * @param args
 * @param target
 * @throws Throwable
 * @should notify listeners about checked privileges
 */
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Calling authorization advice before " + method.getName());
    }
    if (log.isDebugEnabled()) {
        User user = Context.getAuthenticatedUser();
        log.debug("User " + user);
        if (user != null) {
            log.debug("has roles " + user.getAllRoles());
        }
    }
    AuthorizedAnnotationAttributes attributes = new AuthorizedAnnotationAttributes();
    Collection<String> privileges = attributes.getAttributes(method);
    boolean requireAll = attributes.getRequireAll(method);
    // one of them
    if (!privileges.isEmpty()) {
        for (String privilege : privileges) {
            // skip null privileges
            if (privilege == null || privilege.isEmpty()) {
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("User has privilege " + privilege + "? " + Context.hasPrivilege(privilege));
            }
            if (Context.hasPrivilege(privilege)) {
                if (!requireAll) {
                    // causes them to "pass"
                    return;
                }
            } else {
                if (requireAll) {
                    // if all are required, the first miss causes them
                    // to "fail"
                    throwUnauthorized(Context.getAuthenticatedUser(), method, privilege);
                }
            }
        }
        if (!requireAll) {
            // If there's no match, then we know there are privileges and
            // that the user didn't have any of them. The user is not
            // authorized to access the method
            throwUnauthorized(Context.getAuthenticatedUser(), method, privileges);
        }
    } else if (attributes.hasAuthorizedAnnotation(method) && !Context.isAuthenticated()) {
        throwUnauthorized(Context.getAuthenticatedUser(), method);
    }
}
Also used : User(org.openmrs.User) AuthorizedAnnotationAttributes(org.openmrs.annotation.AuthorizedAnnotationAttributes)

Aggregations

User (org.openmrs.User)1 AuthorizedAnnotationAttributes (org.openmrs.annotation.AuthorizedAnnotationAttributes)1