]> git.basschouten.com Git - openhab-addons.git/blob
5aabc4194ec2238accd33dcee25f8910e3e98623
[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.*;
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 javax.ws.rs.core.UriBuilder;
28
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.FeatureArea;
32 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.Scope;
33 import org.openhab.binding.netatmo.internal.api.dto.AccessTokenResponse;
34 import org.openhab.binding.netatmo.internal.config.ApiHandlerConfiguration;
35 import org.openhab.binding.netatmo.internal.handler.ApiBridgeHandler;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * The {@link AuthenticationApi} handles oAuth2 authentication and token refreshing
41  *
42  * @author GaĆ«l L'hopital - Initial contribution
43  */
44 @NonNullByDefault
45 public class AuthenticationApi extends RestManager {
46     private static final UriBuilder OAUTH_BUILDER = getApiBaseBuilder().path(PATH_OAUTH);
47     private static final UriBuilder AUTH_BUILDER = OAUTH_BUILDER.clone().path(SUB_PATH_AUTHORIZE);
48     private static final URI TOKEN_URI = OAUTH_BUILDER.clone().path(SUB_PATH_TOKEN).build();
49
50     private final Logger logger = LoggerFactory.getLogger(AuthenticationApi.class);
51     private final ScheduledExecutorService scheduler;
52
53     private Optional<ScheduledFuture<?>> refreshTokenJob = Optional.empty();
54     private Optional<AccessTokenResponse> tokenResponse = Optional.empty();
55
56     public AuthenticationApi(ApiBridgeHandler bridge, ScheduledExecutorService scheduler) {
57         super(bridge, FeatureArea.NONE);
58         this.scheduler = scheduler;
59     }
60
61     public String authorize(ApiHandlerConfiguration credentials, Set<FeatureArea> features, @Nullable String code,
62             @Nullable String redirectUri) throws NetatmoException {
63         String clientId = credentials.clientId;
64         String clientSecret = credentials.clientSecret;
65         if (!(clientId.isBlank() || clientSecret.isBlank())) {
66             Map<String, String> params = new HashMap<>(Map.of(SCOPE, toScopeString(features)));
67             String refreshToken = credentials.refreshToken;
68             if (!refreshToken.isBlank()) {
69                 params.put(REFRESH_TOKEN, refreshToken);
70             } else {
71                 if (code != null && redirectUri != null) {
72                     params.putAll(Map.of(REDIRECT_URI, redirectUri, CODE, code));
73                 }
74             }
75             if (params.size() > 1) {
76                 return requestToken(clientId, clientSecret, params);
77             }
78         }
79         throw new IllegalArgumentException("Inconsistent configuration state, please file a bug report.");
80     }
81
82     private String requestToken(String id, String secret, Map<String, String> entries) throws NetatmoException {
83         Map<String, String> payload = new HashMap<>(entries);
84         payload.put(GRANT_TYPE, payload.keySet().contains(CODE) ? AUTHORIZATION_CODE : REFRESH_TOKEN);
85         payload.putAll(Map.of(CLIENT_ID, id, CLIENT_SECRET, secret));
86         disconnect();
87         AccessTokenResponse response = post(TOKEN_URI, AccessTokenResponse.class, payload);
88         refreshTokenJob = Optional.of(scheduler.schedule(() -> {
89             try {
90                 requestToken(id, secret, Map.of(REFRESH_TOKEN, response.getRefreshToken()));
91             } catch (NetatmoException e) {
92                 logger.warn("Unable to refresh access token : {}", e.getMessage());
93             }
94         }, Math.round(response.getExpiresIn() * 0.8), TimeUnit.SECONDS));
95         tokenResponse = Optional.of(response);
96         return response.getRefreshToken();
97     }
98
99     public void disconnect() {
100         tokenResponse = Optional.empty();
101     }
102
103     public void dispose() {
104         refreshTokenJob.ifPresent(job -> job.cancel(true));
105         refreshTokenJob = Optional.empty();
106     }
107
108     public @Nullable String getAuthorization() {
109         return tokenResponse.map(at -> String.format("Bearer %s", at.getAccessToken())).orElse(null);
110     }
111
112     public boolean matchesScopes(Set<Scope> requiredScopes) {
113         return requiredScopes.isEmpty() // either we do not require any scope, either connected and all scopes available
114                 || (isConnected() && tokenResponse.map(at -> at.getScope().containsAll(requiredScopes)).orElse(false));
115     }
116
117     public boolean isConnected() {
118         return tokenResponse.isPresent();
119     }
120
121     private static String toScopeString(Set<FeatureArea> features) {
122         return FeatureArea.toScopeString(features.isEmpty() ? FeatureArea.AS_SET : features);
123     }
124
125     public static UriBuilder getAuthorizationBuilder(String clientId, Set<FeatureArea> features) {
126         return AUTH_BUILDER.clone().queryParam(CLIENT_ID, clientId).queryParam(SCOPE, toScopeString(features))
127                 .queryParam(STATE, clientId);
128     }
129 }