Put access restricted login permission

Asked

Viewed 1,357 times

0

I’m using a code that was already made by someone, I made some modifications regarding what I wanted.

This code has 2 types of "Administrator and Employee" access that you would like when you login with the Employee type to be unable to see the following items (jMenu2,jMenuItem12,jMenuItem13) that are in the "Menu" jframe that opens right after you login. Someone could give me a boost?

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);

    }

}  

Class Sqlconnection

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;
        }
    }
} 

Tela Login

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;

}

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Back button

Menu tela = new Menu(false); // setei false igual no usuário que você fez.
tela.setVisible(true);
dispose();
  • 1

    Please add a [mcve] so you can test the code.

  • Missing menu items that are composed of a menu bar and some menu items. I will post an example

  • Well, since you’re not being able to create a simple, no-dependency version of your code, I can post a totally different example with a solution and you can adapt it to your code there, it can be?

  • pole I’ll take the test

  • Hello Are you using a database? if yes create a table for login, so every login done will be stored in this table so you can do the last login search done and compare if the type of user is Adm or common, making this comparison you can disable the buttons you want.

  • @Wagnereliasdeandrade, yes, I already have this table for login and now is working my code. I just have a problem that I explained in the last answer

Show 1 more comment

1 answer

2

Analyzing the code, the simplest way to do this is to create a Boolean parameter in your screen builder Menu whether the user has access to all menu options or not.

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

How did you not provide one Minimum, Complete and Verifiable Example, made the example below to illustrate my suggestion. Stay tuned to class MenuIFrame, in it is that I did the check that you need to apply on your screen Menu, and in class LoginIFrame i pass the boolean value as the option selected in a combobox (obviously in your code you will separate according to how you validate when the login is working 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:

inserir a descrição da imagem aqui

In the code, I used the setEnable which disables the component for change or access, but still keeps it visible on the screen. If you want to hide it completely, switch to setvisible.

I emphasize that the above code was only to illustrate the concept explained at the beginning (of the use of boolean), it is not necessarily to adopt as a substitute solution to what has already done.


Adapting in your code would be something like down in class Login(needs to be tested):

 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 class Menu, something similar to the below inside the builder:

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

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


Restrictions

Although functional, this form is quite simplistic and will not suit if you have more than 2 access level profiles(e.g.: besides employee(limited) and manager, you decide to create a director profile with options that only he sees). But at least it already serves as an inspiration if you need other levels of access, such as the use of ENUM rather than boolean, or create employee objects with a field where he talks about what his function is at the hierarchical level, but explaining this would be a long way from the purpose of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.