aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/main/java/com/vaadin/ui/LoginForm.java
blob: 72d4e0159618ebdc0702ece3a55e6588c58bd6b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
 * Copyright 2000-2022 Vaadin Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.vaadin.ui;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.vaadin.event.SerializableEventListener;
import com.vaadin.server.StreamResource;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.Registration;
import com.vaadin.shared.ui.loginform.LoginFormConstants;
import com.vaadin.shared.ui.loginform.LoginFormRpc;
import com.vaadin.shared.ui.loginform.LoginFormState;
import com.vaadin.util.ReflectTools;

/**
 * Login form with auto-completion and auto-fill for all major browsers. You can
 * derive from this class and implement the
 * {@link #createContent(com.vaadin.ui.TextField, com.vaadin.ui.PasswordField, com.vaadin.ui.Button)}
 * method to build the layout using the text fields and login button that are
 * passed to that method. The supplied components are specially treated so that
 * they work with password managers.
 * <p>
 * To customize the fields or to replace them with your own implementations, you
 * can override {@link #createUsernameField()}, {@link #createPasswordField()}
 * and {@link #createLoginButton()}. These methods are called automatically and
 * cannot be called by your code. Captions can be reset by overriding
 * {@link #getUsernameCaption()}, {@link #getPasswordCaption()} and
 * {@link #getLoginButtonCaption()}.
 * <p>
 * Note that the API of LoginForm changed significantly in Vaadin 7.7.
 *
 * @since 5.3
 */
public class LoginForm extends AbstractSingleComponentContainer {

    /**
     * Event sent when the login form is submitted.
     */
    public static class LoginEvent extends Component.Event {

        private final Map<String, String> params;

        /**
         * Creates a login event using the given source and the given
         * parameters.
         *
         * @param source
         *            the source of the event
         * @param params
         */
        private LoginEvent(LoginForm source, Map<String, String> params) {
            super(source);
            this.params = params;
        }

        @Override
        public LoginForm getSource() {
            return (LoginForm) super.getSource();
        }

        /**
         * Gets the login parameter with the given name.
         *
         * @param name
         *            the name of the parameter
         * @return the value of the parameter or null if no such parameter is
         *         present
         */
        public String getLoginParameter(String name) {
            return params.get(name);
        }
    }

    /**
     * Listener triggered when a login occurs in a {@link LoginForm}.
     */
    @FunctionalInterface
    public interface LoginListener extends SerializableEventListener {
        /**
         * Event method invoked when the login button is pressed in a login
         * form.
         *
         * @param event
         *            the login event
         */
        public void onLogin(LoginEvent event);
    }

    /**
     * Internal stream source for the login URL - always returns "Success" and
     * ignores the values received.
     */
    private static class LoginStreamSource
            implements StreamResource.StreamSource {
        @Override
        public InputStream getStream() {
            return new ByteArrayInputStream(
                    "<html>Success</html>".getBytes(StandardCharsets.UTF_8));
        }
    }

    private static final Method ON_LOGIN_METHOD = ReflectTools
            .findMethod(LoginListener.class, "onLogin", LoginEvent.class);

    private boolean initialized;

    private String usernameCaption = "Username";
    private String passwordCaption = "Password";
    private String loginButtonCaption = "Login";

    /**
     * Customize the user name field. Only for overriding, do not call.
     *
     * @return the user name field
     * @since 7.7
     */
    protected TextField createUsernameField() {
        throwIfInitialized();
        TextField field = new TextField(getUsernameCaption());
        field.focus();
        return field;
    }

    /**
     * Gets the caption set with {@link #setUsernameCaption(String)}. Note that
     * this method might not match what is shown to the user if
     * {@link #createUsernameField()} has been overridden.
     *
     * @return the user name field caption
     */
    public String getUsernameCaption() {
        return usernameCaption;
    }

    /**
     * Sets the caption of the user name field. Note that the caption can only
     * be set with this method before the login form has been initialized
     * (attached).
     * <p>
     * As an alternative to calling this method, the method
     * {@link #createUsernameField()} can be overridden.
     *
     * @param usernameCaption
     *            the caption to set for the user name field
     */
    public void setUsernameCaption(String usernameCaption) {
        this.usernameCaption = usernameCaption;
    }

    /**
     * Customize the password field. Only for overriding, do not call.
     *
     * @return the password field
     * @since 7.7
     */
    protected PasswordField createPasswordField() {
        throwIfInitialized();
        return new PasswordField(getPasswordCaption());
    }

    /**
     * Gets the caption set with {@link #setPasswordCaption(String)}. Note that
     * this method might not match what is shown to the user if
     * {@link #createPasswordField()} has been overridden.
     *
     *
     * @return the password field caption
     */
    public String getPasswordCaption() {
        return passwordCaption;
    }

    /**
     * Set the caption of the password field. Note that the caption can only be
     * set with this method before the login form has been initialized
     * (attached).
     * <p>
     * As an alternative to calling this method, the method
     * {@link #createPasswordField()} can be overridden.
     *
     * @param passwordCaption
     *            the caption for the password field
     */
    public void setPasswordCaption(String passwordCaption) {
        this.passwordCaption = passwordCaption;
    }

