2 * Copyright (c) 2010-2022 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;
21 import java.util.Optional;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
27 import javax.ws.rs.core.UriBuilder;
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;
40 * The {@link AuthenticationApi} handles oAuth2 authentication and token refreshing
42 * @author Gaƫl L'hopital - Initial contribution
45 public class AuthenticationApi extends RestManager {
46 private static final String ALL_SCOPES = FeatureArea.toScopeString(FeatureArea.AS_SET);
47 private static final UriBuilder OAUTH_BUILDER = getApiBaseBuilder().path(PATH_OAUTH);
48 private static final UriBuilder AUTH_BUILDER = OAUTH_BUILDER.clone().path(SUB_PATH_AUTHORIZE);
49 private static final URI TOKEN_URI = OAUTH_BUILDER.clone().path(SUB_PATH_TOKEN).build();
51 private final Logger logger = LoggerFactory.getLogger(AuthenticationApi.class);
52 private final ScheduledExecutorService scheduler;
54 private Optional<ScheduledFuture<?>> refreshTokenJob = Optional.empty();
55 private Optional<AccessTokenResponse> tokenResponse = Optional.empty();
57 public AuthenticationApi(ApiBridgeHandler bridge, ScheduledExecutorService scheduler) {
58 super(bridge, FeatureArea.NONE);
59 this.scheduler = scheduler;
62 public String authorize(ApiHandlerConfiguration credentials, @Nullable String code, @Nullable String redirectUri)
63 throws NetatmoException {
64 if (!(credentials.clientId.isBlank() || credentials.clientSecret.isBlank())) {
65 Map<String, String> params = new HashMap<>(Map.of(SCOPE, ALL_SCOPES));
66 String refreshToken = credentials.refreshToken;
67 if (!refreshToken.isBlank()) {
68 params.put(REFRESH_TOKEN, refreshToken);
70 if (code != null && redirectUri != null) {
71 params.putAll(Map.of(REDIRECT_URI, redirectUri, CODE, code));
74 if (params.size() > 1) {
75 return requestToken(credentials.clientId, credentials.clientSecret, params);
78 throw new IllegalArgumentException("Inconsistent configuration state, please file a bug report.");
81 private String requestToken(String id, String secret, Map<String, String> entries) throws NetatmoException {
82 Map<String, String> payload = new HashMap<>(entries);
83 payload.put(GRANT_TYPE, payload.keySet().contains(CODE) ? AUTHORIZATION_CODE : REFRESH_TOKEN);
84 payload.putAll(Map.of(CLIENT_ID, id, CLIENT_SECRET, secret));
86 AccessTokenResponse response = post(TOKEN_URI, AccessTokenResponse.class, payload);
87 refreshTokenJob = Optional.of(scheduler.schedule(() -> {
89 requestToken(id, secret, Map.of(REFRESH_TOKEN, response.getRefreshToken()));
90 } catch (NetatmoException e) {
91 logger.warn("Unable to refresh access token : {}", e.getMessage());
93 }, Math.round(response.getExpiresIn() * 0.8), TimeUnit.SECONDS));
94 tokenResponse = Optional.of(response);
95 return response.getRefreshToken();
98 public void disconnect() {
99 tokenResponse = Optional.empty();
102 public void dispose() {
103 refreshTokenJob.ifPresent(job -> job.cancel(true));
104 refreshTokenJob = Optional.empty();
107 public @Nullable String getAuthorization() {
108 return tokenResponse.map(at -> String.format("Bearer %s", at.getAccessToken())).orElse(null);
111 public boolean matchesScopes(Set<Scope> requiredScopes) {
112 return requiredScopes.isEmpty() // either we do not require any scope, either connected and all scopes available
113 || (isConnected() && tokenResponse.map(at -> at.getScope().containsAll(requiredScopes)).orElse(false));
116 public boolean isConnected() {
117 return tokenResponse.isPresent();
120 public static UriBuilder getAuthorizationBuilder(String clientId) {
121 return AUTH_BUILDER.clone().queryParam(CLIENT_ID, clientId).queryParam(SCOPE, ALL_SCOPES).queryParam(STATE,