Skip to content

Commit

Permalink
fix: user from seeing that they are signed in when they are signed out
Browse files Browse the repository at this point in the history
  • Loading branch information
cricketthomas committed Jul 27, 2024
1 parent 41fba14 commit 9451510
Show file tree
Hide file tree
Showing 11 changed files with 142 additions and 141 deletions.
29 changes: 25 additions & 4 deletions KeyVaultExplorer/Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -17,6 +18,8 @@ public class AuthService
// Providing the RedirectionUri to receive the token based on success or failure.
public bool IsAuthenticated { get; private set; } = false;

public AuthenticatedUserClaims AuthenticatedUserClaims { get; private set; }

public string TenantName { get; private set; }

public IAccount Account { get; private set; }
Expand All @@ -34,7 +37,7 @@ public AuthService()
public async Task<AuthenticationResult> LoginAsync(CancellationToken cancellationToken)
{
await AttachTokenCache();
AuthenticationResult result;
AuthenticationResult authenticationResult;
try
{
var options = new SystemWebViewOptions()
Expand All @@ -47,7 +50,7 @@ public async Task<AuthenticationResult> LoginAsync(CancellationToken cancellatio
//.WithUseEmbeddedWebView(false)
//.WithSystemWebViewOptions(options)
//#endif
result = await authenticationClient.AcquireTokenInteractive(Constants.Scopes)
authenticationResult = await authenticationClient.AcquireTokenInteractive(Constants.Scopes)
//.WithExtraScopesToConsent(Constants.AzureRMScope)
/*
* Not including extra scopes allows personal accounts to sign in, however, this will be thrown.
Expand All @@ -60,11 +63,19 @@ public async Task<AuthenticationResult> LoginAsync(CancellationToken cancellatio
.ExecuteAsync(cancellationToken);

IsAuthenticated = true;
TenantName = result.Account.Username.Split("@").TakeLast(1).Single();
TenantName = authenticationResult.Account.Username.Split("@").TakeLast(1).Single();
AuthenticatedUserClaims = new AuthenticatedUserClaims()
{
Username = authenticationResult.Account.Username,
TenantId = authenticationResult.TenantId,
Name = authenticationResult.ClaimsPrincipal.Identities.First().FindFirst("name").Value,
Email = authenticationResult.ClaimsPrincipal.Identities.First().FindFirst("preferred_username").Value
};

// set the preferences/settings of the signed in account
//IAccount cachedUserAccount = Task.Run(async () => await PublicClientSingleton.Instance.MSALClientHelper.FetchSignedInUserFromCache()).Result;
//Preferences.Default.Set("auth_account_id", JsonSerializer.Serialize(result.UniqueId));
return result;
return authenticationResult;
}
catch (MsalClientException ex)
{
Expand All @@ -90,6 +101,14 @@ public async Task<AuthenticationResult> RefreshTokenAsync(CancellationToken canc
authenticationResult = await authenticationClient.AcquireTokenSilent(Constants.Scopes, accounts.FirstOrDefault()).WithForceRefresh(true).ExecuteAsync();
IsAuthenticated = true;
TenantName = Account.Username.Split("@").TakeLast(1).Single();
AuthenticatedUserClaims = new AuthenticatedUserClaims()
{
Username = authenticationResult.Account.Username,
TenantId = authenticationResult.TenantId,
Name = authenticationResult.ClaimsPrincipal.Identities.First().FindFirst("name").Value,
Email = authenticationResult.ClaimsPrincipal.Identities.First().FindFirst("preferred_username").Value
};

return authenticationResult;
}

Expand Down Expand Up @@ -122,6 +141,8 @@ public async Task RemoveAccount()
await AttachTokenCache();
var accounts = await authenticationClient.GetAccountsAsync();
Account = null;
IsAuthenticated = false;
AuthenticatedUserClaims = null;
await authenticationClient.RemoveAsync(accounts.FirstOrDefault());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,6 @@ public CreateNewSecretVersionViewModel()
_authService = Defaults.Locator.GetRequiredService<AuthService>();
_vaultService = Defaults.Locator.GetRequiredService<VaultService>();
_notificationViewModel = Defaults.Locator.GetRequiredService<NotificationViewModel>();
if (Subscriptions is null || Subscriptions.Count == 0)
{
Dispatcher.UIThread.InvokeAsync(async () =>
{
Subscriptions = await GetAvailableSubscriptions();
}, DispatcherPriority.Input);
}

}

public bool HasActivationDate => KeyVaultSecretModel is not null && KeyVaultSecretModel.NotBefore.HasValue;
Expand Down
4 changes: 3 additions & 1 deletion KeyVaultExplorer/ViewModels/KeyVaultTreeListViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Avalonia.Threading;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.KeyVault;
Expand Down
29 changes: 11 additions & 18 deletions KeyVaultExplorer/ViewModels/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ namespace KeyVaultExplorer.ViewModels;

public partial class MainViewModel : ViewModelBase
{
[ObservableProperty]
private string email;

[ObservableProperty]
private AuthenticatedUserClaims authenticatedUserClaims;

Expand All @@ -28,13 +25,18 @@ public partial class MainViewModel : ViewModelBase

public NavigationFactory NavigationFactory { get; }


partial void OnIsAuthenticatedChanged(bool value)
{
AuthenticatedUserClaims = _authService.AuthenticatedUserClaims;
}

public MainViewModel()
{
_authService = Defaults.Locator.GetRequiredService<AuthService>();
NavigationFactory = new NavigationFactory();
}


public async Task RefreshTokenAndGetAccountInformation()
{
var cancellation = new CancellationToken();
Expand All @@ -46,35 +48,26 @@ public async Task RefreshTokenAndGetAccountInformation()
var identity = account.ClaimsPrincipal.Identities.First();
var email = identity.FindAll("preferred_username").First().Value ?? account.Account.Username;

Email = email.ToLowerInvariant();

AuthenticatedUserClaims = new AuthenticatedUserClaims()
{
Username = account.Account.Username,
TenantId = account.TenantId,
Name = account.ClaimsPrincipal.Identities.First().FindFirst("name").Value,
Email = account.ClaimsPrincipal.Identities.First().FindFirst("preferred_username").Value,
};
AuthenticatedUserClaims = _authService.AuthenticatedUserClaims;

IsAuthenticated = _authService.IsAuthenticated;
}



[RelayCommand]
[RelayCommand]
private async Task ForceSignIn()
{
var cancellation = new CancellationToken();
var account = await _authService.LoginAsync(cancellation);
Email = account.ClaimsPrincipal.Identities.First().FindFirst("preferred_username").Value;
AuthenticatedUserClaims = _authService.AuthenticatedUserClaims;
IsAuthenticated = _authService.IsAuthenticated;
}

[RelayCommand]
private async Task SignOut()
{
await _authService.RemoveAccount();
AuthenticatedUserClaims = null;
}

}

public class NavigationFactory : INavigationPageFactory
Expand Down
28 changes: 3 additions & 25 deletions KeyVaultExplorer/ViewModels/SettingsPageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,21 +133,14 @@ private async Task SignInOrRefreshTokenAsync()

if (account is null)
account = await _authService.LoginAsync(cancellation);

AuthenticatedUserClaims = new AuthenticatedUserClaims()
{
Username = account.Account.Username,
TenantId = account.TenantId,
Name = account.ClaimsPrincipal.Identities.First().FindFirst("name").Value,
Email = account.ClaimsPrincipal.Identities.First().FindFirst("{preferred_username")?.Value,
};
AuthenticatedUserClaims = _authService.AuthenticatedUserClaims;
}

[RelayCommand]
private async Task SignOut()
{
await _authService.RemoveAccount();
AuthenticatedUserClaims = null;
AuthenticatedUserClaims = _authService.AuthenticatedUserClaims;
}

[RelayCommand]
Expand All @@ -156,20 +149,5 @@ private void OpenIssueGithub()
Process.Start(new ProcessStartInfo("https://github.com/cricketthomas/KeyVaultExplorer/issues/new") { UseShellExecute = true, Verb = "open" });
}

// TODO: Create method of changing the background color from transparent to non stranparent
//[RelayCommand]
//private async Task SetNavigationLayout()
//{
// await AddOrUpdateAppSettings(nameof(NavigationLayoutMode), NavigationLayoutMode);
//}
//private async Task LoadApplicationVersion()
//{
// //string buildDirProps = Environment.GetEnvironmentVariable("EnvironmentName");
// //string _version = await File.ReadAllTextAsync(".\\VERSION.txt");
// //if (!System.Version.TryParse(_version, out Version fullVersion))
// //{
// // Version = "Missing version file" + buildDirProps;
// // return;
// //}
// //Version = $"{fullVersion.Major}.{fullVersion.Minor}.{fullVersion.Build}.{fullVersion.Revision}-{buildDirProps}";

}
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,15 @@ private void RefreshKeyVaultList(object sender, RoutedEventArgs e)
{
Dispatcher.UIThread.Post(async () =>
{
await (DataContext as KeyVaultTreeListViewModel)!.GetAvailableKeyVaultsCommand.ExecuteAsync(true);
await (DataContext as KeyVaultTreeListViewModel)!.GetAvailableKeyVaultsCommand.ExecuteAsync(true).ContinueWith((t) =>
{
((Control)sender)!.RaiseEvent(new RoutedEventArgs(MainView.SignInRoutedEvent));

});
}, DispatcherPriority.Input);



}

private void OnDoubleClicked(object sender, TappedEventArgs args)
Expand Down
7 changes: 4 additions & 3 deletions KeyVaultExplorer/Views/MainPage.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:models="clr-namespace:KeyVaultExplorer.Models;assembly=KeyVaultExplorer"
xmlns:pages="clr-namespace:KeyVaultExplorer.Views.Pages"
xmlns:ui="using:FluentAvalonia.UI.Controls"
xmlns:vm="clr-namespace:KeyVaultExplorer.ViewModels"
Expand Down Expand Up @@ -43,12 +44,12 @@
Background="{x:Null}"
FontSize="{StaticResource FontSizeSmall}"
Text="You are currently signed out." />
<TextBlock
<!-- <TextBlock
Margin="4,0"
Background="{x:Null}"
FontSize="{StaticResource FontSizeSmall}"
Text="Sign In"
TextDecorations="Underline" />
TextDecorations="Underline" />-->
</StackPanel>


Expand All @@ -68,7 +69,7 @@
Margin="5,0"
Background="{x:Null}"
FontSize="{StaticResource FontSizeSmall}"
Text="{Binding Email}" />
Text="{Binding AuthenticatedUserClaims.Email}" />
</StackPanel>
</StackPanel>
</Grid>
Expand Down
Loading

0 comments on commit 9451510

Please sign in to comment.