2 * Copyright (c) 2010-2024 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.List;
20 import java.util.Optional;
22 import java.util.stream.Stream;
24 import javax.ws.rs.core.UriBuilder;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.FeatureArea;
29 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.Scope;
30 import org.openhab.binding.netatmo.internal.handler.ApiBridgeHandler;
33 * The {@link AuthenticationApi} handles oAuth2 authentication and token refreshing
35 * @author Gaƫl L'hopital - Initial contribution
36 * @author Jacob Laursen - Refactored to use standard OAuth2 implementation
39 public class AuthenticationApi extends RestManager {
40 public static final URI TOKEN_URI = getApiBaseBuilder(PATH_OAUTH, SUB_PATH_TOKEN).build();
41 public static final URI AUTH_URI = getApiBaseBuilder(PATH_OAUTH, SUB_PATH_AUTHORIZE).build();
43 private List<Scope> grantedScope = List.of();
44 private @Nullable String authorization;
46 public AuthenticationApi(ApiBridgeHandler bridge) {
47 super(bridge, FeatureArea.NONE);
50 public void setAccessToken(@Nullable String accessToken) {
51 if (accessToken != null) {
52 authorization = "Bearer " + accessToken;
58 public void setScope(String scope) {
59 grantedScope = Stream.of(scope.split(" ")).map(s -> Scope.valueOf(s.toUpperCase())).toList();
62 public void dispose() {
64 grantedScope = List.of();
67 public Optional<String> getAuthorization() {
68 return Optional.ofNullable(authorization);
71 public boolean matchesScopes(Set<Scope> requiredScopes) {
72 return requiredScopes.isEmpty() || grantedScope.containsAll(requiredScopes);
75 public boolean isConnected() {
76 return authorization != null;
79 public static UriBuilder getAuthorizationBuilder(String clientId) {
80 return getApiBaseBuilder(PATH_OAUTH, SUB_PATH_AUTHORIZE).queryParam(CLIENT_ID, clientId)
81 .queryParam(SCOPE, FeatureArea.ALL_SCOPES).queryParam(STATE, clientId);