1 14 15 package echoserver; 16 17 import org.quickserver.net.server.*; 18 import java.io.*; 19 import java.sql.*; 20 import java.util.*; 21 import org.quickserver.net.AppException; 22 23 public class EchoServerAuthenticatorDBBased extends QuickAuthenticationHandler { 24 public AuthStatus askAuthentication(ClientHandler handler) 25 throws IOException, AppException { 26 Data data = (Data) handler.getClientData(); 27 data.setLastAsked("U"); 28 handler.sendClientMsg("User Name :"); 29 return null; 30 } 31 32 public AuthStatus handleAuthentication(ClientHandler handler, String command) 33 throws IOException, AppException { 34 Data data = (Data)handler.getClientData(); 35 36 if(data.getLastAsked().equals("U")) { 37 data.setUsername(command); 38 data.setLastAsked("P"); 39 handler.sendClientMsg("Password :"); 40 } else if(data.getLastAsked().equals("P")) { 41 data.setPassword(command.getBytes()); 42 43 if(validate(handler, data.getUsername(), data.getPassword())) { 44 handler.sendClientMsg("Auth OK"); 45 data.setPassword(null); 46 handler.sendClientMsg(data.getWelcomeMsg()); 47 return AuthStatus.SUCCESS; 48 } else { 49 handler.sendClientMsg("Auth Failed"); 50 data.setPassword(null); 51 return AuthStatus.FAILURE; 52 } 53 } else { 54 throw new AppException("Unknown LastAsked!"); 55 } 56 57 return null; 58 } 59 60 protected static boolean validate(ClientHandler handler, String username, byte[] password) { 61 Connection con = null; 62 try { 63 con = handler.getServer().getDBPoolUtil().getConnection("TestDB1"); 64 Statement s = con.createStatement(); 65 ResultSet r = s.executeQuery("SELECT welcomemesage FROM Auth "+ 66 "WHERE USERNAME='"+username+"' AND PASSWORD='"+new String (password)+"'"); 67 if(r.next()) { 68 Data data = (Data)handler.getClientData(); 69 data.setWelcomeMsg(r.getString(1)); 70 return true; 71 } else { 72 return false; 73 } 74 } catch(Exception e) { 75 return false; 76 } finally { 77 try { 78 con.close(); 79 } catch(Exception e) { 80 handler.sendSystemMsg("IGNORING: "+e); 81 } 82 } 83 } 84 } 85 | Popular Tags |