FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

AuthorizationStrategySample · brix-cms/brix-cms Wiki · GitHub

AuthorizationStrategySample

igor.vaynberg edited this page Oct 23, 2010 · 1 revision

I thought I would share what I came up with for my AuthorizationStrategy? implementation. I had the following goals:

  • Avoid using 'instanceof' in the code
  • Allow for a site-specific selection of Action implementations (some sites I build may include different plugins than others)
  • Clean delegation of interpretation of the various action handlers

Initially tried doing this with the visitor pattern, but that requires that the base interface knows all the Action implementations in advance. It solves the first goal but breaks the second.

Eventually came up with the following. It uses reflection, but caches the results so it's not terribly slow.

Comments and improvements welcome!

/**
 * @author <a href="mailto:topping@codehaus.org">Brian Topping</a>
 * @version $Id$
 * @date Mar 17, 2009 12:57:02 PM
 */
public class AuthorizationStrategyImpl implements AuthorizationStrategy {
// ------------------------------ FIELDS ------------------------------

    private static Log log = LogFactory.getLog(AuthorizationStrategyImpl.class);
    private Map<Class, Method> methodHashMap = new ConcurrentHashMap<Class, Method>();

    public AuthorizationStrategyImpl() {
    }

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface AuthorizationStrategy ---------------------

    public boolean isActionAuthorized(Action action) {
        Class<? extends Action> clazz = action.getClass();
        Method m = methodHashMap.get(clazz);
        try {
            if (m == null) {
                m = this.getClass().getDeclaredMethod("isActionAuthorized", new Class[]{clazz});
                methodHashMap.put(clazz, m);
            }
            return (Boolean) m.invoke(this, action);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

// -------------------------- OTHER METHODS --------------------------

    public boolean isActionAuthorized(SiteNodeAction action) {
        return true;
    }

    public boolean isActionAuthorized(AccessWorkspaceSwitcherToolbarAction action) {
        return true;
    }

    public boolean isActionAuthorized(ViewWorkspaceAction action) {
        return true;
    }
    
    // .. add rest of your handlers here
}

Wiki pages Pages 17

Clone this wiki locally


Back | FazBrowse Home | New Git URL