Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(BackendApiService): request additional user scopes #1695

Merged
merged 5 commits into from
Dec 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void CanEnCodeCorrectUrl()
State = "8774fbe7-f9aa-4e36-8e88-5c8b27137f20",
};
var url = backendApiService.GenerateAuthUrl(requestInformation, "en-US");
var expectedUrl = "https://auth.tesla.com/oauth2/v3/authorize?&client_id=f29f71d6285a-4873-8b6b-80f15854892e&locale=en-US&prompt=login&redirect_uri=https%3A%2F%2Fwww.teslasolarcharger.de%2F&response_type=code&scope=offline_access%20vehicle_device_data%20vehicle_cmds%20vehicle_charging_cmds&state=8774fbe7-f9aa-4e36-8e88-5c8b27137f20";
var expectedUrl = "https://auth.tesla.com/oauth2/v3/authorize?&client_id=f29f71d6285a-4873-8b6b-80f15854892e&locale=en-US&prompt=login&redirect_uri=https%3A%2F%2Fwww.teslasolarcharger.de%2F&response_type=code&scope=offline_access%20vehicle_device_data%20vehicle_cmds%20vehicle_charging_cmds&state=8774fbe7-f9aa-4e36-8e88-5c8b27137f20&prompt_missing_scopes=true";
Assert.Equal(expectedUrl, url);
}
}
2 changes: 1 addition & 1 deletion TeslaSolarCharger/Server/Services/BackendApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ internal string GenerateAuthUrl(DtoTeslaOAuthRequestInformation oAuthInformation
{
logger.LogTrace("{method}({@oAuthInformation})", nameof(GenerateAuthUrl), oAuthInformation);
var url =
$"https://auth.tesla.com/oauth2/v3/authorize?&client_id={Uri.EscapeDataString(oAuthInformation.ClientId)}&locale={Uri.EscapeDataString(locale)}&prompt={Uri.EscapeDataString(oAuthInformation.Prompt)}&redirect_uri={Uri.EscapeDataString(oAuthInformation.RedirectUri)}&response_type={Uri.EscapeDataString(oAuthInformation.ResponseType)}&scope={Uri.EscapeDataString(oAuthInformation.Scope)}&state={Uri.EscapeDataString(oAuthInformation.State)}";
$"https://auth.tesla.com/oauth2/v3/authorize?&client_id={Uri.EscapeDataString(oAuthInformation.ClientId)}&locale={Uri.EscapeDataString(locale)}&prompt={Uri.EscapeDataString(oAuthInformation.Prompt)}&redirect_uri={Uri.EscapeDataString(oAuthInformation.RedirectUri)}&response_type={Uri.EscapeDataString(oAuthInformation.ResponseType)}&scope={Uri.EscapeDataString(oAuthInformation.Scope)}&state={Uri.EscapeDataString(oAuthInformation.State)}&prompt_missing_scopes=true";
return url;
}

Expand Down
4 changes: 2 additions & 2 deletions TeslaSolarCharger/Server/Services/ErrorHandlingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ await AddOrRemoveErrors(activeErrors, issueKeys.FleetApiTokenUnauthorized, "Flee
"You recently changed your password or did not enable mobile access in your car. Enable mobile access in your car and open the <a href=\"/BaseConfiguration\">Base Configuration</a> and request a new token. Important: You need to allow access to all selectable scopes.",
tokenState == FleetApiTokenState.TokenUnauthorized).ConfigureAwait(false);
await AddOrRemoveErrors(activeErrors, issueKeys.FleetApiTokenMissingScopes, "Your Tesla token has missing scopes.",
"Remove Tesla Solar Charger from your <a href=\"https://accounts.tesla.com/account-settings/security?tab=tpty-apps\" target=\"_blank\">third party apps</a> as you won't get asked again for the scopes. After that request a new token in the <a href=\"/BaseConfiguration\">Base Configuration</a> and select all available scopes.",
"Open the <a href=\"/BaseConfiguration\">Base Configuration</a> and request a new token. Note: You need to allow all selectable scopes as otherwise TSC won't work properly.",
tokenState == FleetApiTokenState.MissingScopes).ConfigureAwait(false);
await AddOrRemoveErrors(activeErrors, issueKeys.FleetApiTokenRequestExpired, "Tesla Token could not be received",
"Open the <a href=\"/BaseConfiguration\">Base Configuration</a> and request a new token.",
Expand Down Expand Up @@ -479,7 +479,7 @@ private async Task AddOrRemoveErrors(List<LoggedError> activeErrors, string issu
}
else if (shouldBeActive)
{
for (var i = 0; i < activeErrors.Count; i++)
for (var i = 0; i < filteredErrors.Count; i++)
{
if (i == 0)
{
Expand Down
14 changes: 8 additions & 6 deletions TeslaSolarCharger/Server/Services/TeslaFleetApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1169,18 +1169,13 @@ public async Task RefreshTokensIfAllowedAndNeeded()
logger.LogError("No token found. Cannot refresh token.");
return;
}

var tokensToRefresh = tokens.Where(t => t.ExpiresAtUtc < (dateTimeProvider.UtcNow() + TimeSpan.FromMinutes(2))).ToList();
if (tokensToRefresh.Count < 1)
{
logger.LogTrace("No token needs to be refreshed.");
return;
}
//ToDo: needs to handle manual generated tokens. For now as soon as rate limits are introduced nobody gets refresh tokens even if they have a token not from www.teslasolarcharger.de
if (settings.AllowUnlimitedFleetApiRequests == false)
{
logger.LogError("Due to rate limitations fleet api requests are not allowed. As this version can not handle rate limits try updating to the latest version.");
return;
}

foreach (var tokenToRefresh in tokensToRefresh)
{
Expand Down Expand Up @@ -1217,6 +1212,13 @@ await errorHandlingService.HandleError(nameof(TeslaFleetApiService), nameof(Send
await HandleNonSuccessTeslaApiStatusCodes(response.StatusCode, tokenToRefresh, responseString, TeslaApiRequestType.Other).ConfigureAwait(false);
}
response.EnsureSuccessStatusCode();
if (settings.AllowUnlimitedFleetApiRequests == false)
{
logger.LogError("Due to rate limitations fleet api requests are not allowed. As this version can not handle rate limits try updating to the latest version.");
teslaSolarChargerContext.TeslaTokens.Remove(tokenToRefresh);
await teslaSolarChargerContext.SaveChangesAsync().ConfigureAwait(false);
return;
}
var newToken = JsonConvert.DeserializeObject<DtoTeslaFleetApiRefreshToken>(responseString) ?? throw new InvalidDataException("Could not get token from string.");
tokenToRefresh.AccessToken = newToken.AccessToken;
tokenToRefresh.RefreshToken = newToken.RefreshToken;
Expand Down
Loading