]> git.basschouten.com Git - openhab-addons.git/blob
f308f7ef80bf96e965d5c2548064d3bdb64a4ed9
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.tesla.internal.handler;
14
15 import static org.openhab.binding.tesla.internal.TeslaBindingConstants.*;
16
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;
23
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;
35
36 import com.google.gson.Gson;
37
38 /**
39  * The {@link TeslaSSOHandler} is responsible for authenticating with the Tesla SSO service.
40  *
41  * @author Christian Güdel - Initial contribution
42  */
43 @NonNullByDefault
44 public class TeslaSSOHandler {
45
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());
51
52     public TeslaSSOHandler(HttpClient httpClient) {
53         this.httpClient = httpClient;
54     }
55
56     @Nullable
57     public TokenResponse getAccessToken(String refreshToken) {
58         logger.debug("Exchanging SSO refresh token for API access token");
59
60         // get a new access token for the owner API token endpoint
61         RefreshTokenRequest refreshRequest = new RefreshTokenRequest(refreshToken);
62         String refreshTokenPayload = gson.toJson(refreshRequest);
63
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);
68
69         ContentResponse refreshResponse = executeHttpRequest(request);
70
71         if (refreshResponse != null && refreshResponse.getStatus() == 200) {
72             String refreshTokenResponse = refreshResponse.getContentAsString();
73             TokenResponse tokenResponse = gson.fromJson(refreshTokenResponse.trim(), TokenResponse.class);
74
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)));
79                 return tokenResponse;
80             } else {
81                 logger.debug("An error occurred while exchanging SSO auth token for API access token.");
82             }
83         } else {
84             logger.debug("An error occurred during refresh of SSO token: {}",
85                     (refreshResponse != null ? refreshResponse.getStatus() : "no response"));
86         }
87
88         return null;
89     }
90
91     @Nullable
92     private ContentResponse executeHttpRequest(org.eclipse.jetty.client.api.Request request) {
93         request.timeout(10, TimeUnit.SECONDS);
94
95         ContentResponse response;
96         try {
97             response = request.send();
98             return response;
99         } catch (InterruptedException | TimeoutException | ExecutionException e) {
100             logger.debug("An exception occurred while invoking a HTTP request: '{}'", e.getMessage());
101             return null;
102         }
103     }
104 }