Skip to content

Commit

Permalink
With Test Cases and other changes
Browse files Browse the repository at this point in the history
  • Loading branch information
amanpras committed Sep 11, 2024
1 parent dcf60eb commit 7ffaece
Show file tree
Hide file tree
Showing 11 changed files with 464 additions and 98 deletions.
1 change: 1 addition & 0 deletions Ginger/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ csharp_style_prefer_extended_property_pattern = true:suggestion
csharp_style_var_for_built_in_types = true:none
csharp_style_var_when_type_is_apparent = true:none
csharp_style_var_elsewhere = true:none
csharp_indent_braces = false

[*.vb]
#### Naming styles ####
Expand Down
120 changes: 120 additions & 0 deletions Ginger/Ginger/ExternalConfigurations/GingerAnalyticsAPI.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
#region License
/*
Copyright © 2014-2024 European Support Limited
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion

using Ginger.Configurations;
using Amdocs.Ginger.Common;
using amdocs.ginger.GingerCoreNET;
using System.Net.Http;
using System.Threading.Tasks;
using System;
using IdentityModel.Client;
using System.IdentityModel.Tokens.Jwt;

namespace Ginger.ExternalConfigurations
{
public class GingerAnalyticsAPI

Check warning on line 30 in Ginger/Ginger/ExternalConfigurations/GingerAnalyticsAPI.cs

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

Ginger/Ginger/ExternalConfigurations/GingerAnalyticsAPI.cs#L30

Add a 'protected' constructor or the 'static' keyword to the class declaration.
{
public static DateTime validTo = DateTime.MinValue;

Check failure on line 32 in Ginger/Ginger/ExternalConfigurations/GingerAnalyticsAPI.cs

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

Ginger/Ginger/ExternalConfigurations/GingerAnalyticsAPI.cs#L32

Change the visibility of 'validTo' or make it 'const' or 'readonly'.
public static GingerAnalyticsConfiguration gingerAnalyticsUserConfig =

Check failure on line 33 in Ginger/Ginger/ExternalConfigurations/GingerAnalyticsAPI.cs

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

Ginger/Ginger/ExternalConfigurations/GingerAnalyticsAPI.cs#L33

Change the visibility of 'gingerAnalyticsUserConfig' or make it 'const' or 'readonly'.
WorkSpace.Instance.SolutionRepository.GetAllRepositoryItems<GingerAnalyticsConfiguration>().Count == 0 ? new GingerAnalyticsConfiguration() : WorkSpace.Instance.SolutionRepository.GetFirstRepositoryItem<GingerAnalyticsConfiguration>();


public static async Task<bool> RequestToken(string clientId, string clientSecret, string address)
{
try
{
HttpClientHandler handler = new HttpClientHandler() { UseProxy = false };

using (var client = new HttpClient(handler))
{

var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
{
Address = address,
Policy =
{
RequireHttps = true,
ValidateIssuerName = true
}
});

if (disco.IsError)
{
Reporter.ToLog(eLogLevel.ERROR, $"Discovery document error: {disco.Error}");
return false;
}

var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = clientId,
ClientSecret = clientSecret
});

if (tokenResponse.IsError)
{
Reporter.ToLog(eLogLevel.ERROR, $"Token request error: {tokenResponse.Error}");
return false;
}

validTo = DateTime.UtcNow.AddMinutes(60);
gingerAnalyticsUserConfig.Token = tokenResponse.AccessToken;
return true;
}
}
catch (HttpRequestException httpEx)
{
Reporter.ToLog(eLogLevel.ERROR, "HTTP request failed", httpEx);
return false;
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Unexpected error during token request", ex);
return false;
}
}

public static bool IsTokenValid()
{
try
{
if (string.IsNullOrEmpty(gingerAnalyticsUserConfig.Token) || gingerAnalyticsUserConfig.Token.Split('.').Length != 3)
{
return false;
}

var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(gingerAnalyticsUserConfig.Token);
validTo = jwtToken.ValidTo;
if (DateTime.UtcNow < validTo)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Error occured in validate token", ex);
return false;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
<Activities:UCValueExpression x:Name="xClientSecretTextBox" Grid.Column="1" Grid.Row="3" HorizontalAlignment="Left" VerticalAlignment="Center" ToolTip="Client Secret" Margin="10,0,0,0" Width="400" LostKeyboardFocus="xClientSecretTextBox_LostKeyboardFocus"/>
</Grid>
<Grid>
<Button x:Name="xTestConBtn" Click="xTestConBtn_Click" Content="Test Connection" Width="100" Background="White" Style="{StaticResource $InputButtonStyle}" Margin="10,15,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" />
<Button x:Name="xTestConBtn" IsEnabled="True" Click="xTestConBtn_Click" Content="Test Connection" Width="100" Background="White" Style="{StaticResource $InputButtonStyle}" Margin="10,15,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" />
<usercontrols:ImageMakerControl x:Name="xProcessingImage" ImageType="Processing" Margin="120,10,0,0" HorizontalAlignment="Left" Height="30" Width="20" Visibility="Hidden"></usercontrols:ImageMakerControl>

</Grid>
</StackPanel>
</Grid>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,16 @@ namespace Ginger.ExternalConfigurations
/// </summary>
public partial class GingerAnalyticsConfigurationPage : GingerUIPage
{
public DateTime validTo = DateTime.MinValue;
private GingerAnalyticsConfiguration gingerAnalyticsUserConfig = null;
public GingerAnalyticsConfiguration gingerAnalyticsUserConfig;
public GingerAnalyticsAPI analyticsAPI;
public GingerAnalyticsConfigurationPage()
{
InitializeComponent();
Init();
}
private void Init()
{
analyticsAPI = new GingerAnalyticsAPI();
gingerAnalyticsUserConfig = WorkSpace.Instance.SolutionRepository.GetAllRepositoryItems<GingerAnalyticsConfiguration>().Count == 0 ? new GingerAnalyticsConfiguration() : WorkSpace.Instance.SolutionRepository.GetFirstRepositoryItem<GingerAnalyticsConfiguration>();
gingerAnalyticsUserConfig.StartDirtyTracking();
SetControls();
Expand Down Expand Up @@ -77,43 +78,53 @@ private void ApplyValidationRules()

private async void xTestConBtn_Click(object sender, RoutedEventArgs e)
{
ShowLoader();
xTestConBtn.IsEnabled = false;
if (AreRequiredFieldsEmpty())
{
Reporter.ToUser(eUserMsgKey.RequiredFieldsEmpty);
HideLoader();
xTestConBtn.IsEnabled = true;
return;
}

GingerCoreNET.GeneralLib.General.CreateGingerAnalyticsConfiguration(gingerAnalyticsUserConfig);

if (IsTokenValid())
if (GingerAnalyticsAPI.IsTokenValid())
{
Reporter.ToUser(eUserMsgKey.GingerAnalyticsConnectionSuccess);
HideLoader();
xTestConBtn.IsEnabled = true;
return;
}

bool isAuthorized = await HandleTokenAuthorization();
ShowConnectionResult(isAuthorized);
HideLoader();
xTestConBtn.IsEnabled = true;
}

private bool AreRequiredFieldsEmpty()
public bool AreRequiredFieldsEmpty()
{
return string.IsNullOrEmpty(gingerAnalyticsUserConfig.AccountUrl)
|| string.IsNullOrEmpty(gingerAnalyticsUserConfig.IdentityServiceURL)
|| string.IsNullOrEmpty(gingerAnalyticsUserConfig.ClientId)
|| string.IsNullOrEmpty(gingerAnalyticsUserConfig.ClientSecret);
}

private async Task<bool> HandleTokenAuthorization()
public async Task<bool> HandleTokenAuthorization()
{
if (string.IsNullOrEmpty(gingerAnalyticsUserConfig.Token))
{
return await RequestToken(gingerAnalyticsUserConfig.ClientId, gingerAnalyticsUserConfig.ClientSecret, gingerAnalyticsUserConfig.IdentityServiceURL);
return await GingerAnalyticsAPI.RequestToken(ValueExpression.PasswordCalculation(gingerAnalyticsUserConfig.ClientId),
ValueExpression.PasswordCalculation(gingerAnalyticsUserConfig.ClientSecret),
ValueExpression.PasswordCalculation(gingerAnalyticsUserConfig.IdentityServiceURL));
}

return true;
}

private static void ShowConnectionResult(bool isAuthorized)
public static void ShowConnectionResult(bool isAuthorized)
{
if (isAuthorized)
{
Expand Down Expand Up @@ -145,90 +156,22 @@ private void xClientIdTextBox_LostKeyboardFocus(object sender, System.Windows.In
}


public async Task<bool> RequestToken(string clientId, string clientSecret, string address)


public void HideLoader()
{
try
{
HttpClientHandler handler = new HttpClientHandler() { UseProxy = false};

using (var client = new HttpClient(handler))
{
clientId = ValueExpression.CredentialsCalculation(gingerAnalyticsUserConfig.ClientId);
clientSecret = ValueExpression.CredentialsCalculation(gingerAnalyticsUserConfig.ClientSecret);
address = ValueExpression.CredentialsCalculation(gingerAnalyticsUserConfig.IdentityServiceURL);

var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
{
Address = address,
Policy =
{
RequireHttps = true,
ValidateIssuerName = true
}
});

if (disco.IsError)
{
Reporter.ToLog(eLogLevel.ERROR, $"Discovery document error: {disco.Error}");
return false;
}

var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = clientId,
ClientSecret = clientSecret
});

if (tokenResponse.IsError)
{
Reporter.ToLog(eLogLevel.ERROR, $"Token request error: {tokenResponse.Error}");
return false;
}

validTo = DateTime.UtcNow.AddMinutes(60);
gingerAnalyticsUserConfig.Token = tokenResponse.AccessToken;
return true;
}
}
catch (HttpRequestException httpEx)
{
Reporter.ToLog(eLogLevel.ERROR, "HTTP request failed", httpEx);
return false;
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Unexpected error during token request", ex);
return false;
}
this.Dispatcher.Invoke(() =>
{
xProcessingImage.Visibility = Visibility.Hidden;
});
}

public bool IsTokenValid()
public void ShowLoader()
{
try
{
if (string.IsNullOrEmpty(gingerAnalyticsUserConfig.Token) || gingerAnalyticsUserConfig.Token.Split('.').Length != 3)
{
return false;
}

var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(gingerAnalyticsUserConfig.Token);
validTo = jwtToken.ValidTo;
if (DateTime.UtcNow < validTo)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Error occured in validate token", ex);
return false;
}
this.Dispatcher.Invoke(() =>
{
xProcessingImage.Visibility = Visibility.Visible;
});
}
}
}
9 changes: 9 additions & 0 deletions Ginger/Ginger/MenusLib/ConfigurationsMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ private static TwoLevelMenu GetMenu()
externalConfigMenu.Add(eImageType.GingerAnalytics, "Ginger Analytics Configuration", GetGingerAnalyticsPage, ConsoleKey.X, "Ginger Analytics Configuration", "Ginger Analytics Configuration AID");
twoLevelMenu.Add(externalConfigMenu);

TopMenuItem accessiblityRulesMenu = new TopMenuItem(eImageType.Accessibility, $"{GingerCore.General.GetEnumValueDescription(typeof(eTermResKey), nameof(eTermResKey.AccessibilityRules))}", ConsoleKey.T, $"{GingerCore.General.GetEnumValueDescription(typeof(eTermResKey), nameof(eTermResKey.AccessibilityRules))}", "Name & rules of the Accessibility which been present current json");
accessiblityRulesMenu.Add(eImageType.Application, "", GetAccessibilityRulePage, ConsoleKey.T, "", "AID");
twoLevelMenu.Add(accessiblityRulesMenu);

return twoLevelMenu;
}

Expand Down Expand Up @@ -162,5 +166,10 @@ private static Page OthersPage()
{
return new Page();
}

private static Page GetAccessibilityRulePage()
{
return (new AccessibilityRulePage());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static SolutionRepository CreateGingerSolutionRepository()
SR.AddItemInfo<RemoteServiceGrid>("*.Ginger.RemoteServiceGrid.xml", SolutionRepository.cSolutionRootFolderSign + "RemoteServiceGrid", true, "RemoteServiceGrid", PropertyNameForFileName: nameof(RemoteServiceGrid.Name));

SR.AddItemInfo<AccessibilityConfiguration>("*.Ginger.Configuration.xml", SolutionRepository.cSolutionRootFolderSign + "Configurations", true, "AccessibilityConfiguration", PropertyNameForFileName: nameof(AccessibilityConfiguration.Name));
SR.AddItemInfo<GingerAnalyticsConfiguration>("*.Ginger.GingerAnalyticsConfiguration.xml", SolutionRepository.cSolutionRootFolderSign + "GingerAnalyticsConfiguration", true, "GingerAnalyticsConfiguration", PropertyNameForFileName: nameof(GingerAnalyticsConfiguration.Name));
SR.AddItemInfo<GingerAnalyticsConfiguration>("*.Ginger.Configuration.xml", SolutionRepository.cSolutionRootFolderSign + "Configurations", true, "GingerAnalyticsConfiguration", PropertyNameForFileName: nameof(GingerAnalyticsConfiguration.Name));


return SR;
Expand Down
24 changes: 15 additions & 9 deletions Ginger/GingerCoreNET/ValueExpressionLib/ValueExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1865,22 +1865,28 @@ public static string Calculate(ProjEnvironment ProjEnvironment, BusinessFlow Bus
/// </summary>
/// <param name="value">The input string which might be a value expression or an encrypted string.</param>
/// <returns>The calculated or decrypted value, or the input string if no processing is needed.</returns>
public static string CredentialsCalculation(string value)
public static string PasswordCalculation(string value)
{
try
{
if (IsThisAValueExpression(value))
{
ValueExpression valueExpression = new();
valueExpression.DecryptFlag = true;
value = valueExpression.Calculate(value);
valueExpression.DecryptFlag = false;
return value;
ValueExpression valueExpression = new();
valueExpression.DecryptFlag = true;
value = valueExpression.Calculate(value);
valueExpression.DecryptFlag = false;
return value;
}
else if (EncryptionHandler.IsStringEncrypted(value))
{
value = EncryptionHandler.DecryptwithKey(value);
return value;
value = EncryptionHandler.DecryptwithKey(value);
return value;
}
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR,"Unable to decrypt the value expression", ex);
}

return value;
}
}
Expand Down
Loading

0 comments on commit 7ffaece

Please sign in to comment.