01: /*
02: * This file is part of the QuickServer library
03: * Copyright (C) 2003-2005 QuickServer.org
04: *
05: * Use, modification, copying and distribution of this software is subject to
06: * the terms and conditions of the GNU Lesser General Public License.
07: * You should have received a copy of the GNU LGP License along with this
08: * library; if not, you can download a copy from <http://www.quickserver.org/>.
09: *
10: * For questions, suggestions, bug-reports, enhancement-requests etc.
11: * visit http://www.quickserver.org
12: *
13: */
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
24: QuickAuthenticationHandler {
25: public AuthStatus askAuthentication(ClientHandler handler)
26: throws IOException, AppException {
27: Data data = (Data) handler.getClientData();
28: data.setLastAsked("U");
29: handler.sendClientMsg("User Name :");
30: return null;
31: }
32:
33: public AuthStatus handleAuthentication(ClientHandler handler,
34: String command) throws IOException, AppException {
35: Data data = (Data) handler.getClientData();
36:
37: if (data.getLastAsked().equals("U")) {
38: data.setUsername(command);
39: data.setLastAsked("P");
40: handler.sendClientMsg("Password :");
41: } else if (data.getLastAsked().equals("P")) {
42: data.setPassword(command.getBytes());
43:
44: if (validate(handler, data.getUsername(), data
45: .getPassword())) {
46: handler.sendClientMsg("Auth OK");
47: data.setPassword(null);
48: handler.sendClientMsg(data.getWelcomeMsg());
49: return AuthStatus.SUCCESS;
50: } else {
51: handler.sendClientMsg("Auth Failed");
52: data.setPassword(null);
53: return AuthStatus.FAILURE;
54: }
55: } else {
56: throw new AppException("Unknown LastAsked!");
57: }
58:
59: return null;
60: }
61:
62: protected static boolean validate(ClientHandler handler,
63: String username, byte[] password) {
64: Connection con = null;
65: try {
66: con = handler.getServer().getDBPoolUtil().getConnection(
67: "TestDB1");
68: Statement s = con.createStatement();
69: ResultSet r = s
70: .executeQuery("SELECT welcomemesage FROM Auth "
71: + "WHERE USERNAME='" + username
72: + "' AND PASSWORD='" + new String(password)
73: + "'");
74: if (r.next()) {
75: Data data = (Data) handler.getClientData();
76: data.setWelcomeMsg(r.getString(1));
77: return true;
78: } else {
79: return false;
80: }
81: } catch (Exception e) {
82: return false;
83: } finally {
84: try {
85: con.close();
86: } catch (Exception e) {
87: handler.sendSystemMsg("IGNORING: " + e);
88: }
89: }
90: }
91: }
|