source: sandbox/trunk.old/security/ExpressoCertLogin/src/LoginApplet.java @ 3633

Revision 3633, 12.0 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1430 - Mais de um certificados gravados no mesmo token.

Line 
1
2import java.awt.Frame;
3import java.io.IOException;
4import java.net.MalformedURLException;
5import java.net.URL;
6import java.security.GeneralSecurityException;
7import java.security.ProviderException;
8
9import javax.net.ssl.SSLHandshakeException;
10import javax.swing.JApplet;
11import javax.swing.JOptionPane;
12import javax.swing.SwingUtilities;
13import org.apache.commons.httpclient.HttpException;
14
15import netscape.javascript.JSObject;
16
17import br.gov.serpro.cert.DigitalCertificate;
18import br.gov.serpro.setup.Setup;
19import br.gov.serpro.ui.DialogBuilder;
20
21/**
22 * GUI que realiza o login com certificados A1 e A3 ou login com usuário e senha no expresso.
23 * Esta classe estende a classe JApplet
24 * @author Mário César Kolling - mario.kolling@serpro.gov.br
25 */
26public class LoginApplet extends JApplet {
27
28    /**
29     * Valor gerado aleatoriamente
30     */
31    //TODO: Alterar a cor e fonte dos labels e das caixas de texto e senha.
32    private static final long serialVersionUID = -6204158613173951516L;
33    private DigitalCertificate dc;
34    private Setup setup;
35
36    /* (non-Javadoc)
37     * @see java.applet.Applet#init()
38     */
39    public void init() {
40        super.init();
41        this.setSize(0, 0);
42        this.setup = new Setup(this);
43        this.setup.addLanguageResource("ExpressoCertLoginMessages");
44    }
45
46    /* (non-Javadoc)
47     * @see java.applet.Applet#start()
48     */
49    @Override
50    public void start() {
51        super.start();
52
53        int useCertificate = DigitalCertificate.KEYSTORE_NOT_DETECTED;
54        boolean tryAgain = true;
55
56        do {
57
58            // Cria uma instância de DigitalCertificate e a inicializa
59            this.dc = new DigitalCertificate(this.getDocumentBase(), setup);
60            useCertificate = dc.init();
61            String[] returnCode = null;
62
63            try {
64                switch (useCertificate) {
65                    case DigitalCertificate.KEYSTORE_DETECTED:
66                        // Mostra PinNeedeDialog.
67                        String pin = DialogBuilder.showPinDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup);
68                        if (pin != null) {
69                            dc.openKeyStore(pin.toCharArray());
70                            returnCode = dc.getCredentials(pin);
71
72                            // Faz o login
73                            if (setup.getParameter("debug").equalsIgnoreCase("true")) {
74                                System.out.println("Código de retorno: " + returnCode[0].trim());
75                            }
76
77                            if (returnCode == null){ // Ação cancelada
78                                tryAgain = false;
79                                String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php";
80                                try {
81                                    this.getAppletContext().showDocument(new URL(redirect));
82                                } catch (MalformedURLException e) {
83                                    // TODO Bloco catch gerado automaticamente
84                                    if (setup.getParameter("debug").equalsIgnoreCase("true")) {
85                                        e.printStackTrace();
86                                    }
87                                }
88                            }
89                            else if (Integer.parseInt(returnCode[0].trim()) == 0) {
90
91                                tryAgain = false;
92                                // Pega usuário e senha de credentials[1] e credentials[2], respectivamente
93                                // adiciona na página e faz o submit.
94                                JSObject document = (JSObject) JSObject.getWindow(this).getMember("document");
95                                JSObject loginForm = (JSObject) document.getMember("flogin");
96                                JSObject loginField = (JSObject) loginForm.getMember("user");
97                                loginField.setMember("value", returnCode[1].trim());
98
99                                JSObject passwdField = (JSObject) loginForm.getMember("passwd");
100                                passwdField.setMember("value", returnCode[2].trim());
101
102                                loginForm.call("submit", null);
103                                Thread.yield();
104
105                            } else if (Integer.parseInt(returnCode[0].trim()) == 6) {
106
107                                tryAgain = false;
108
109                                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
110                                    System.out.println("Mensagem de retorno: " + returnCode[1].trim());
111                                }
112
113                                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup);
114
115
116
117                                String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php?cd=98&ts=202";
118                                try {
119                                    this.getAppletContext().showDocument(new URL(redirect));
120                                } catch (MalformedURLException e) {
121                                    // TODO Bloco catch gerado automaticamente
122                                    if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
123                                        e.printStackTrace();
124                                    }
125                                }
126                            } else {
127                                tryAgain = true;
128                                dc.destroy();
129                                System.gc();
130
131                                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
132                                    System.out.println("Mensagem de retorno: " + returnCode[1].trim());
133                                }
134
135                                // Mostra mensagem de erro para o usuário
136                                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup);
137                                Thread.yield();
138                            }
139
140                        } else {
141
142                            tryAgain = false;
143                            String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php";
144                            try {
145                                this.getAppletContext().showDocument(new URL(redirect));
146                            } catch (MalformedURLException e) {
147                                // TODO Bloco catch gerado automaticamente
148                                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
149                                    e.printStackTrace();
150                                }
151                            }
152                        }
153
154                        break;
155                    default:
156
157                        // Mostra Diálogo dizendo que token não foi encontrado
158                        // ou repositório de chaves públicas não foi configurado.
159                        // Tentar carregar token/keystore novamente? / Logon sem certificado digital?
160
161                        tryAgain = false;
162                        if (setup.getParameter("debug").equalsIgnoreCase("true")) {
163                            System.out.println("não achou token");
164                        }
165
166                        dc.destroy();
167                        System.gc();
168
169                        String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php";
170                        try {
171                            this.getAppletContext().showDocument(new URL(redirect));
172                        } catch (MalformedURLException e) {
173                            // TODO Bloco catch gerado automaticamente
174                            if (setup.getParameter("debug").equalsIgnoreCase("true")) {
175                                e.printStackTrace();
176                            }
177                        }
178                }
179
180            } catch (SSLHandshakeException e) {
181                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
182                    e.printStackTrace();
183                }
184                dc.destroy();
185                System.gc();
186                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this),
187                        this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet001"), this.setup);
188
189                Thread.yield();
190
191                tryAgain = true;
192            } catch (HttpException e) {
193                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
194                    e.printStackTrace();
195                }
196
197                tryAgain = true;
198                Thread.yield();
199            } catch (GeneralSecurityException e) {
200                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
201                    e.printStackTrace();
202                }
203
204                DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this),
205                        this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet002"), this.setup);
206
207                Thread.yield();
208                tryAgain = true;
209            } catch (IOException e) {
210                dc.destroy();
211                System.gc();
212
213                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
214                    e.printStackTrace();
215                }
216
217                Throwable cause = null;
218                if ((cause = e.getCause()) != null) {
219                    if (cause instanceof javax.security.auth.login.LoginException) {
220                        DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet003"), this.setup);
221                    } else {
222                        if (setup.getParameter("debug").equalsIgnoreCase("true")) {
223                            System.out.println("Exception lançada: " + cause.getClass().getCanonicalName());
224                        }
225                    }
226                } else {
227                    if (e instanceof java.net.ConnectException) {
228                        DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this),
229                                this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet004"), this.setup);
230                    } else {
231                        if (setup.getParameter("debug").equalsIgnoreCase("true")) {
232                            System.out.println("Exception lançada: " + e.getClass().getCanonicalName());
233                        }
234                    }
235                }
236
237                Thread.yield();
238                tryAgain = true;
239            } catch (ProviderException e) {
240
241                dc.destroy();
242                System.gc();
243
244                if (setup.getParameter("debug").equalsIgnoreCase("true")) {
245                    e.printStackTrace();
246                }
247
248                int resultado = DialogBuilder.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this),
249                        //"Deseja tentar carregá-lo novamente?",
250                        this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet005"),
251                        JOptionPane.QUESTION_MESSAGE,
252                        JOptionPane.OK_CANCEL_OPTION, this.setup);
253
254                if (resultado == JOptionPane.OK_OPTION) {
255                    tryAgain = true;
256                } else {
257                    tryAgain = false;
258                }
259
260                Thread.yield();
261            }
262
263        } while (tryAgain);
264
265    }
266
267    /**
268     * Destrói a Applet, executando códigos para desregistrar tokens, keystores, etc.
269     */
270    @Override
271    public void stop() {
272        //super.destroy();
273        if (setup.getParameter("debug").equalsIgnoreCase("true")) {
274            System.out.println("Finalizando Applet de Login!");
275        }
276
277        this.dc.destroy();
278        this.dc = null;
279        System.gc();
280    }
281}
Note: See TracBrowser for help on using the repository browser.