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