How do I assign one user to another user?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tangara
    New Member
    • Jan 2010
    • 27

    How do I assign one user to another user?

    I have created a form where there's an option or 2 user types.

    All the data collected will be posted to my msaccess table.

    I have user java servlet to link the html to msaccess table so that user can view the table.

    Now I need to complete another task which is I can allow 1st user to assign 2nd user to any existing 1st users available on my database.

    I hope someone can advise me how to go about doing this.
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    create a permission table. Give each user a role and store the user name and role there.
    Then code some rules like an "administra tor" can always assign a "normal user", but not the other way around.
    So if 1st user tries to assign a 2nd user, query the permission table if he is allowed or not.

    Comment

    • tangara
      New Member
      • Jan 2010
      • 27

      #3
      Hi Charmaine,

      Could you please advise how create a permission table. I'm new in java and jsp so not sure how to create one. Is there any link you can point me to that can show me examples what you mentioned?

      Comment

      • chaarmann
        Recognized Expert Contributor
        • Nov 2007
        • 785

        #4
        you can create a table with an SQL-command:
        Code:
        create table permission (user_name TEXT, role TEXT);
        You can pass this SQL-command in java to your Database (access etc.) via JDBC or much better, use some library like Hibernate

        Comment

        • tangara
          New Member
          • Jan 2010
          • 27

          #5
          Hi Chaarmann,

          First, my apologies for addressing your name wrongly earlier.

          Sorry, I'm still very confusing.

          My question was how to do the assigning portion, assuming that the admin has the permission to do so.

          Now, I already have a table/database which consist of :-

          Name, email, ID, contact, Membeship Type

          The membership types will have user1 and user2.

          How do I let the admin person assigning user2 to user1, consider there are already many records there.

          OK. Hope to hear from you soon.

          Tks

          Comment

          • chaarmann
            Recognized Expert Contributor
            • Nov 2007
            • 785

            #6
            You haven't given any example data. So I can only guess that the "Membeship" type column contains the role. (if not, just add a new column to the table).
            So just grab the data from this table for user 1 and then for user 2 with the following SQL-command:
            "select membeship from table where name='user1'". (or name='user2')
            Then test if the roles are right (e.g. user1=administr ator" and user2="guest") and if yes, process the requested task, else print an error.

            This is role-based security. But If you want to map a user to one or more other users, you need individual security. Then you need to set up an extra table with the columns:
            User-ID1, User-ID2.
            So if a user with userid1 assigns other users with userid2 and userid3, you would simply add 2 rows to this table:
            userid1, userid2
            userid1, userid3

            Comment

            • tangara
              New Member
              • Jan 2010
              • 27

              #7
              Hi Charmann,

              I hope you don't mind I side track abit but this is related to the above question also.

              Now, I tried to create session into my login page.

              My table now will have userid, password and access.

              Hence, I'll redirect the user according to the access which is admin or user1.

              However, I'm a bit fuzzy about the session concepts. Could you take a look at my codes and advise me where I have done wrong?

              My html code is:-
              Code:
              <form action="session.jsp">                   
                      
                                   <td>Userid</td>
                                  <td><input type="text" id="userid" name="login" ></td>
                                             <tr>
                                           <td>password</td>
                                  <td><input type="text" id="password" name="password" ></td>
                              </tr>
                              <tr>
                                           <td>accessType</td>
                                  <td><input type="text" id="access" name="access" ></td>
                                      </tr>
                              <tr>
                                  <td align="right"><input type="submit" value="Submit" />
                              </tr>
                                </table>
                               </form>
                </body>
              </html>
              my session.jsp as follows;-

              Code:
              <%@page language="java" import ="java.sql.*" import="java.util.*" %>
                      <%  Connection conn = null;
                          PreparedStatement ps = null;
                          ResultSet rs = null;
                          Statement stmt = null;
                          PrintWriter out = null;
                          try {
                              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                              String url = "jdbc:odbc:sessionODBC";
                              conn = DriverManager.getConnection(url);
                              stmt = conn.createStatement();
                          } catch (Exception e) {
                              System.out.println(e.getMessage());
                          }
                          rs = stmt.executeQuery("Select * from Staff");
              
                          String accessPermission = rs.getString("access");
                          session.setAttribute("login", accessPermission;%>
                        rs.close();
                        stmt.close();
                        conn.close();
                      <% String accessType=(String)session.getAttribute("login");
              
                      if(accessType==null){
                          response.sendRedirect("login.html");
                      }
                      else if(accessType.equals("member"){
                          
                          response.sendRedirect("xyz.jsp");
                      }
                      else{
                          out.printline("Found");
                      }
                      %>
              Many thanks.

              Comment

              • chaarmann
                Recognized Expert Contributor
                • Nov 2007
                • 785

                #8
                Strange code. You are getting all entrries from table "staff" - but you should get only the entry of the current user. Then you don't loop through the table until you find your user, but just grab a column of the first record, ignoring all the other records. If the table is empty, it could be "null". Then you store the grabbed value into the session and retrieve it right afterwards. If it's null, you send him to a login-page, else somewhere else - That means, if you have no user inside your table, all are going to the login-page, but if you have at least one entry inside your table, all users that are trying to login are going to the page xyz.jsp or stay on the current, whatever you put inside this table at the first place.
                And it doesn't matter in the slightest which username and password the users have put at the login-page session.jsp.

                You are not grabbing any values from session.jsp with "response.getPa rameter(..)". You are not comparing entered password against stored password. You are not printing any error (redirect to error page) if the user is not allowed to enter. You are not destroying the current session if the user gave wrong credentials. So what's the use of the whole code???

                By the way, you should never put the business-layer code inside a JSP!
                This is a no-no! (Read about MVC; the JSP should only format your output!)
                Make an Action-class in Java and make all the checkings there!
                Use some ready-made Business-layer like Hibernate, so your code can run with all databases, instead of making the low-level database-calls yourself.)

                Comment

                • tangara
                  New Member
                  • Jan 2010
                  • 27

                  #9
                  Hi Chaarman,

                  Thanks for replying. Yes, my codes are not really correct. Anyway, I managed to find out the solution, after working on it for 3 days!!!

                  The hibernate thing is like a very distance subject to me. Would you be able to provide me with a link to learn basic stuff first?

                  Thank you again for your help.

                  Comment

                  • chaarmann
                    Recognized Expert Contributor
                    • Nov 2007
                    • 785

                    #10
                    Originally posted by tangara
                    Hi Chaarman,

                    Thanks for replying. Yes, my codes are not really correct. Anyway, I managed to find out the solution, after working on it for 3 days!!!
                    Can you please post your solution here, so that others with the same problem can benefit? I spent my time and knowledge to help you for free, so it's your turn now to help others .

                    And maybe I can help you even more by giving you some performance tips on your new code.

                    Originally posted by tangara
                    The hibernate thing is like a very distance subject to me. Would you be able to provide me with a link to learn basic stuff first?
                    Just google for "Hibernate" . The first hit will go directly to "www.hibernate. org". The third link will go to wikipedia's article about Hibernate, for a rough overview. Under chapter "External links" at the bottom of this page there is also a link to a tutorial listed.

                    Comment

                    • tangara
                      New Member
                      • Jan 2010
                      • 27

                      #11
                      I just knew yesterday that I still have a bit of my code not working. That is, if people enter a wrong userid or password, the servlet returns a blank.

                      Could you help me out on this? Here's my code:-

                      Code:
                      public class Servlet1 extends HttpServlet {
                      
                          
                          protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                                  throws ServletException, IOException {
                              response.setContentType("text/html;charset=UTF-8");      
                                    
                          }
                          
                          @Override
                          protected void doGet(HttpServletRequest request, HttpServletResponse response)
                                  throws ServletException, IOException {processRequest(request, response);
                      	}
                             
                          @Override
                          protected void doPost(HttpServletRequest request, HttpServletResponse response)
                                  throws ServletException, IOException {
                             
                              PrintWriter out = response.getWriter();
                      
                              String userid = request.getParameter("userid");
                              String password = request.getParameter("password");
                             // String access = request.getParameter("access");
                      
                              try {
                                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                  Connection conn = DriverManager.getConnection("jdbc:odbc:sessionODBC");
                                  Statement stmt = conn.createStatement();
                                  String sql = "SELECT password, access FROM Staff WHERE userid='" + userid +
                                          "'" ;
                                  ResultSet resultSet = stmt.executeQuery(sql);
                                  
                                  if (resultSet.next()){
                                      if  (!(resultSet.getString("userid")).equals(request.getParameter("null"))
                                              && (!(resultSet.getString("password")).equals(request.getParameter("null"))
                                              &&(resultSet.getString("password").equals(request.getParameter("password"))
                                          && (resultSet.getString("userid").equals(request.getParameter("userid"))))))
                                      {
                                          HttpSession session = request.getSession(true); // create a session
                                          String accessPermission = resultSet.getString("access");
                                          session.setAttribute("access", accessPermission);                    
                                          out.println("<html>");
                                          out.println("<head><title>Login Success</title></head>");
                                          out.println("<body>");
                                          out.println("<p>Login Success! Welcome " + userid);
                                          out.println("<a href=\"checkValid.jsp\">Click here to login</a>");
                                          out.println("</body></html>");                   
                                          } else {
                                          out.println("<html>");
                                          out.println("<head><title>No Such User</title></head>");
                                          out.println("<body>");
                                          out.println("<p>Login Failed! " + userid);
                                          out.println("<p>No such user exists, " + userid);
                                          out.println("</body></html>");
                                          out.println("<a href=\"login.html\">Click here to login</a>");
                                      out.close();
                                      conn.close();
                                          }}} catch  (Exception e) {
                                  System.out.println("Error" + e.getMessage());
                                          }}

                      Comment

                      • chaarmann
                        Recognized Expert Contributor
                        • Nov 2007
                        • 785

                        #12
                        1.) It returns blank, because the else-clause is missing for "if (resultset.next ())". That's exactly the case if a user enters a wrong userId, so nothing is returned from database.So you should put appropriate error-messages (to be printed with out.println()). inside these else-clause.

                        2.) Your code is not secure, I can do an malicious code injection attack: if I type "'; delete from staff; select * from staff where id='" (pay attention to single quotes!) in your web page inside userid-field, your whole user-table got deleted. And I even can do more damage if I want instead, with a more complex SQL: delete all your tables! So you can avoid that in 2 ways: a.) replace single quotes with two single quotes, b.) use "prepared statements". They are faster anyway.

                        3.) the if-staement in line 34 is too complex! Why compare with userID? You know it's equal, because you searched in database with it in a way that it returns only those records where they are equal! And second, no need to call request.getPara meter() again. You forgot that you already stored that value in "password" a few lines above.

                        4.) Your application is unsecure: you are transportating the plain password over the netword from the database! Everyone can read it with a network sniffer. You should only store the encrypted password inside your table.
                        And before you compare the passwords, you should also encrypt the password you got from the web page. So if both encrypted passwords are the same (web-page and database), you will grant access, else display an error.

                        5.) You should put all the HTML-code (Line 42 to 55) into an JSP-page. The rest is fine to stay here. (Separation of diplay and business logic, learn about MVC (= Model View Controller)). At least you could improve it by putting all the HTML-code inside a template that can be changed easily. Like:
                        Code:
                        String template="<html><head><body>...<p>Login Failed!  #userid <p>No such user exists,  #userid ...";
                        template.replaceAll("#userid", userid);
                        out.println(template);
                        .
                        You could even store the template inside your database or filesystem and load it. Then there is no need to change the program if you want to change the HTML-code for another design later on.
                        Read about "freemarker templates" for automating this task. It's even better than JSP!

                        6.) quotation from my email above: "You are not destroying the current session if the user gave wrong credentials."

                        Comment

                        • tangara
                          New Member
                          • Jan 2010
                          • 27

                          #13
                          Hi Chaarman,

                          Thanks so much for your guidance above, I have changed my codes except I don't know about how to go about doing the encryption stuff. However, the funny thing is that I don't know why when the url, say display.jsp is pasted again, without proper login. It can be accessed. Could you kindly advise on this?

                          my code is as follows:-
                          Code:
                          public class Servlet2a extends HttpServlet {
                          
                              protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                                      throws ServletException, IOException, SQLException {
                                  response.setContentType("text/html;charset=UTF-8");
                                  PrintWriter out = response.getWriter();
                                  try {
                                      String userid = request.getParameter("userid");
                                      String password = request.getParameter("password");
                                      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                      Connection conn = DriverManager.getConnection("jdbc:odbc:sessionODBC");
                                      String sql = "SELECT password, access FROM Staff WHERE userid= ? AND password = ?";
                          
                                      PreparedStatement stmt = conn.prepareStatement(sql);
                                      stmt.setString(1, userid);
                                      stmt.setString(2, password);
                                      ResultSet resultSet = stmt.executeQuery();
                          
                                           if (resultSet.next() != false) {
                                          String access = resultSet.getString("access");
                                          out.print("<p><h5>You have successfully logged in, " + userid + "</h5></p>");
                                          HttpSession session = request.getSession();
                                          session.setMaxInactiveInterval(3600);
                                          session.setAttribute("access", access);
                                          {
                                              out.print("<p><a href=\"displayData.jsp\">Update and Delete Data</a></p>");
                                          }
                                      } else {
                                          out.print("<p>Wrong Userid or password.</p>");
                                          out.print("<p><a href=\"login.html\">Try again</a></p>");
                                          out.print("</body></html>");
                                          conn.close();
                                      }
                                  } catch (ClassNotFoundException cnfe) {
                                      System.err.println("Error loading driver: " + cnfe);
                                  } catch (SQLException sqle) {
                                      System.err.println("Error with connection: " + sqle);
                                  } finally {
                                      out.close();
                                  }
                              }
                          And here's my displaypage.jsp
                          Code:
                          <%
                                      String access = (String) session.getAttribute("access");
                                      if (access == null) {
                                          response.sendRedirect("login.html");
                                      }
                          
                                      %>
                          <%-- Display page --%>
                          <%         Connection conn = null;
                                      PreparedStatement ps = null;
                                      ResultSet rs = null;
                                      Statement stmt = null;
                          
                                      try {
                                          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                          String url = "jdbc:odbc:sessionODBC";
                                          conn = DriverManager.getConnection(url);
                                          stmt = conn.createStatement();
                                      } catch (Exception e) {
                                          System.out.println(e.getMessage());
                                      }
                                      rs = stmt.executeQuery("Select * from MemberParticulars3");
                          %>
                          <html>
                              <head>
                                         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                              </head>
                              <body>
                                       <h5>Members Record</h5>
                                      <table border ="1" cellspacing="0" cellspacing="0" align="center" class="bordered">
                                          <tr><td><b>Member No</b></td>
                                              <td><b>Name</b></td>
                                              <td><b>NRIC</b></td>
                                              <td><b>Email</b></td>
                                              <td><b>Address</b></td>
                                              <td><b>Gender</b></td>
                                              <td><b>Type</b></td>
                                              <td><b>Remarks</b></td>
                                              <td><b>Contact</b></td>
                                          </tr>
                          
                                          <% int no = 1;
                                                      while (rs.next()) {
                                                          int id = rs.getInt("ID");
                                          %>
                                          <tr>
                                              <td><%= id%> </td>
                                              <td> <%=rs.getString("strFullNameME")%> </td>
                                              <td><%=rs.getString("strNRICNOME")%> </td>
                                              <td><%=rs.getString("strEmailME")%> </td>
                                              <td><%=rs.getString("strAddressME")%> </td>
                                              <td><%=rs.getString("strGenderME")%> </td>
                                              <td><%=rs.getString("strTypeME")%> </td>
                                              <td><%=rs.getString("strRemarksME")%> </td>
                                              <td><%=rs.getString("strContactME")%> </td>
                          
                                              <% if (access.equals("admin")) {
                                                                                  out.print("<td><a href=\"Update.jsp?ID=" + id + "\">Update</a></td>");
                                                                              }%>
                          
                                              <% if (access.equals("admin")) {
                                                                                  out.print("<td><a href=\"DeleteMember.jsp?ID=" + id + "\">Delete</a></td>");
                                                                              }%>
                                              <td>
                                                  <%no++;%>
                                              </td></tr> <%}
                                                          rs.close();
                                                          stmt.close();
                                                          conn.close();
                                              %>
                                      </table>
                          
                                      <tr>
                                          <td>Total Number of Members: <%=no - 1%>
                                              <br />
                                              To return to login page : "<a href="login.html">Click here</a>"</td></tr>
                                       <tr>
                                      <td>
                                         To logout : "<a href="logout.jsp">Click here</a>"</td></tr>
                                          
                                  <% if (access.equals("admin")) {
                                                  out.print("<td><a href=\"AddMember.jsp\">Click here to Register Member</a></td>");
                                              } else {
                                                  out.print("<a href=\"AddMember.jsp\"><h5>Register as Member or Volunteer click here</h5></a>");
                                              }%>    
                          </body>
                          </html>

                          Comment

                          Working...