KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > echoserver > EchoAuthenticatorHandler


1 /*
2  * This file is part of the QuickServer library
3  * Copyright (C) QuickServer.org
4  *
5  * Use, modification, copying and distribution of this software is subject to
6  * the terms and conditions of the GNU Lesser General Public License.
7  * You should have received a copy of the GNU LGP License along with this
8  * library; if not, you can download a copy from <http://www.quickserver.org/>.
9  *
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.util.*;
20 import org.quickserver.net.AppException;
21
22 /**
23  * Needs ClientData
24  */

25 public class EchoAuthenticatorHandler extends QuickAuthenticationHandler {
26     public AuthStatus askAuthentication(ClientHandler handler)
27             throws IOException, AppException {
28         Data data = (Data) handler.getClientData();
29         data.setLastAsked("U");
30         handler.sendClientMsg("User Name :");
31         return null;//no AuthStatus yet
32
}
33
34     public AuthStatus handleAuthentication(ClientHandler handler, String JavaDoc command)
35             throws IOException, AppException {
36         Data data = (Data)handler.getClientData();
37
38         if(data.getLastAsked().equals("U")) {
39             data.setUsername(command);
40             data.setLastAsked("P");
41             handler.sendClientMsg("Password :");
42         } else if(data.getLastAsked().equals("P")) {
43             data.setPassword(command.getBytes());
44             
45             if(validate(handler, data.getUsername(), data.getPassword())) {
46                 handler.sendClientMsg("Auth OK");
47                 data.setPassword(null);
48                 return AuthStatus.SUCCESS;
49             } else {
50                 handler.sendClientMsg("Auth Failed");
51                 data.setPassword(null);
52                 return AuthStatus.FAILURE;
53             }
54         } else {
55             throw new AppException("Unknown LastAsked!");
56         }
57
58         return null;//no AuthStatus yet
59
}
60
61     /**
62      * This function is used to validate username and password.
63      * May be overridden to change username and/or password.
64      */

65     protected static boolean validate(ClientHandler handler, String JavaDoc username, byte[] password) {
66         return Arrays.equals(password,username.getBytes());
67     }
68 }
69
Popular Tags