Search in sources :

Example 46 with OAuthClientService

use of org.openhab.core.auth.client.oauth2.OAuthClientService in project openhab-addons by openhab.

the class EcobeeAuth method getTokens.

/**
 * Call the Ecobee token endpoint to get the access and refresh tokens. Once successfully retrieved,
 * the access and refresh tokens will be injected into the OHC OAuth service.
 * Warnings are suppressed to avoid the Gson.fromJson warnings.
 */
@SuppressWarnings({ "null", "unused" })
private void getTokens() throws EcobeeAuthException {
    logger.debug("EcobeeAuth: State is {}: Executing step: 'getToken'", state);
    StringBuilder url = new StringBuilder(ECOBEE_TOKEN_URL);
    url.append("?grant_type=ecobeePin");
    url.append("&code=").append(code);
    url.append("&client_id=").append(apiKey);
    logger.trace("EcobeeAuth: Posting token URL={}", url);
    String response = executeUrl("POST", url.toString());
    logger.trace("EcobeeAuth: Got a valid token response: {}", response);
    TokenResponseDTO tokenResponse = EcobeeApi.getGson().fromJson(response, TokenResponseDTO.class);
    if (tokenResponse == null) {
        logger.debug("EcobeeAuth: Got null token response from Ecobee API");
        updateBridgeStatus();
        setState(isPinExpired() ? EcobeeAuthState.NEED_PIN : EcobeeAuthState.NEED_TOKEN);
        return;
    }
    String error = tokenResponse.error;
    if (error != null && !error.isEmpty()) {
        throw new EcobeeAuthException(error + ": " + tokenResponse.errorDescription);
    }
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    accessTokenResponse.setRefreshToken(tokenResponse.refreshToken);
    accessTokenResponse.setAccessToken(tokenResponse.accessToken);
    accessTokenResponse.setScope(tokenResponse.scope);
    accessTokenResponse.setTokenType(tokenResponse.tokenType);
    accessTokenResponse.setExpiresIn(tokenResponse.expiresIn);
    try {
        logger.debug("EcobeeAuth: Importing AccessTokenResponse into oAuthClientService!!!");
        oAuthClientService.importAccessTokenResponse(accessTokenResponse);
        bridgeHandler.updateBridgeStatus(ThingStatus.ONLINE);
        setState(EcobeeAuthState.COMPLETE);
        return;
    } catch (OAuthException e) {
        logger.info("EcobeeAuth: Got OAuthException", e);
    // No other processing needed here
    }
    updateBridgeStatus();
    setState(isPinExpired() ? EcobeeAuthState.NEED_PIN : EcobeeAuthState.NEED_TOKEN);
}
Also used : TokenResponseDTO(org.openhab.binding.ecobee.internal.dto.oauth.TokenResponseDTO) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 47 with OAuthClientService

use of org.openhab.core.auth.client.oauth2.OAuthClientService in project openhab-addons by openhab.

the class GoogleCloudAPI method setConfig.

/**
 * Configuration update.
 *
 * @param config New configuration.
 */
void setConfig(GoogleTTSConfig config) {
    this.config = config;
    String clientId = config.clientId;
    String clientSecret = config.clientSecret;
    if (clientId != null && !clientId.isEmpty() && clientSecret != null && !clientSecret.isEmpty()) {
        try {
            final OAuthClientService oAuthService = oAuthFactory.createOAuthClientService(GoogleTTSService.SERVICE_PID, GCP_TOKEN_URI, GCP_AUTH_URI, clientId, clientSecret, GCP_SCOPE, false);
            this.oAuthService = oAuthService;
            getAccessToken();
            initialized = true;
            initVoices();
        } catch (AuthenticationException | CommunicationException e) {
            logger.warn("Error initializing Google Cloud TTS service: {}", e.getMessage());
            oAuthService = null;
            initialized = false;
            voices.clear();
        }
    } else {
        oAuthService = null;
        initialized = false;
        voices.clear();
    }
    // maintain cache
    if (config.purgeCache) {
        File[] files = cacheFolder.listFiles();
        if (files != null && files.length > 0) {
            Arrays.stream(files).forEach(File::delete);
        }
        logger.debug("Cache purged.");
    }
}
Also used : CommunicationException(org.openhab.core.i18n.CommunicationException) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) AuthenticationException(org.openhab.core.auth.AuthenticationException) File(java.io.File)