    /**
     * Customize the login button. Only for overriding, do not call.
     *
     * @return the login button
     * @since 7.7
     */
    protected Button createLoginButton() {
        throwIfInitialized();
        return new Button(getLoginButtonCaption());
    }

    /**
     * Gets the caption set with {@link #setLoginButtonCaption(String)}. Note
     * that this method might not match what is shown to the user if
     * {@link #createLoginButton()} has been overridden.
     *
     * @return the login button caption
     */
    public String getLoginButtonCaption() {
        return loginButtonCaption;
    }

    /**
     * Sets the caption of the login button. Note that the caption can only be
     * set with this method before the login form has been initialized
     * (attached).
     * <p>
     * As an alternative to calling this method, the method
     * {@link #createLoginButton()} can be overridden.
     *
     * @param loginButtonCaption
     *            new caption
     */
    public void setLoginButtonCaption(String loginButtonCaption) {
        this.loginButtonCaption = loginButtonCaption;
    }

    @Override
    protected LoginFormState getState() {
        return (LoginFormState) super.getState();
    }

    @Override
    protected LoginFormState getState(boolean markAsDirty) {
        return (LoginFormState) super.getState(markAsDirty);
    }

    @Override
    public void attach() {
        super.attach();
        init();
    }

    private void throwIfInitialized() {
        if (initialized) {
            throw new IllegalStateException(
                    "Already initialized. The create methods may not be called explicitly.");
        }
    }

    /**
     * Create the content for the login form with the supplied user name field,
     * password field and the login button. You cannot use any other text fields
     * or buttons for this purpose. To replace these components with your own
     * implementations, override {@link #createUsernameField()},
     * {@link #createPasswordField()} and {@link #createLoginButton()}. If you
     * only want to change the default captions, override
     * {@link #getUsernameCaption()}, {@link #getPasswordCaption()} and
     * {@link #getLoginButtonCaption()}. You do not have to use the login button
     * in your layout.
     *
     * @param userNameField
     *            the user name text field
     * @param passwordField
     *            the password field
     * @param loginButton
     *            the login button
     * @return content component
     * @since 7.7
     */
    protected Component createContent(TextField userNameField,
            PasswordField passwordField, Button loginButton) {
        VerticalLayout layout = new VerticalLayout();
        layout.setSpacing(true);
        layout.setMargin(true);
        layout.addComponent(userNameField);
        layout.addComponent(passwordField);
        layout.addComponent(loginButton);
        return layout;
    }

    private void init() {
        if (initialized) {
            return;
        }

        LoginFormState state = getState();
        state.userNameFieldConnector = createUsernameField();
        state.passwordFieldConnector = createPasswordField();
        state.loginButtonConnector = createLoginButton();

        StreamResource resource = new StreamResource(new LoginStreamSource(),
                LoginFormConstants.LOGIN_RESOURCE_NAME);
        resource.setMIMEType(ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8);
        resource.setCacheTime(-1);
        setResource(LoginFormConstants.LOGIN_RESOURCE_NAME, resource);

        registerRpc((LoginFormRpc) this::login);

        initialized = true;

        setContent(createContent(getUsernameField(), getPasswordField(),
                getLoginButton()));
    }

    private TextField getUsernameField() {
        assert initialized;
        return (TextField) getState(false).userNameFieldConnector;
    }

    private PasswordField getPasswordField() {
        assert initialized;
        return (PasswordField) getState(false).passwordFieldConnector;
    }

    private Button getLoginButton() {
        assert initialized;
        return (Button) getState(false).loginButtonConnector;
    }

    /**
     * Handles the login.
     * <p>
     * In deferred mode, this method is called after the dummy POST request that
     * triggers the password manager has been completed. In direct mode (the
     * default setting), it is called directly when the user hits the enter key
     * or clicks on the login button. In the latter case, you cannot change the
     * URL in the method or the password manager will not be triggered.
     */
    private void login() {
        Map<String, String> params = new HashMap<>();
        params.put("username", getUsernameField().getValue());
        params.put("password", getPasswordField().getValue());
        LoginEvent event = new LoginEvent(LoginForm.this, params);
        fireEvent(event);
    }

    /**
     * Adds a {@link LoginListener}.
     * <p>
     * The listener is called when the user presses the login button.
     *
     * @param listener
     *            the listener to add
     * @return a registration object for removing the listener
     * @since 8.0
     */
    public Registration addLoginListener(LoginListener listener) {
        return addListener(LoginEvent.class, listener, ON_LOGIN_METHOD);
    }

    /**
     * Removes a {@link LoginListener}.
     *
     * @param listener
     *            the listener to remove
     * @deprecated As of 8.0, replaced by {@link Registration#remove()} in the
     *             registration object returned from
     *             {@link #addLoginListener(LoginListener)}.
     */
    @Deprecated
    public void removeLoginListener(LoginListener listener) {
        removeListener(LoginEvent.class, listener, ON_LOGIN_METHOD);
    }

}