]> git.basschouten.com Git - openhab-addons.git/blob
2da5144aef2c8142713584f4f71d5acb3b98ab1a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.netatmo.internal.api;
14
15 import static org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.PATH_OAUTH;
16 import static org.openhab.core.auth.oauth2client.internal.Keyword.*;
17
18 import java.net.URI;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Optional;
22 import java.util.Set;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.FeatureArea;
30 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.Scope;
31 import org.openhab.binding.netatmo.internal.api.dto.AccessTokenResponse;
32 import org.openhab.binding.netatmo.internal.config.ApiHandlerConfiguration.Credentials;
33 import org.openhab.binding.netatmo.internal.handler.ApiBridgeHandler;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * The {@link AuthenticationApi} handles oAuth2 authentication and token refreshing
39  *
40  * @author GaĆ«l L'hopital - Initial contribution
41  */
42 @NonNullByDefault
43 public class AuthenticationApi extends RestManager {
44     private static final URI OAUTH_URI = getApiBaseBuilder().path(PATH_OAUTH).build();
45
46     private final ScheduledExecutorService scheduler;
47     private final Logger logger = LoggerFactory.getLogger(AuthenticationApi.class);
48
49     private @Nullable ScheduledFuture<?> refreshTokenJob;
50     private Optional<AccessTokenResponse> tokenResponse = Optional.empty();
51     private String scope = "";
52
53     public AuthenticationApi(ApiBridgeHandler bridge, ScheduledExecutorService scheduler) {
54         super(bridge, FeatureArea.NONE);
55         this.scheduler = scheduler;
56     }
57
58     public void authenticate(Credentials credentials, Set<FeatureArea> features) throws NetatmoException {
59         Set<FeatureArea> requestedFeatures = !features.isEmpty() ? features : FeatureArea.AS_SET;
60         scope = FeatureArea.toScopeString(requestedFeatures);
61         requestToken(credentials.clientId, credentials.clientSecret,
62                 Map.of(USERNAME, credentials.username, PASSWORD, credentials.password, SCOPE, scope));
63     }
64
65     private void requestToken(String id, String secret, Map<String, String> entries) throws NetatmoException {
66         Map<String, String> payload = new HashMap<>(entries);
67         payload.putAll(Map.of(GRANT_TYPE, entries.keySet().contains(PASSWORD) ? PASSWORD : REFRESH_TOKEN, CLIENT_ID, id,
68                 CLIENT_SECRET, secret));
69         disconnect();
70         AccessTokenResponse response = post(OAUTH_URI, AccessTokenResponse.class, payload);
71         refreshTokenJob = scheduler.schedule(() -> {
72             try {
73                 requestToken(id, secret, Map.of(REFRESH_TOKEN, response.getRefreshToken()));
74             } catch (NetatmoException e) {
75                 logger.warn("Unable to refresh access token : {}", e.getMessage());
76             }
77         }, Math.round(response.getExpiresIn() * 0.8), TimeUnit.SECONDS);
78         tokenResponse = Optional.of(response);
79     }
80
81     public void disconnect() {
82         tokenResponse = Optional.empty();
83     }
84
85     public void dispose() {
86         ScheduledFuture<?> job = refreshTokenJob;
87         if (job != null) {
88             job.cancel(true);
89         }
90         refreshTokenJob = null;
91     }
92
93     public @Nullable String getAuthorization() {
94         return tokenResponse.map(at -> String.format("Bearer %s", at.getAccessToken())).orElse(null);
95     }
96
97     public boolean matchesScopes(Set<Scope> requiredScopes) {
98         // either we do not require any scope, either connected and all scopes available
99         return requiredScopes.isEmpty()
100                 || (isConnected() && tokenResponse.map(at -> at.getScope().containsAll(requiredScopes)).orElse(false));
101     }
102
103     public boolean isConnected() {
104         return !tokenResponse.isEmpty();
105     }
106 }