Example 48 with OAuthClientService

use of org.openhab.core.auth.client.oauth2.OAuthClientService in project openhab-addons by openhab.

the class AbstractMieleThingHandlerTest method setUpBridge.

private void setUpBridge() throws Exception {
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    accessTokenResponse.setAccessToken(ACCESS_TOKEN);
    OAuthClientService oAuthClientService = mock(OAuthClientService.class);
    when(oAuthClientService.getAccessTokenResponse()).thenReturn(accessTokenResponse);
    OAuthFactory oAuthFactory = mock(OAuthFactory.class);
    when(oAuthFactory.getOAuthClientService(MieleCloudBindingIntegrationTestConstants.BRIDGE_THING_UID.getAsString())).thenReturn(oAuthClientService);
    OpenHabOAuthTokenRefresher tokenRefresher = getService(OAuthTokenRefresher.class, OpenHabOAuthTokenRefresher.class);
    assertNotNull(tokenRefresher);
    setPrivate(Objects.requireNonNull(tokenRefresher), "oauthFactory", oAuthFactory);
    bridge = BridgeBuilder.create(MieleCloudBindingConstants.THING_TYPE_BRIDGE, MieleCloudBindingIntegrationTestConstants.BRIDGE_THING_UID).withLabel("Miele@home Account").withConfiguration(new Configuration(Collections.singletonMap(MieleCloudBindingConstants.CONFIG_PARAM_EMAIL, MieleCloudBindingIntegrationTestConstants.EMAIL))).build();
    assertNotNull(bridge);
    getThingRegistry().add(getBridge());
    // then:
    waitForAssert(() -> {
        assertNotNull(getBridge().getHandler());
        assertTrue(getBridge().getHandler() instanceof MieleBridgeHandler, "Handler type is wrong");
    });
    MieleBridgeHandler bridgeHandler = (MieleBridgeHandler) getBridge().getHandler();
    assertNotNull(bridgeHandler);
    waitForAssert(() -> {
        assertNotNull(bridgeHandler.getThing());
    });
    bridgeHandler.initialize();
    bridgeHandler.onConnectionAlive();
    setPrivate(bridgeHandler, "discoveryService", null);
    this.bridgeHandler = bridgeHandler;
}
Also used : Configuration(org.openhab.core.config.core.Configuration) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) OpenHabOAuthTokenRefresher(org.openhab.binding.mielecloud.internal.auth.OpenHabOAuthTokenRefresher) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Aggregations

OAuthClientService (org.openhab.core.auth.client.oauth2.OAuthClientService)36 OAuthFactory (org.openhab.core.auth.client.oauth2.OAuthFactory)15 AccessTokenResponse (org.openhab.core.auth.client.oauth2.AccessTokenResponse)12 IOException (java.io.IOException)10 Test (org.junit.jupiter.api.Test)10 OAuthResponseException (org.openhab.core.auth.client.oauth2.OAuthResponseException)10 Nullable (org.eclipse.jdt.annotation.Nullable)8 OAuthException (org.openhab.core.auth.client.oauth2.OAuthException)7 OAuthClientService (org.eclipse.smarthome.core.auth.client.oauth2.OAuthClientService)6 AuthorizationException (org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException)4 CommunicationException (org.openhab.binding.homeconnect.internal.client.exception.CommunicationException)4 List (java.util.List)3 Map (java.util.Map)3 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3 ZonedDateTime (java.time.ZonedDateTime)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2