Skip to content

Commit

Permalink
[Account] Remove extra table from interactive context selection proce…
Browse files Browse the repository at this point in the history
…ss (Azure#25520)

* remove extra table

* refine code

* refine code

* refine code

* fix test cases

---------

Co-authored-by: Yabo Hu <[email protected]>
  • Loading branch information
BethanyZhou and VeryEarly authored Jul 15, 2024
1 parent 3b6e3c7 commit 3c9899c
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,8 @@ public void LoginByTenant()
null,
false,
mockOpenIDConfig.Object,
null);
null,
IsInteractiveContextSelectionEnabled: false);

Assert.Equal("2021-01-01", client.SubscriptionAndTenantClient.ApiVersion);
Assert.Equal(tenantA, azureRmProfile.DefaultContext.Tenant.Id.ToString());
Expand Down
10 changes: 2 additions & 8 deletions src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ public override void ExecuteCmdlet()
}
profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
profileClient.InformationLog = (message) => _tasks.Enqueue(new Task(() => WriteInteractiveInformation(message)));
profileClient.InteractiveInformationLog = (message) => _tasks.Enqueue(new Task(() => WriteInteractiveInformation(message)));
profileClient.DebugLog = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message)));
profileClient.PromptAndReadLine = (message) =>
{
Expand All @@ -561,7 +561,6 @@ public override void ExecuteCmdlet()
shouldPopulateContextList,
MaxContextPopulation,
resourceId,
IsInteractiveAuthenticationFlow(),
IsInteractiveContextSelectionEnabled()));
task.Start();
while (!task.IsCompleted)
Expand Down Expand Up @@ -614,11 +613,6 @@ private bool IsInteractiveContextSelectionEnabled()
return AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out IConfigManager configManager) ? configManager.GetConfigValue<LoginExperienceConfig>(ConfigKeys.LoginExperienceV2).Equals(LoginExperienceConfig.On) : true;
}

private bool IsInteractiveAuthenticationFlow()
{
return ParameterSetName.Equals(UserParameterSet);
}

