]> git.basschouten.com Git - openhab-addons.git/blob
33152e38662d9020d97468c127c639f0aa47b099
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.homematic.internal.common;
14
15 import java.util.Base64;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.eclipse.jetty.client.api.Request;
20 import org.eclipse.jetty.http.HttpHeader;
21 import org.openhab.core.i18n.ConfigurationException;
22
23 /**
24  * Handles the authentication to Homematic server.
25  *
26  * @author Christian Kittel
27  */
28 @NonNullByDefault
29 public class AuthenticationHandler {
30
31     private Boolean useAuthentication;
32     private @Nullable String authValue;
33
34     public AuthenticationHandler(HomematicConfig config) throws ConfigurationException {
35         this.useAuthentication = config.getUseAuthentication();
36         if (!useAuthentication) {
37             return;
38         }
39
40         if (config.getPassword() == null || config.getUserName() == null) {
41             throw new ConfigurationException("Username or password missing");
42         }
43         this.authValue = "Basic "
44                 + Base64.getEncoder().encodeToString((config.getUserName() + ":" + config.getPassword()).getBytes());
45     }
46
47     /**
48      * Add or remove the basic auth credentials th the request if needed.
49      */
50     public Request updateAuthenticationInformation(final Request request) {
51         return useAuthentication ? request.header(HttpHeader.AUTHORIZATION, authValue) : request;
52     }
53 }