+package eu.etaxonomy.taxeditor.security;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Observable;
+import java.util.Observer;
+
+import org.eclipse.ui.AbstractSourceProvider;
+import org.eclipse.ui.ISources;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+
+import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
+import eu.etaxonomy.taxeditor.store.CdmStore;
+import eu.etaxonomy.taxeditor.store.LoginManager;
+
+/**
+ * Provides the Roles assigned to the currently authenticated principal as the
+ * variable {@code eu.etaxonomy.taxeditor.security.userRoles}
+ *
+ * @author a.kohlbecker
+ *
+ */
+public class RolesSourceProvider extends AbstractSourceProvider implements Observer {
+
+ public final static String RIGHTS_VARIABLE = "eu.etaxonomy.taxeditor.security.userRoles";
+ private final static String[] PROVIDED_SOURCE_NAMES = new String[] { RIGHTS_VARIABLE };
+
+ private final static Map<String, List<String>> stateMap = new HashMap<String, List<String>>();
+
+ public RolesSourceProvider() {
+ super();
+ initialize();
+ }
+
+ private void initialize() {
+ CdmStore.getLoginManager().addObserver(this);
+ }
+
+ @Override
+ public void dispose() {
+ CdmStore.getLoginManager().deleteObserver(this);
+ }
+
+ @Override
+ public Map getCurrentState() {
+
+ // SecurityContextHolder.getContext().
+ List<Role> roles = getCurrentAuthenticationsRoles();
+ List<String> rolesStr = new ArrayList<String>(roles.size());
+ for(Role r : roles){
+ rolesStr.add(r.getAuthority());
+ }
+
+ stateMap.put(RIGHTS_VARIABLE, rolesStr);
+ return stateMap;
+ }
+
+ /*
+ * TODO refactor into User once Role is a model class
+ */
+ private List<Role> getCurrentAuthenticationsRoles() {
+
+ List<Role> roles = new ArrayList<Role>();
+ Authentication authentication = CdmStore.getCurrentAuthentiation();
+ if (authentication == null) {
+ return roles;
+ }
+
+ Collection<? extends GrantedAuthority> authorities = authentication
+ .getAuthorities();
+ if (authorities == null) {
+ return roles;
+ }
+
+ Role role = null;
+ for (GrantedAuthority ga : authorities) {
+ try {
+ // check if it is a valid role
+ role = Role.fromString(ga.getAuthority());
+ if (role != null) {
+ roles.add(role);
+ }
+ } catch (Exception e) {
+ /* IGNORE */
+ }
+ }
+ return roles;
+
+ }
+
+ public String[] getProvidedSourceNames() {
+ return PROVIDED_SOURCE_NAMES;
+ }
+
+ @Override
+ public void update(Observable o, Object arg) {
+ if(o instanceof LoginManager){
+ /*
+ * This triggers an update of the variable state, and will update also
+ * all listeners to the evaluation service. So that every menu point,
+ * which is also expression controlled, gets updated too.
+ */
+ fireSourceChanged(ISources.WORKBENCH, getCurrentState());
+ }
+ }
+
+}