Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[tado] Add OAuth authentication (deadline 2025-03-15) #18354

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
537 changes: 272 additions & 265 deletions bundles/org.openhab.binding.tado/README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@
package org.openhab.binding.tado.internal.api;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.tado.internal.auth.OAuthorizerV2;
import org.openhab.binding.tado.swagger.codegen.api.GsonBuilderFactory;
import org.openhab.binding.tado.swagger.codegen.api.auth.Authorizer;
import org.openhab.binding.tado.swagger.codegen.api.auth.OAuthAuthorizer;
import org.openhab.binding.tado.swagger.codegen.api.client.HomeApi;
import org.openhab.core.auth.client.oauth2.OAuthClientService;

import com.google.gson.Gson;

/**
* Factory to create and configure {@link HomeApi} instances.
*
* @author Dennis Frommknecht - Initial contribution
* @author Andrew Fiddian-Green - Use OAuthAuthorizerV2
*/
@NonNullByDefault
public class HomeApiFactory {
Expand All @@ -37,4 +40,10 @@ public HomeApi create(String username, String password) {
.clientSecret(OAUTH_CLIENT_SECRET).scopes(OAUTH_SCOPE);
return new HomeApi(gson, authorizer);
}

public HomeApi create(OAuthClientService oAuthClientService) {
Gson gson = GsonBuilderFactory.defaultGsonBuilder().create();
Authorizer authorizer = new OAuthorizerV2(oAuthClientService);
return new HomeApi(gson, authorizer);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2010-2025 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.tado.internal.auth;

import java.io.IOException;

import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpHeader;
import org.openhab.binding.tado.swagger.codegen.api.auth.Authorizer;
import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
import org.openhab.core.auth.client.oauth2.DeviceCodeResponse;

Check failure on line 22 in bundles/org.openhab.binding.tado/src/main/java/org/openhab/binding/tado/internal/auth/OAuthorizerV2.java

View workflow job for this annotation

GitHub Actions / Build (Java 21, ubuntu-24.04)

The import org.openhab.core.auth.client.oauth2.DeviceCodeResponse cannot be resolved
import org.openhab.core.auth.client.oauth2.OAuthClientService;
import org.openhab.core.auth.client.oauth2.OAuthException;
import org.openhab.core.auth.client.oauth2.OAuthResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* This is a new {@link Authorizer} that is mandated by Tado after March 15 2025.
*
* @see <a href="https://support.tado.com/en/articles/8565472-how-do-i-authenticate-to-access-the-rest-api">Tado Support
* Article</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc8628">RFC-8628</a>
*
* @author Andrew Fiddian-Green - Initial contribution
*/
public class OAuthorizerV2 implements Authorizer {

private final Logger logger = LoggerFactory.getLogger(OAuthorizerV2.class);

private final OAuthClientService oAuthService;

public OAuthorizerV2(OAuthClientService oAuthService) {
this.oAuthService = oAuthService;
}

@Override
public void addAuthorization(Request request) {
try {
AccessTokenResponse token = oAuthService.getAccessTokenResponse();
if (token != null) {
request.header(HttpHeader.AUTHORIZATION,
String.format("%s %s", token.getTokenType(), token.getAccessToken()));
return;
}
} catch (OAuthException | IOException | OAuthResponseException e) {
logger.debug("addAuthorization() => getAccessTokenResponse() error: {}", e.getMessage(), e);
}
}

public @Nullable DeviceCodeResponse getDeviceCodeResponse() throws OAuthException {

Check failure on line 62 in bundles/org.openhab.binding.tado/src/main/java/org/openhab/binding/tado/internal/auth/OAuthorizerV2.java

View workflow job for this annotation

GitHub Actions / Build (Java 21, ubuntu-24.04)

DeviceCodeResponse cannot be resolved to a type
return oAuthService.getDeviceCodeResponse();

Check failure on line 63 in bundles/org.openhab.binding.tado/src/main/java/org/openhab/binding/tado/internal/auth/OAuthorizerV2.java

View workflow job for this annotation

GitHub Actions / Build (Java 21, ubuntu-24.04)

The method getDeviceCodeResponse() is undefined for the type org.openhab.core.auth.client.oauth2.OAuthClientService
}

public @Nullable AccessTokenResponse getAccessTokenResponse()
throws OAuthException, IOException, OAuthResponseException {
return oAuthService.getAccessTokenResponse();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
package org.openhab.binding.tado.internal.config;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;

/**
* Holder-object for home configuration
Expand All @@ -21,6 +22,7 @@
*/
@NonNullByDefault
public class TadoHomeConfig {
public String username = "";
public String password = "";
public @Nullable String username;
public @Nullable String password;
public @Nullable Boolean useRfc8628;
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.tado.internal.discovery.TadoDiscoveryService;
import org.openhab.core.auth.client.oauth2.OAuthFactory;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Thing;
Expand All @@ -34,6 +35,7 @@
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.http.HttpService;

/**
* The {@link TadoHandlerFactory} is responsible for creating things and thing
Expand All @@ -51,10 +53,15 @@ public class TadoHandlerFactory extends BaseThingHandlerFactory {
private final Map<ThingUID, ServiceRegistration<?>> discoveryServiceRegs = new HashMap<>();

private final TadoStateDescriptionProvider stateDescriptionProvider;
private final HttpService httpService;
private final OAuthFactory oAuthFactory;

@Activate
public TadoHandlerFactory(final @Reference TadoStateDescriptionProvider stateDescriptionProvider) {
public TadoHandlerFactory(@Reference TadoStateDescriptionProvider stateDescriptionProvider,
@Reference HttpService httpService, @Reference OAuthFactory oAuthFactory) {
this.stateDescriptionProvider = stateDescriptionProvider;
this.httpService = httpService;
this.oAuthFactory = oAuthFactory;
}

@Override
Expand All @@ -67,7 +74,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();

if (thingTypeUID.equals(THING_TYPE_HOME)) {
TadoHomeHandler tadoHomeHandler = new TadoHomeHandler((Bridge) thing);
TadoHomeHandler tadoHomeHandler = new TadoHomeHandler((Bridge) thing, httpService, oAuthFactory);
registerTadoDiscoveryService(tadoHomeHandler);
return tadoHomeHandler;
} else if (thingTypeUID.equals(THING_TYPE_ZONE)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,21 @@
package org.openhab.binding.tado.internal.handler;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.tado.internal.TadoBindingConstants;
import org.openhab.binding.tado.internal.TadoBindingConstants.TemperatureUnit;
import org.openhab.binding.tado.internal.api.HomeApiFactory;
import org.openhab.binding.tado.internal.config.TadoHomeConfig;
import org.openhab.binding.tado.internal.servlet.TadoAuthenticationServlet;
import org.openhab.binding.tado.swagger.codegen.api.ApiException;
import org.openhab.binding.tado.swagger.codegen.api.client.HomeApi;
import org.openhab.binding.tado.swagger.codegen.api.model.HomeInfo;
Expand All @@ -31,6 +36,10 @@
import org.openhab.binding.tado.swagger.codegen.api.model.PresenceState;
import org.openhab.binding.tado.swagger.codegen.api.model.User;
import org.openhab.binding.tado.swagger.codegen.api.model.UserHomes;
import org.openhab.core.auth.client.oauth2.AccessTokenRefreshListener;
import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
import org.openhab.core.auth.client.oauth2.OAuthClientService;
import org.openhab.core.auth.client.oauth2.OAuthFactory;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.ChannelUID;
Expand All @@ -41,6 +50,8 @@
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -50,22 +61,37 @@
* @author Dennis Frommknecht - Initial contribution
*/
@NonNullByDefault
public class TadoHomeHandler extends BaseBridgeHandler {
public class TadoHomeHandler extends BaseBridgeHandler implements AccessTokenRefreshListener {

private Logger logger = LoggerFactory.getLogger(TadoHomeHandler.class);
private static final ZonedDateTime AUTH_V2_FROM_DATE = ZonedDateTime.parse("2025-03-15T00:00:00Z");

private TadoHomeConfig configuration;
private final HomeApi api;
private static final String DEVICE_URL = "https://login.tado.com/oauth2/device_authorize";
private static final String TOKEN_URL = "https://login.tado.com/oauth2/token";
private static final String CLIENT_ID = "1bb50063-6b0c-4d11-bd99-387f4a91cc46";
private static final String SCOPE = "offline_access";

private final Logger logger = LoggerFactory.getLogger(TadoHomeHandler.class);

private @Nullable Long homeId;
private final TadoBatteryChecker batteryChecker;
private final HttpService httpService;
private final TadoAuthenticationServlet httpServlet;
private final OAuthFactory oAuthFactory;

private @NonNullByDefault({}) TadoHomeConfig configuration;
private @NonNullByDefault({}) String offlinePrompt;
private @NonNullByDefault({}) HomeApi api;

private @Nullable Long homeId;
private @Nullable ScheduledFuture<?> initializationFuture;
private @Nullable OAuthClientService oAuthClientService;

public TadoHomeHandler(Bridge bridge) {
public TadoHomeHandler(Bridge bridge, HttpService httpService, OAuthFactory oAuthFactory) {
super(bridge);
batteryChecker = new TadoBatteryChecker(this);
configuration = getConfigAs(TadoHomeConfig.class);
api = new HomeApiFactory().create(configuration.username, configuration.password);
this.batteryChecker = new TadoBatteryChecker(this);
this.configuration = getConfigAs(TadoHomeConfig.class);
this.httpService = httpService;
this.httpServlet = new TadoAuthenticationServlet(this);
this.oAuthFactory = oAuthFactory;
}

public TemperatureUnit getTemperatureUnit() {
Expand All @@ -77,14 +103,50 @@ public TemperatureUnit getTemperatureUnit() {
@Override
public void initialize() {
configuration = getConfigAs(TadoHomeConfig.class);

String userName = configuration.username;
String password = configuration.password;
boolean v1CredentialsOk = userName != null && !userName.isBlank() && password != null && !password.isBlank();

boolean suggestRfc8628 = false;
suggestRfc8628 |= Boolean.TRUE.equals(configuration.useRfc8628);
suggestRfc8628 |= !v1CredentialsOk;
suggestRfc8628 |= ZonedDateTime.now().isAfter(AUTH_V2_FROM_DATE);

if (suggestRfc8628) {
String url = "http(s)://<YOUROPENHAB>:<YOURPORT>" + TadoAuthenticationServlet.PATH;
offlinePrompt = String.format("@text/tado.home.status.oauth [\"%s\"]", url);

OAuthClientService oAuthService = oAuthFactory.getOAuthClientService(thing.getUID().toString());
if (oAuthService == null) {
oAuthService = oAuthFactory.createOAuthClientService(thing.getUID().getAsString(), TOKEN_URL,
DEVICE_URL, CLIENT_ID, null, SCOPE, false);
}
oAuthService.addAccessTokenRefreshListener(this);
oAuthClientService = oAuthService;

api = new HomeApiFactory().create(oAuthService);
logger.trace("initialize() api v2 created");
} else {
offlinePrompt = "@text/tado.home.status.username";
api = new HomeApiFactory().create(Objects.requireNonNull(userName), Objects.requireNonNull(password));
logger.trace("initialize() api v1 created");
}

try {
httpService.registerServlet(TadoAuthenticationServlet.PATH, httpServlet, null, null);
} catch (ServletException | NamespaceException e) {
logger.warn("initialize() failed to register servlet", e);
}

ScheduledFuture<?> initializationFuture = this.initializationFuture;
if (initializationFuture == null || initializationFuture.isDone()) {
this.initializationFuture = scheduler.scheduleWithFixedDelay(
this::initializeBridgeStatusAndPropertiesIfOffline, 0, 300, TimeUnit.SECONDS);
}
}

private void initializeBridgeStatusAndPropertiesIfOffline() {
private synchronized void initializeBridgeStatusAndPropertiesIfOffline() {
if (getThing().getStatus() == ThingStatus.ONLINE) {
for (Thing thing : getThing().getThings()) {
ThingHandler handler = thing.getHandler();
Expand All @@ -101,21 +163,21 @@ private void initializeBridgeStatusAndPropertiesIfOffline() {
// Get user info to verify successful authentication and connection to server
User user = api.showUser();
if (user == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"Cannot connect to server. Username and/or password might be invalid");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING, offlinePrompt);
return;
}

List<UserHomes> homes = user.getHomes();
if (homes == null || homes.isEmpty()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"User does not have access to any home");
"@text/tado.home.status.nohome");
return;
}

Integer firstHomeId = homes.get(0).getId();
if (firstHomeId == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Missing Home Id");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"@text/tado.home.status.nohomeid");
return;
}

Expand All @@ -128,9 +190,8 @@ private void initializeBridgeStatusAndPropertiesIfOffline() {
.getTemperatureUnit() ? TemperatureUnit.FAHRENHEIT : TemperatureUnit.CELSIUS;
updateProperty(TadoBindingConstants.PROPERTY_HOME_TEMPERATURE_UNIT, temperatureUnit.name());
} catch (IOException | ApiException e) {
logger.debug("Error accessing tado server: {}", e.getMessage(), e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Could not connect to server due to " + e.getMessage());
logger.debug("Error accessing tado server: {}", e.getMessage());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING, offlinePrompt);
return;
}

Expand All @@ -140,6 +201,10 @@ private void initializeBridgeStatusAndPropertiesIfOffline() {
@Override
public void dispose() {
super.dispose();
OAuthClientService service = oAuthClientService;
if (service != null) {
service.removeAccessTokenRefreshListener(this);
}
ScheduledFuture<?> initializationFuture = this.initializationFuture;
if (initializationFuture != null && !initializationFuture.isCancelled()) {
initializationFuture.cancel(true);
Expand Down Expand Up @@ -195,4 +260,9 @@ public void handleCommand(ChannelUID channelUID, Command command) {
public TadoBatteryChecker getBatteryChecker() {
return this.batteryChecker;
}

@Override
public void onAccessTokenResponse(AccessTokenResponse atr) {
initializeBridgeStatusAndPropertiesIfOffline();
}
}
Loading
Loading