Place access permission with access restriction

0

I'm using a code that was already done by someone, I made some modifications about what I wanted.

This code has 2 types of access "Administrator and Official" would like that when the person entered with the login of type Employee it could not see the following items (jMenu2, jMenuItem12, jMenuItem13) that is in the jframe "Menu" that opens shortly after logging in. Could someone give me strength?

Main class

package Classes;

import Telas.Menu;
import Telas.Login;


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        new Login().setVisible(true);

    }

}  

SQLConnection class

package Classes;

import java.sql.*;
import javax.swing.*;

/**
 *
 * @author rafael
 */
public class SQLConnection {

    Connection conn = null;

    public static Connection java_db() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection conn = DriverManager.getConnection("jdbc:sqlserver://DESKTOP-33483CU:1433;databaseName=DADOSPROD;user=PROD");
            return conn;

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
            return null;
        }
    }
} 

Login screen

package Telas;

import Classes.SQLConnection;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 *
 * @author rafael
 */
public class Login extends javax.swing.JFrame {

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                LoginUsuario.requestFocus();
            }
        });
        conn = SQLConnection.java_db();
        Toolkit toolkit = getToolkit();
        Dimension size = toolkit.getScreenSize();
        setLocation(size.width / 2 - getWidth() / 2,
                size.height / 2 - getHeight() / 2);

    }


private void EntrarActionPerformed(java.awt.event.ActionEvent evt) {                                       

            if (LoginUsuario.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "O Campo Usuário está vazio");
            } else if (LoginSenha.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "O Campo Senha está vazio");
            } else {

                String sql = "select id,username,password,division from Users Where (username =? and password =? and division =?)";

                try {
                    int count = 0;

                    pst = conn.prepareStatement(sql);

                    pst.setString(1, LoginUsuario.getText());
                    pst.setString(2, LoginSenha.getText());
                    pst.setString(3, txt_divisao.getSelectedItem().toString());

                    rs = pst.executeQuery();

                    {
                    }
                    while (rs.next()) {
                        int id = rs.getInt(1);
                        Emp.empId = id;
                        count = count + 1;
                    }
                    String access = (txt_divisao.getSelectedItem().toString());

                    if (access.equals("Administrador")) {

                        if (count == 1) {
                            JOptionPane.showMessageDialog(null, "Bem Vindo!");
                            Menu j = new Menu();
                            j.setVisible(true);
                            this.dispose();

                        } else if (count > 1) {
                            JOptionPane.showMessageDialog(null, "Duplicado, nome de usuário ou acesso à senha negado");
                        } else {
                            JOptionPane.showMessageDialog(null, "O nome de usuário e a senha não estão corretos");
                        }
                    } else if (access.equals("Funcionario")) {

                        if (count == 1) {
                            JOptionPane.showMessageDialog(null, "Bem Vindo!");
                            Menu j = new Menu();
                            j.setVisible(true);

                        } else {
                            JOptionPane.showMessageDialog(null, "O nome de usuário e a senha não estão corretos");
                        }
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, e);

                } finally {

                    try {
                        rs.close();
                        pst.close();

                    } catch (Exception e) {

                    }
                }

            }     

Menu Screen

package Telas;

/**
 *
 * @author rafae
 */
public class Menu extends javax.swing.JFrame {

    /**
     * Creates new form Menu
     */
    public Menu() {
        initComponents();
    }

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
      teste1 tela = new teste1();
    tela.setVisible(true);
    dispose();
}                                          

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    teste2 tela = new teste2();
    tela.setVisible(true);
    dispose();
}                                          

private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    teste3 tela = new teste3();
    tela.setVisible(true);
    dispose();
}

Emp class inside screens

package Telas;

/**
 *
 * @author rafae
 */
class Emp {

    static int empId;

}

Back button

Menu tela = new Menu(false); // setei false igual no usuário que você fez.
tela.setVisible(true);
dispose();
    
asked by anonymous 04.07.2017 / 14:45

1 answer

2

By analyzing the code, the easiest way to do this is to create a Boolean parameter in the constructor of your Menu screen that tells you whether or not the user has access to all the menu options.

When the user is Manager, pass true and when he is an employee, pass false . And in the Menu screen class, use this parameter passed to set the visibility of the menus that you want to be based on access level.

Since you did not provide a Minimum, Full and Verifiable example , I've done the example below to illustrate my suggestion. Attention to class MenuIFrame , in it is that I made the check that you need to apply on your Menu screen, and in class LoginIFrame I pass the boolean value according to the selected option in a combobox (obviously in your code you go separate according to how you validate when the login is official or manager):

import java.awt.*;
import javax.swing.*;

public class LoginWithRestrictionsTest extends JFrame {

