Advertisement
MerAll

DAO backend to Authentication/Authorization filters

Aug 21st, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.94 KB | None | 0 0
  1. package daos;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8.  
  9. public class MerUsersDAO {
  10.  
  11.     private static final String DBCONSTRING = "jdbc:mysql://localhost:3306/merwebappdb";
  12.     private static final String DBUSER = "root";
  13.     private static final String DBPASSWORD="censored";
  14.    
  15.     private static final String GETUSERSTATEMENT="SELECT COUNT(*) FROM registered_users WHERE userid=? AND password=?";
  16.     private static final String GETPERMSSTATEMENT="SELECT COUNT(*) FROM pageperms WHERE pageurl=? AND userid=?";
  17.     public MerUsersDAO() {
  18.     try {
  19.         Class.forName("com.mysql.jdbc.Driver");
  20.     } catch (ClassNotFoundException e) {
  21.         System.err.println("Couldn't load mysql driver.");
  22.     }
  23.    
  24.    
  25.     }
  26.     /**Check to see if a given user is a valid user, with the correct password.
  27.      * This is a login verifier, and should be used with the AUTHENTICATION FILTER.
  28.      * @param username
  29.      * @param password
  30.      * @return true if valid user; false otherwise
  31.      * @throws Exception if database contains more than one user with this username/password
  32.      */
  33.     public boolean isUserValid(String username, String password) throws DBIntegrityException{
  34.    
  35.     try(Connection conn=DriverManager.getConnection(DBCONSTRING,DBUSER,DBPASSWORD);
  36.         PreparedStatement userRecStmt=conn.prepareStatement(GETUSERSTATEMENT))
  37.     {
  38.         userRecStmt.setString(1,username);
  39.         userRecStmt.setString(2,password);
  40.         ResultSet userCount = userRecStmt.executeQuery();  //this is a count bc the sql was SELECT COUNT(*) FROM..
  41.         if(userCount.next()) //first item, only entry should be the count of matching records
  42.         {   int matchingCount  = userCount.getInt(1);
  43.             System.out.printf("Found %d user(s) matching the username %s and password %s.%n",matchingCount,username,password);
  44.             if(matchingCount==1) //should match exactly 1
  45.                 return true;
  46.             else if(matchingCount>1)
  47.                 throw new DBIntegrityException(String.format("Found more than one (%d) user(s) matching the username %s and password %s.%n"
  48.                     + "User id/password combinations should be unique!%n",matchingCount,username,password));
  49.         }
  50.         else
  51.         {   System.out.printf("Did not find any user(s) matching the username %s and password %s.%n",username,password);
  52.             //proceed to return false on exit of try-catch block.
  53.         }
  54.            
  55.            
  56.     } catch (SQLException e) {
  57.         e.printStackTrace();
  58.     }
  59.     return false;
  60.        
  61.        
  62.    
  63.     }
  64.     /**Checks to see whether the user has permission to access a given page.
  65.      * This is an authorization check, and should be used by the AUTHORIZATION FILTER.
  66.      * For the sake of this demo, I'm keeping per-page permissions, vs. permission classes,
  67.      * and those will be maintained in a table called "pageperms" in database merwebappdb.
  68.      * (yes, I know that this is an asstarded way of doing things, but it makes the coding more interesting.)
  69.      *mysql> CREATE TABLE pageperms(pageurl varchar(255),userid varchar(255), UNIQUE KEY (pageurl, userid));
  70.      * mysql> INSERT INTO pageperms VALUES("/Whatever.jsp","merid");
  71.      * @param url page to which access is sought (url is the relative one as specified in struts.xml.)
  72.      * In this table, there can be multiple entries for each userid and pageurl.  They are not unique.
  73.      * @param username user seeking access
  74.      * @return true if user has access to page; false otherwise
  75.      * @throws DBIntegrityException if there is more than one of the same permission PAIR.
  76.      * though each user can have multiple page permissions, and each page multiple users with permissions
  77.      * to it, record of such permission should only occur once per (userid/pageurl) combo.
  78.      */
  79.     public boolean hasPermissionsToPage(String url, String username) throws DBIntegrityException
  80.     {
  81.     try(Connection conn = DriverManager.getConnection(DBCONSTRING,DBUSER,DBPASSWORD);
  82.         PreparedStatement authznStmt = conn.prepareStatement(GETPERMSSTATEMENT)){
  83.         authznStmt.setString(1, url);
  84.         authznStmt.setString(2, username);
  85.         ResultSet foundauthd = authznStmt.executeQuery();
  86.         if(foundauthd.next())
  87.         {
  88.         int count = foundauthd.getInt(1);
  89.         if(count==1) //exactly 1 match is the only correct match
  90.         {
  91.             System.out.printf("Found exactly one match giving the user %s permission to the page %s.%n",username,url);
  92.             return true;
  93.         }
  94.         else if(count>1)
  95.         {
  96.             throw new DBIntegrityException(String.format("Found more than one (%d) records granting user %s permission to page %s.%n",
  97.                 count,username,url));
  98.         }
  99.         }
  100.         else{
  101.           System.out.printf("Did not find any match giving the user %s permission to the page %s.%n",username,url);
  102.         //proceed to return false.
  103.         }
  104.        
  105.     } catch (SQLException e) {
  106.         e.printStackTrace();
  107.     }
  108.     return false;
  109.    
  110.     }
  111.     /**Exception indicating some flaw in the data in the database (such as multiple users
  112.      * with the same username.)
  113.      */
  114.     public class DBIntegrityException extends Exception{
  115.  
  116.     private static final long serialVersionUID = 3669280035176647166L;
  117.     public DBIntegrityException(String message)
  118.     {
  119.         super(message);
  120.     }
  121.     }
  122.  
  123.     public static void main(String[] args) throws Exception{
  124.     MerUsersDAO mdao = new MerUsersDAO();
  125.     System.out.println(mdao.isUserValid("merid", "merpassword"));
  126.     System.out.println(mdao.isUserValid("impostor", "someotherpassword"));
  127.  
  128.     System.out.println(mdao.hasPermissionsToPage("/Whatever.jsp","merid"));
  129.     System.out.println(mdao.isUserValid("/Whatever.jsp","impostor"));
  130.     }
  131.  
  132. }
  133.  
  134. /*Sample output:
  135. Found 1 user(s) matching the username merid and password merpassword.
  136. true
  137. Found 0 user(s) matching the username impostor and password someotherpassword.
  138. false
  139. Found exactly one match giving the user merid permission to the page /Whatever.jsp.
  140. true
  141. Found 0 user(s) matching the username /Whatever.jsp and password impostor.
  142. false
  143. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement