Skip to content

Porting to CLU changes in powershell cmdlets #1382

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

Merged
merged 3 commits into from
Dec 1, 2015
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
@@ -0,0 +1,3 @@
{
"profiles": {}
}
11 changes: 6 additions & 5 deletions src/CLU/Commands.Common/Models/PSAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System;
using System.Collections.Generic;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using System.Linq;

namespace Microsoft.Azure.Commands.Models
{
Expand Down Expand Up @@ -86,12 +87,12 @@ public static implicit operator AzureAccount(PSAzureRmAccount account)
result.SetProperty(AzureAccount.Property.AccessToken, account.AccessToken);
}

if (account.Tenants != null)
if (account.Tenants != null &&
account.Tenants.Any(s => !string.IsNullOrWhiteSpace(s)))
{
foreach (var tenant in account.Tenants)
{
result.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
}
result.SetProperty(
AzureAccount.Property.Tenants,
account.Tenants.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray());
}

if (!string.IsNullOrWhiteSpace(account.CertificateThumbprint))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public void AddUserAgent(string productName)

/// <summary>
/// This class exists to allow adding an additional reference to the httpClient to prevent the client
/// from being disposed. Should not be used execpt in this mocked context.
/// from being disposed. Should not be used except in this mocked context.
/// </summary>
class PassThroughDelegatingHandler : DelegatingHandler
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ public class AddAzureRMAccountCommand : AzureRMCmdlet
[ValidateNotNullOrEmpty]
public AzureEnvironment Environment { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Name of the environment containing the account to log into")]
[ValidateNotNullOrEmpty]
public string EnvironmentName { get; set; }

[Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = true, HelpMessage = "Credential")]
[Parameter(ParameterSetName = SubscriptionIdParameterSet, Mandatory = false, HelpMessage = "Optional credential")]
[Parameter(ParameterSetName = SubscriptionNameParameterSet, Mandatory = false, HelpMessage = "Optional credential")]
Expand Down Expand Up @@ -77,8 +81,6 @@ public class AddAzureRMAccountCommand : AzureRMCmdlet

[Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = true)]
[Parameter(ParameterSetName = ServicePrincipalCertificateParameterSet, Mandatory = true)]
[Parameter(ParameterSetName = SubscriptionIdParameterSet, Mandatory = false)]
[Parameter(ParameterSetName = SubscriptionNameParameterSet, Mandatory = false)]
public SwitchParameter ServicePrincipal { get; set; }

[Parameter(ParameterSetName = UserParameterSet, Mandatory = false, HelpMessage = "Optional tenant name or ID")]
Expand All @@ -104,10 +106,12 @@ public class AddAzureRMAccountCommand : AzureRMCmdlet
public string AccountId { get; set; }

[Parameter(ParameterSetName = SubscriptionIdParameterSet, Mandatory = false, HelpMessage = "Subscription", ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = false, HelpMessage = "Subscription", ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string SubscriptionId { get; set; }

[Parameter(ParameterSetName = SubscriptionNameParameterSet, Mandatory = false, HelpMessage = "Subscription Name", ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = false, HelpMessage = "Subscription Name", ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string SubscriptionName { get; set; }

Expand All @@ -122,9 +126,21 @@ protected override AzureContext DefaultContext
protected override void BeginProcessing()
{
base.BeginProcessing();
if (Environment == null)
if (Environment == null && EnvironmentName == null)
{
Environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
Environment = AzureEnvironment.PublicEnvironments[Common.Authentication.Models.EnvironmentName.AzureCloud];
}
else if (Environment == null && EnvironmentName != null)
{
if (DefaultProfile.Environments.ContainsKey(EnvironmentName))
{
Environment = DefaultProfile.Environments[EnvironmentName];
}
else
{
throw new PSInvalidOperationException(
string.Format(Resources.UnknownEnvironment, EnvironmentName));
}
}
}

Expand All @@ -140,7 +156,8 @@ protected override void ProcessRecord()
if (!string.IsNullOrWhiteSpace(SubscriptionId) &&
!Guid.TryParse(SubscriptionId, out subscrptionIdGuid))
{
throw new PSInvalidOperationException(Resources.InvalidSubscriptionId);
throw new PSInvalidOperationException(
string.Format(Resources.InvalidSubscriptionId, SubscriptionId));
}

AzureAccount azureAccount = new AzureAccount();
Expand Down Expand Up @@ -173,8 +190,7 @@ protected override void ProcessRecord()
{
azureAccount.SetProperty(AzureAccount.Property.CertificateThumbprint, CertificateThumbprint);
}



if (!string.IsNullOrEmpty(ApplicationId))
{
azureAccount.Id = ApplicationId;
Expand Down
70 changes: 58 additions & 12 deletions src/CLU/Microsoft.Azure.Commands.Profile/Models/RMProfileClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,20 +72,59 @@ public AzureRMProfile Login(
if (!string.IsNullOrEmpty(tenantId))
{
var token = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);
TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant);
if (TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant))
{
account.SetProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() });
}
}
// (tenant is not provided and subscription is present) OR
// (tenant is not provided and subscription is not provided)
else
{
foreach (var tenant in ListAccountTenants(account, environment, password, promptBehavior))
var tenants = ListAccountTenants(account, environment, password, promptBehavior).Select(s => s.Id.ToString()).ToArray();
account.SetProperty(AzureAccount.Property.Tenants, null);
string accountId = null;

for (int i = 0; i < tenants.Count(); i++)
{
var tenant = tenants[i];

AzureTenant tempTenant;
AzureSubscription tempSubscription;
var token = AcquireAccessToken(account, environment, tenant.Id.ToString(), password,
ShowDialog.Auto);
if (newTenant == null && TryGetTenantSubscription(token, account, environment, tenant.Id.ToString(), subscriptionId, subscriptionName, out tempSubscription, out tempTenant) &&
newTenant == null)

IAccessToken token = null;

try
{
token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto);
if (accountId == null)
{
accountId = account.Id;
account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
}
else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
{
account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
}
else
{ // if account ID is different from the first tenant account id we need to ignore current tenant
WriteWarningMessage(string.Format(
Microsoft.Azure.Commands.Profile.Properties.Resources.AccountIdMismatch,
account.Id,
tenant,
accountId));
account.Id = accountId;
token = null;
}
}
catch
{
WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenant));
}

if (token != null &&
newTenant == null &&
TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant))
{
newTenant = tempTenant;
newSubscription = tempSubscription;
Expand Down Expand Up @@ -485,7 +524,6 @@ private bool TryGetTenantSubscription(IAccessToken accessToken,
Properties = new Dictionary<AzureSubscription.Property, string> { { AzureSubscription.Property.Tenants, accessToken.TenantId } }
};

account.Properties[AzureAccount.Property.Tenants] = accessToken.TenantId;
tenant = new AzureTenant();
tenant.Id = new Guid(accessToken.TenantId);
tenant.Domain = accessToken.GetDomain();
Expand Down Expand Up @@ -513,9 +551,7 @@ private bool TryGetTenantSubscription(IAccessToken accessToken,
return false;
}
}




private List<AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, string password, ShowDialog promptBehavior)
{
List<AzureTenant> result = null;
Expand Down Expand Up @@ -548,7 +584,6 @@ private List<AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironm
Domain = AccessTokenExtensions.GetDomain(account.Id)
}).ToList();
}

}

return result;
Expand All @@ -557,7 +592,18 @@ private List<AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironm
private IEnumerable<AzureSubscription> ListSubscriptionsForTenant(AzureAccount account, AzureEnvironment environment,
string password, ShowDialog promptBehavior, string tenantId)
{
var accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);
IAccessToken accessToken = null;

try
{
accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);
}
catch
{
WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenantId));
return new List<AzureSubscription>();
}

using (var subscriptionClient = _clientFactory.CreateCustomArmClient<SubscriptionClient>(
environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager),
new TokenCredentials(accessToken.AccessToken)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@
<data name="AccessTokenRequiresAccount" xml:space="preserve">
<value>AccountId must be provided to use an AccessToken credential.</value>
</data>
<data name="AccountIdMismatch" xml:space="preserve">
<value>Account ID '{0}' for tenant '{1}' does not match home Account ID '{2}'</value>
</data>
<data name="AccountIdRequired" xml:space="preserve">
<value>Access token credentials must provide the AccountId parameter.</value>
</data>
Expand Down Expand Up @@ -186,4 +189,10 @@
<data name="TypeNotAccessToken" xml:space="preserve">
<value>To create an access token credential, you must provide an access token account.</value>
</data>
<data name="UnableToAqcuireToken" xml:space="preserve">
<value>Unabe to acquire token for tenant '{0}'</value>
</data>
<data name="UnknownEnvironment" xml:space="preserve">
<value>Unable to find environment with name '{0}</value>
</data>
</root>