    private JDesktopPane desktopPane;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(() -> {
            LoginWithRestrictionsTest frame = new LoginWithRestrictionsTest();
            frame.createAndShowGUI();
        });
    }

    public LoginWithRestrictionsTest() {
        createAndShowGUI();
    }

    private void createAndShowGUI() {

        desktopPane = new JDesktopPane();
        this.desktopPane.setBackground(Color.LIGHT_GRAY);

        LoginIFrame internalframe = new LoginIFrame();
        internalframe.getContentPane().setForeground(Color.WHITE);

        desktopPane.add(internalframe);
        internalframe.getContentPane().setLayout(null);

        internalframe.setVisible(true);

        setContentPane(desktopPane);
        setTitle("Login Demo");

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setPreferredSize(new Dimension(screenSize.width / 2, screenSize.height / 2));
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

/**
 * 
 * 
 * CLASSE LoginIFrame
 *
 */

class LoginIFrame extends JInternalFrame {

    static final int xOffset = 30, yOffset = 30;
    private JLabel lblNewLabel;
    private JLabel lblNewLabel_1;
    private JTextField userField;
    private JTextField passField;
    private JButton btnLogin;
    private JComboBox<String> comboBox;
    MenuIFrame pFrame;

    public LoginIFrame() {
        super("LoginIFrame", false, true, true, true);
        initComponents();
    }

    private void initComponents() {

        setSize(250, 200);

        getContentPane().setLayout(null);

        this.lblNewLabel = new JLabel("User:");
        this.lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        this.lblNewLabel.setBounds(10, 32, 46, 14);
        getContentPane().add(this.lblNewLabel);

        this.lblNewLabel_1 = new JLabel("Pass:");
        this.lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
        this.lblNewLabel_1.setBounds(10, 57, 46, 14);
        getContentPane().add(this.lblNewLabel_1);

        this.userField = new JTextField();
        this.userField.setBounds(66, 29, 121, 20);
        getContentPane().add(this.userField);

        this.passField = new JTextField();
        this.passField.setBounds(66, 54, 121, 20);
        getContentPane().add(this.passField);

        this.btnLogin = new JButton("Login");
        this.btnLogin.setBounds(98, 119, 89, 23);
        getContentPane().add(this.btnLogin);

        btnLogin.addActionListener(e -> {
            if (pFrame != null) {
                pFrame.dispose();
            }
            pFrame = new MenuIFrame(comboBox.getSelectedItem().equals("Gerente"));
            getParent().add(pFrame);
            pFrame.setVisible(true);
        });

        setLocation(xOffset, yOffset);

        this.comboBox = new JComboBox<String>();
        this.comboBox.addItem("Funcionario");
        this.comboBox.addItem("Gerente");
        this.comboBox.setBounds(66, 85, 121, 20);

        getContentPane().add(this.comboBox);
    }
}

/**
 * 
 * 
 * CLASSE MenuIFrame
 *
 */
class MenuIFrame extends JInternalFrame {

    static final int xOffset = 350, yOffset = 30;

    public MenuIFrame(boolean isFullLevelAccess) {
        super("MenuIFrame", false, true, true, true);

        setSize(300, 300);
        setLocation(xOffset, yOffset);

        JMenu menu1, menu2;
        JMenuItem menuItem1, menuItem2, menuItem3, menuItem4, menuItem5;
        JMenuBar menuBar = new JMenuBar();

        menu1 = new JMenu("Menu 1");
        menuItem1 = new JMenuItem("Item 1");
        menuItem2 = new JMenuItem("Item 2");
        menuItem3 = new JMenuItem("Item 3");
        // Esse sub-item só estará acessivel
        // se o usuario tiver acesso completo
        menuItem3.setEnabled(isFullLevelAccess);

        menu1.add(menuItem1);
        menu1.add(menuItem2);
        menu1.add(menuItem3);

        menu2 = new JMenu("Menu 2");
        // Esse menu e todos os seus sub-itens só estarão acessíveis
        // se o usuario tiver acesso completo
        menu2.setEnabled(isFullLevelAccess);
        menuItem4 = new JMenuItem("Item 4");
        menuItem5 = new JMenuItem("Item 5");

        menu2.add(menuItem4);
        menu2.add(menuItem5);

        menuBar.add(menu1);
        menuBar.add(menu2);

        setJMenuBar(menuBar);

    }
}

Running:

  

Incode,IusedsetEnablewhichdisablesthecomponentforchangeoraccess,butstillkeepsitvisibleonthescreen.Ifyouwanttocompletelyhide,changetosetvisible.

Istressthattheabovecodewasonlytoillustratetheconceptexplainedinthebeginning(oftheuseofBoolean),itisnotnecessarilysothatitisadoptedasasubstitutesolutiontowhatithasalreadydone.

AdaptinginyourcodewouldlooksomethinglikebelowinclassLogin(needstobetested):

if(access.equals("Administrador")) {

        if (count == 1) {
            JOptionPane.showMessageDialog(null, "Bem Vindo!");
            Menu j = new Menu(true);
            j.setVisible(true);
            this.dispose();

        } else if (count > 1) {
            JOptionPane.showMessageDialog(null, "Duplicado, nome de usuário ou acesso à senha negado");
        } else {
            JOptionPane.showMessageDialog(null, "O nome de usuário e a senha não estão corretos");
        }
    } else if (access.equals("Funcionario")) {

        if (count == 1) {
            JOptionPane.showMessageDialog(null, "Bem Vindo!");
            Menu j = new Menu(false);
            j.setVisible(true);

        } else {
            JOptionPane.showMessageDialog(null, "O nome de usuário e a senha não estão corretos");
        }

And in the Menu class, something like the one below inside the constructor:

public Menu(boolean isFullLevelAccess) {
    initComponents();
    jMenu2.setEnable(isFullLevelAccess);
    jMenuItem12.setEnable(isFullLevelAccess);
    jMenuItem13.setEnable(isFullLevelAccess);
}

Note: If jMenuItem12 and jMenuItem13 are options of jMenu2 , you do not need to apply the restriction to them, just the menu.

Restrictions

Although functional, this form is very simplistic and will not suit if you have more than 2 access level profiles (eg, other than official (limited) and manager, you decide to create a director profile with options that only he sees). But at least it is already inspirational if you need other levels of access, such as using ENUM instead of Boolean, or creating employee objects with a field where you talk about what its function is hierarchical, but explain it would escape the point of the question.

    
04.07.2017 / 20:20