]> git.basschouten.com Git - openhab-addons.git/blob
6d7602a01c80a6f765dde0640991d1485dc272ef
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.util.concurrent.ExecutionException;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.TimeoutException;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.eclipse.jetty.client.HttpClient;
25 import org.eclipse.jetty.client.api.ContentResponse;
26 import org.eclipse.jetty.client.util.StringContentProvider;
27 import org.eclipse.jetty.http.HttpHeader;
28 import org.eclipse.jetty.http.HttpMethod;
29 import org.openhab.binding.tesla.internal.protocol.sso.RefreshTokenRequest;
30 import org.openhab.binding.tesla.internal.protocol.sso.TokenResponse;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import com.google.gson.Gson;
35
36 /**
37  * The {@link TeslaSSOHandler} is responsible for authenticating with the Tesla SSO service.
38  *
39  * @author Christian Güdel - Initial contribution
40  */
41 @NonNullByDefault
42 public class TeslaSSOHandler {
43
44     private final HttpClient httpClient;
45     private final Gson gson = new Gson();
46     private final Logger logger = LoggerFactory.getLogger(TeslaSSOHandler.class);
47
48     public TeslaSSOHandler(HttpClient httpClient) {
49         this.httpClient = httpClient;
50     }
51
52     @Nullable
53     public TokenResponse getAccessToken(String refreshToken) {
54         logger.debug("Exchanging SSO refresh token for API access token");
55
56         // get a new access token for the owner API token endpoint
57         RefreshTokenRequest refreshRequest = new RefreshTokenRequest(refreshToken);
58         String refreshTokenPayload = gson.toJson(refreshRequest);
59
60         final org.eclipse.jetty.client.api.Request request = httpClient.newRequest(URI_SSO + "/" + PATH_TOKEN);
61         request.content(new StringContentProvider(refreshTokenPayload));
62         request.header(HttpHeader.CONTENT_TYPE, "application/json");
63         request.method(HttpMethod.POST);
64
65         ContentResponse refreshResponse = executeHttpRequest(request);
66
67         if (refreshResponse != null && refreshResponse.getStatus() == 200) {
68             String refreshTokenResponse = refreshResponse.getContentAsString();
69             TokenResponse tokenResponse = gson.fromJson(refreshTokenResponse.trim(), TokenResponse.class);
70
71             if (tokenResponse != null && tokenResponse.access_token != null && !tokenResponse.access_token.isEmpty()) {
72                 tokenResponse.created_at = Instant.now().getEpochSecond();
73                 return tokenResponse;
74             } else {
75                 logger.debug("An error occurred while exchanging SSO auth token for API access token.");
76             }
77         } else {
78             logger.debug("An error occurred during refresh of SSO token: {}",
79                     (refreshResponse != null ? refreshResponse.getStatus() : "no response"));
80         }
81
82         return null;
83     }
84
85     @Nullable
86     private ContentResponse executeHttpRequest(org.eclipse.jetty.client.api.Request request) {
87         request.timeout(10, TimeUnit.SECONDS);
88
89         ContentResponse response;
90         try {
91             response = request.send();
92             return response;
93         } catch (InterruptedException | TimeoutException | ExecutionException e) {
94             logger.debug("An exception occurred while invoking a HTTP request: '{}'", e.getMessage());
95             return null;
96         }
97     }
98 }