Pergunta

I have a database which contains users, roles, and permissions. I want to be able to map this to the front end (Java Swing) so a user who can't do an action can't see it.

An example:

  • Role AddressManager has permissions create_address, edit_address and remove_address.
  • User A has permissions create_address and edit_address.
  • User B has permission remove_address.

I want three buttons for the address view that represent the roles from the AddressManager, and for the users A and B to enable / disable the buttons.

Question: Is there any easy way to map database table values to Swing components (Buttons)?

One way is to assign enable/disable manually to every single component, but that’s unpractical if there are 40 dialogs in the application with about 200 components that must have permission.

Foi útil?

Solução

What you can do is to write a class like this and use it everywhere. In your example you would add it with new ActionContainer("adress"); and it will create a create_address, edit_address, delete_address Button that are enabled if the user posses the matching right.

package de.steamnet.samples;

// This class is a Panel that renders buttons based on rights.

import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;

public class ActionContainer extends JPanel {
    List<JButton> buttons = new ArrayList<JButton>();

    public ActionContainer(String rightBase) {
        List<String> rights = database.getRightsStartingWith(rightBase);
        for(String nextRight : rights) {
            JButton next = new JButton(nextRight);
            buttons.add(next);
            if(user.hasRight(nextRight)) {
                next.setEnabled(true);
            } else {
                next.setEnabled(false);
            }
            add(next);
        }
    }

    public void addActionListener(ActionListener al) {
        for(JButton next: buttons) {
            next.addActionListener(al);
        }
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top