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.tesla.internal.handler;
15 import static org.openhab.binding.tesla.internal.TeslaBindingConstants.*;
17 import java.time.Instant;
18 import java.time.ZoneId;
19 import java.time.format.DateTimeFormatter;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.eclipse.jetty.client.api.ContentResponse;
28 import org.eclipse.jetty.client.util.StringContentProvider;
29 import org.eclipse.jetty.http.HttpHeader;
30 import org.eclipse.jetty.http.HttpMethod;
31 import org.openhab.binding.tesla.internal.protocol.sso.RefreshTokenRequest;
32 import org.openhab.binding.tesla.internal.protocol.sso.TokenResponse;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
36 import com.google.gson.Gson;
39 * The {@link TeslaSSOHandler} is responsible for authenticating with the Tesla SSO service.
41 * @author Christian Güdel - Initial contribution
44 public class TeslaSSOHandler {
46 private final HttpClient httpClient;
47 private final Gson gson = new Gson();
48 private final Logger logger = LoggerFactory.getLogger(TeslaSSOHandler.class);
49 private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
50 .withZone(ZoneId.systemDefault());
52 public TeslaSSOHandler(HttpClient httpClient) {
53 this.httpClient = httpClient;
57 public TokenResponse getAccessToken(String refreshToken) {
58 logger.debug("Exchanging SSO refresh token for API access token");
60 // get a new access token for the owner API token endpoint
61 RefreshTokenRequest refreshRequest = new RefreshTokenRequest(refreshToken);
62 String refreshTokenPayload = gson.toJson(refreshRequest);
64 final org.eclipse.jetty.client.api.Request request = httpClient.newRequest(URI_SSO + "/" + PATH_TOKEN);
65 request.content(new StringContentProvider(refreshTokenPayload));
66 request.header(HttpHeader.CONTENT_TYPE, "application/json");
67 request.method(HttpMethod.POST);
69 ContentResponse refreshResponse = executeHttpRequest(request);
71 if (refreshResponse != null && refreshResponse.getStatus() == 200) {
72 String refreshTokenResponse = refreshResponse.getContentAsString();
73 TokenResponse tokenResponse = gson.fromJson(refreshTokenResponse.trim(), TokenResponse.class);
75 if (tokenResponse != null && tokenResponse.access_token != null && !tokenResponse.access_token.isEmpty()) {
76 tokenResponse.created_at = Instant.now().getEpochSecond();
77 logger.debug("Access token expires in {} seconds at {}", tokenResponse.expires_in, DATE_FORMATTER
78 .format(Instant.ofEpochMilli((tokenResponse.created_at + tokenResponse.expires_in) * 1000)));
81 logger.debug("An error occurred while exchanging SSO auth token for API access token.");
84 logger.debug("An error occurred during refresh of SSO token: {}",
85 (refreshResponse != null ? refreshResponse.getStatus() : "no response"));
92 private ContentResponse executeHttpRequest(org.eclipse.jetty.client.api.Request request) {
93 request.timeout(10, TimeUnit.SECONDS);
95 ContentResponse response;
97 response = request.send();
99 } catch (InterruptedException | TimeoutException | ExecutionException e) {
100 logger.debug("An exception occurred while invoking a HTTP request: '{}'", e.getMessage());