private bool IsPopUpInteractiveAuthenticationFlow()
{
return ParameterSetName.Equals(UserParameterSet) && UseDeviceAuthentication.IsPresent == false;
Expand All @@ -634,7 +628,7 @@ private void ValidateActionRequiredMessageCanBePresented()

private void WriteInteractiveInformation(string message)
{
if (IsInteractiveAuthenticationFlow())
if (ParameterSetName.Equals(UserParameterSet))
{
this.WriteInformation(message, false);
}
Expand Down
1 change: 1 addition & 0 deletions src/Accounts/Accounts/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
-->

## Upcoming Release
* Removed the informational table about selected context to avoid duplication with output table.

## Version 3.0.2
* Fixed bug handling GUID type subscription Id.
Expand Down
43 changes: 19 additions & 24 deletions src/Accounts/Accounts/Models/RMProfileClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,21 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Common.Authentication.ResourceManager;
using Microsoft.Azure.Commands.Common.Exceptions;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.Profile.Properties;
using Microsoft.Azure.Commands.Profile.Utilities;
using Microsoft.Azure.Management.Profiles.Storage.Version2019_06_01.Models;
using Microsoft.Identity.Client.NativeInterop;
using Microsoft.Rest.Azure;
using Microsoft.WindowsAzure.Commands.Common;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Text;

using AuthenticationMessages = Microsoft.Azure.Commands.Common.Authentication.Properties.Resources;
using ProfileMessages = Microsoft.Azure.Commands.Profile.Properties.Resources;
Expand All @@ -46,7 +39,7 @@ public class RMProfileClient
private IAzureTokenCache _cache;
public Action<string> WarningLog;
public Action<string> DebugLog;
public Action<string> InformationLog;
public Action<string> InteractiveInformationLog;
internal Func<string, string> PromptAndReadLine;

private List<AzureTenant> _queriedTenants = new List<AzureTenant>();
Expand Down Expand Up @@ -137,18 +130,21 @@ public AzureRmProfile Login(
bool shouldPopulateContextList = true,
int maxContextPopulation = Profile.ConnectAzureRmAccountCommand.DefaultMaxContextPopulation,
string authScope = null,
bool isInteractiveAuthenticationFlow = false,
bool IsInteractiveContextSelectionEnabled = true)
{
if(isInteractiveAuthenticationFlow) WriteInformationMessage($"{PSStyle.ForegroundColor.BrightYellow}{Resources.PleaseSelectAccount}{PSStyle.Reset}{System.Environment.NewLine}");

WriteInteractiveInformationMessage($"{PSStyle.ForegroundColor.BrightYellow}{Resources.PleaseSelectAccount}{PSStyle.Reset}{System.Environment.NewLine}");

IAzureSubscription defaultSubscription = null;
IAzureTenant defaultTenant = null;
List<AzureSubscription> subscriptions = new List<AzureSubscription>();
List<AzureSubscription> tempSubscriptions = null;
string tenantName = null;

bool selectSubscriptionFromList = isInteractiveAuthenticationFlow && IsInteractiveContextSelectionEnabled && string.IsNullOrEmpty(subscriptionId) && string.IsNullOrEmpty(subscriptionName);
bool selectSubscriptionFromList = AzureAccount.AccountType.User.Equals(account.Type) &&
IsInteractiveContextSelectionEnabled &&
string.IsNullOrEmpty(subscriptionId) &&
string.IsNullOrEmpty(subscriptionName);
var lastUsedSubscription = selectSubscriptionFromList ? _profile?.DefaultContext?.Subscription : null;

string promptBehavior =
Expand Down Expand Up @@ -242,7 +238,7 @@ public AzureRmProfile Login(
throw new ArgumentNullException(string.Format($"{e.Message}{Environment.NewLine}{baseMessage} {typeMessage}"), e);
}

WriteInformationMessage(Resources.RetrievingSubscription);
WriteInteractiveInformationMessage(Resources.RetrievingSubscription);
tempSubscriptions = null;
if (TryGetTenantSubscription(
token,
Expand All @@ -253,8 +249,7 @@ public AzureRmProfile Login(
true,
out defaultSubscription,
out defaultTenant,
out tempSubscriptions,
isInteractiveAuthenticationFlow))
out tempSubscriptions))
{
account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { defaultTenant.Id.ToString() });

Expand All @@ -267,7 +262,7 @@ public AzureRmProfile Login(
{
InteractiveSubscriptionSelectionHelper.SelectSubscriptionFromList(
subscriptions, _queriedTenants, tenantIdOrName, tenantName, lastUsedSubscription,
Prompt, WriteInformationMessage,
Prompt, WriteInteractiveInformationMessage,
ref defaultSubscription, ref defaultTenant);
}
}
Expand All @@ -283,7 +278,7 @@ public AzureRmProfile Login(
IAzureSubscription tempSubscription = null;
tempSubscriptions = null;

WriteInformationMessage(Resources.RetrievingSubscription);
WriteInteractiveInformationMessage(Resources.RetrievingSubscription);

foreach (var tenant in _queriedTenants)
{
Expand Down Expand Up @@ -323,7 +318,7 @@ public AzureRmProfile Login(

if (token != null &&
(defaultTenant == null || selectSubscriptionFromList) &&
TryGetTenantSubscription(token, account, environment, subscriptionId, subscriptionName, false, out tempSubscription, out tempTenant, out tempSubscriptions, isInteractiveAuthenticationFlow))
TryGetTenantSubscription(token, account, environment, subscriptionId, subscriptionName, false, out tempSubscription, out tempTenant, out tempSubscriptions))
{
// If no subscription found for the given token/tenant,discard tempTenant value.
// Continue to look for matched subscripitons until one subscription retrived by its home tenant is found.
Expand All @@ -350,7 +345,7 @@ public AzureRmProfile Login(
{
InteractiveSubscriptionSelectionHelper.SelectSubscriptionFromList(
subscriptions, _queriedTenants, tenantIdOrName, tenantName, lastUsedSubscription,
Prompt, WriteInformationMessage,
Prompt, WriteInteractiveInformationMessage,
ref defaultSubscription, ref defaultTenant);
}
}
Expand Down Expand Up @@ -385,7 +380,7 @@ public AzureRmProfile Login(
WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, defaultContext.ToString()));
}

if (!skipValidation && !defaultSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
if (!skipValidation && null != defaultSubscription.State && !defaultSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
{
WriteWarningMessage(string.Format(
ProfileMessages.SelectedSubscriptionNotActive,
Expand Down Expand Up @@ -707,9 +702,9 @@ private bool TryGetTenantSubscription(IAccessToken accessToken,
bool isTenantPresent,
out IAzureSubscription subscription,
out IAzureTenant tenant,
out List<AzureSubscription> subscriptions,
bool isInteractiveAuthentication)
out List<AzureSubscription> subscriptions)
{
bool isInteractiveAuthentication = AzureAccount.AccountType.User.Equals(account.Type);
subscriptions = new List<AzureSubscription>();
subscription = null;
if (accessToken != null)
Expand Down Expand Up @@ -881,11 +876,11 @@ private void WriteDebugMessage(string message)
DebugLog(message);
}
}
private void WriteInformationMessage(string message)
private void WriteInteractiveInformationMessage(string message)
{
if (InformationLog != null)
if (InteractiveInformationLog != null)
{
InformationLog(message);
InteractiveInformationLog(message);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,6 @@ internal static void SelectSubscriptionFromList(IEnumerable<IAzureSubscription>
{
defaultTenant.ExtendedProperties.Add(AzureTenant.Property.DisplayName, tenantName);
}
WriteSelectedSubscriptionTable(defaultSubscription?.Name ?? defaultSubscription?.Id,
defaultTenant?.GetProperty(AzureTenant.Property.DisplayName) ?? tenantName ?? defaultTenant?.Id,
outputAction, columnSubNameWidth, columnTenantWidth, columnIndentsWidth);
}
catch (ArgumentOutOfRangeException)
{
Expand Down Expand Up @@ -149,26 +146,6 @@ private static void WriteSubscriptionSelectionTableRow(int subIndex, IAzureSubsc

}

private static void WriteSelectedSubscriptionTable(string subscription, string tenant,
Action<string> outputAction, int columnSubNameWidth, int columnTenantWidth, int columnIndentsWidth)
{
string columnSubNameTab = "Subscription name", columnTenantTab = "Tenant name";
string separator = "-",
ColumSubNameSeparator = new StringBuilder().Insert(0, separator, columnSubNameWidth).ToString(),
ColumTenantSeparator = new StringBuilder().Insert(0, separator, columnTenantWidth).ToString();

outputAction("");
outputAction($"{String.Format($"{{0,-{columnSubNameWidth + columnIndentsWidth}}}", columnSubNameTab)}" +
$"{String.Format($"{{0,-{columnTenantWidth + columnIndentsWidth}}}", columnTenantTab)}");
outputAction($"{String.Format($"{{0,-{columnSubNameWidth + columnIndentsWidth}}}", ColumSubNameSeparator)}" +
$"{String.Format($"{{0,-{columnTenantWidth}}}", ColumTenantSeparator)}");
string truncatedSubName = subscription?.Length > columnSubNameWidth ? $"{subscription.Substring(0, columnSubNameWidth - 3)}..." : subscription;
string truncatedTenantName = tenant?.Length > columnTenantWidth ? $"{tenant.Substring(0, columnTenantWidth - 3)}..." : tenant;
string subNameRowValue = String.Format($"{{0,-{columnSubNameWidth + columnIndentsWidth}}}", truncatedSubName),
tenantDomainNameRowValue = String.Format($"{{0,-{columnTenantWidth}}}", truncatedTenantName);
outputAction($"{subNameRowValue}{tenantDomainNameRowValue}");
}

public static IAzureTenant GetDetailedTenantFromQueryHistory(List<AzureTenant> queriedTenants, string tenantId)
{
return queriedTenants?.Where(t => t.Id.Equals(tenantId, StringComparison.OrdinalIgnoreCase))?.FirstOrDefault();
Expand Down

0 comments on commit 3c9899c

Please sign in to comment.