2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.netatmo.internal.api;
15 import static org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.*;
16 import static org.openhab.core.auth.oauth2client.internal.Keyword.*;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.Optional;
24 import java.util.concurrent.ScheduledExecutorService;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
28 import javax.ws.rs.core.UriBuilder;
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;
41 * The {@link AuthenticationApi} handles oAuth2 authentication and token refreshing
43 * @author Gaƫl L'hopital - Initial contribution
46 public class AuthenticationApi extends RestManager {
47 private static final URI TOKEN_URI = getApiBaseBuilder(PATH_OAUTH, SUB_PATH_TOKEN).build();
49 private final Logger logger = LoggerFactory.getLogger(AuthenticationApi.class);
50 private final ScheduledExecutorService scheduler;
52 private Optional<ScheduledFuture<?>> refreshTokenJob = Optional.empty();
53 private List<Scope> grantedScope = List.of();
54 private @Nullable String authorization;
56 public AuthenticationApi(ApiBridgeHandler bridge, ScheduledExecutorService scheduler) {
57 super(bridge, FeatureArea.NONE);
58 this.scheduler = scheduler;
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));
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));
72 if (params.size() > 1) {
73 requestToken(credentials.clientId, credentials.clientSecret, params);
77 throw new IllegalArgumentException("Inconsistent configuration state, please file a bug report.");
80 private void requestToken(String clientId, String secret, Map<String, String> entries) throws NetatmoException {
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));
87 AccessTokenResponse response = post(TOKEN_URI, AccessTokenResponse.class, payload);
89 refreshTokenJob = Optional.of(scheduler.schedule(() -> {
91 requestToken(clientId, secret, Map.of(REFRESH_TOKEN, response.getRefreshToken()));
92 } catch (NetatmoException e) {
93 logger.warn("Unable to refresh access token : {}", e.getMessage());
95 }, Math.round(response.getExpiresIn() * 0.9), TimeUnit.SECONDS));
97 grantedScope = response.getScope();
98 authorization = "Bearer %s".formatted(response.getAccessToken());
99 apiBridge.storeRefreshToken(response.getRefreshToken());
102 public void disconnect() {
103 authorization = null;
104 grantedScope = List.of();
107 public void dispose() {
109 refreshTokenJob.ifPresent(job -> job.cancel(true));
110 refreshTokenJob = Optional.empty();
113 public Optional<String> getAuthorization() {
114 return Optional.ofNullable(authorization);
117 public boolean matchesScopes(Set<Scope> requiredScopes) {
118 return requiredScopes.isEmpty() || grantedScope.containsAll(requiredScopes);
121 public boolean isConnected() {
122 return authorization != null;
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);