Skip to content

Commit 4ac52ac

Browse files
author
Hovsep
committed
Merge pull request #918 from hovsepm/dev
Added Get-AzureRMTenant [#102955260]
2 parents 8d7f0fb + 07b13d7 commit 4ac52ac

File tree

8 files changed

+220
-16
lines changed

8 files changed

+220
-16
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using Microsoft.Azure.Common.Authentication;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Linq;
5+
using System.Text;
6+
using System.Threading.Tasks;
7+
8+
namespace Microsoft.Azure.Commands.ResourceManager.Common
9+
{
10+
public static class AccessTokenExtensions
11+
{
12+
public static string GetDomain(this IAccessToken token)
13+
{
14+
if( token != null && token.UserId !=null && token.UserId.Contains('@'))
15+
{
16+
return token.UserId.Split(
17+
new[] { '@' },
18+
StringSplitOptions.RemoveEmptyEntries).Last();
19+
}
20+
21+
return null;
22+
}
23+
}
24+
}

src/Common/Commands.ResourceManager.Common/Commands.ResourceManager.Common.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@
182182
<Compile Include="..\Commands.Common\TestMockSupport.cs">
183183
<Link>Common\TestMockSupport.cs</Link>
184184
</Compile>
185+
<Compile Include="AccessTokenExtensions.cs" />
185186
<Compile Include="AzureRMCmdlet.cs" />
186187
<Compile Include="Properties\AssemblyInfo.cs" />
187188
<Compile Include="Properties\Resources.Designer.cs">

src/Common/Commands.ResourceManager.Common/RMProfileClient.cs

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -45,27 +45,23 @@ public RMProfileClient(AzureRMProfile profile)
4545
public AzureRMProfile Login(AzureAccount account, AzureEnvironment environment, string tenantId, string subscriptionId, SecureString password)
4646
{
4747
AzureSubscription newSubscription = null;
48-
AzureTenant newTenant = new AzureTenant();
48+
AzureTenant newTenant = null;
4949
ShowDialog promptBehavior = password == null ? ShowDialog.Always : ShowDialog.Never;
5050

5151
// (tenant and subscription are present) OR
5252
// (tenant is present and subscription is not provided)
5353
if (!string.IsNullOrEmpty(tenantId))
5454
{
55-
if (TryGetTenantSubscription(account, environment, tenantId, subscriptionId, password, promptBehavior, out newSubscription))
56-
{
57-
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
58-
}
55+
TryGetTenantSubscription(account, environment, tenantId, subscriptionId, password, promptBehavior, out newSubscription, out newTenant);
5956
}
6057
// (tenant is not provided and subscription is present) OR
6158
// (tenant is not provided and subscription is not provided)
6259
else
6360
{
6461
foreach(var tenant in ListAccountTenants(account, environment, password, promptBehavior))
6562
{
66-
if (TryGetTenantSubscription(account, environment, tenant, subscriptionId, password, ShowDialog.Auto, out newSubscription))
63+
if (TryGetTenantSubscription(account, environment, tenant.Id.ToString(), subscriptionId, password, ShowDialog.Auto, out newSubscription, out newTenant))
6764
{
68-
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
6965
break;
7066
}
7167
}
@@ -85,17 +81,16 @@ public AzureRMProfile Login(AzureAccount account, AzureEnvironment environment,
8581
public AzureContext UpdateCurrentContext(string subscriptionId, string tenantId)
8682
{
8783
AzureSubscription newSubscription = null;
88-
AzureTenant newTenant = new AzureTenant();
84+
AzureTenant newTenant = null;
8985
AzureAccount account = _profile.Context.Account;
9086
AzureEnvironment envrionment = _profile.Context.Environment;
9187
ShowDialog promptBehavior = ShowDialog.Auto;
9288

9389
if (!string.IsNullOrWhiteSpace(tenantId) &&
9490
!string.IsNullOrWhiteSpace(subscriptionId))
9591
{
96-
if(TryGetTenantSubscription(account, envrionment, tenantId, subscriptionId, null, promptBehavior, out newSubscription))
92+
if(TryGetTenantSubscription(account, envrionment, tenantId, subscriptionId, null, promptBehavior, out newSubscription, out newTenant))
9793
{
98-
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
9994
_profile.Context = new AzureContext(newSubscription, account, envrionment, newTenant);
10095
}
10196
}
@@ -110,16 +105,17 @@ public AzureContext UpdateCurrentContext(string subscriptionId, string tenantId)
110105
TokenCache.DefaultShared);
111106

112107
account.Properties[AzureAccount.Property.Tenants] = accessToken.TenantId;
108+
newTenant = new AzureTenant();
113109
newTenant.Id = new Guid(accessToken.TenantId);
110+
newTenant.Domain = accessToken.GetDomain();
114111
_profile.Context = new AzureContext(account, envrionment, newTenant);
115112
}
116113
else if(!string.IsNullOrWhiteSpace(subscriptionId))
117114
{
118115
foreach (var tenant in ListAccountTenants(account, envrionment, null, promptBehavior))
119116
{
120-
if (TryGetTenantSubscription(account, envrionment, tenant, subscriptionId, null, promptBehavior, out newSubscription))
117+
if (TryGetTenantSubscription(account, envrionment, tenant.Id.ToString(), subscriptionId, null, promptBehavior, out newSubscription, out newTenant))
121118
{
122-
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
123119
_profile.Context = new AzureContext(newSubscription, account, envrionment, newTenant);
124120
break;
125121
}
@@ -135,14 +131,24 @@ public AzureContext UpdateCurrentContext(string subscriptionId, string tenantId)
135131
return _profile.Context;
136132
}
137133

134+
public List<AzureTenant> ListTenants(string tenant)
135+
{
136+
return ListAccountTenants(_profile.Context.Account, _profile.Context.Environment, null, ShowDialog.Auto)
137+
.Where(t => tenant == null ||
138+
tenant.Equals(t.Id.ToString(), StringComparison.OrdinalIgnoreCase) ||
139+
tenant.Equals(t.Domain, StringComparison.OrdinalIgnoreCase))
140+
.ToList();
141+
}
142+
138143
private bool TryGetTenantSubscription(
139144
AzureAccount account,
140145
AzureEnvironment environment,
141146
string tenantId,
142147
string subscriptionId,
143148
SecureString password,
144149
ShowDialog promptBehavior,
145-
out AzureSubscription subscription)
150+
out AzureSubscription subscription,
151+
out AzureTenant tenant)
146152
{
147153
var accessToken = AzureSession.AuthenticationFactory.Authenticate(
148154
account,
@@ -166,7 +172,7 @@ private bool TryGetTenantSubscription(
166172
else
167173
{
168174
var subscriptions = subscriptionClient.Subscriptions.List().Subscriptions;
169-
if (subscriptions != null)
175+
if (subscriptions != null && subscriptions.Any())
170176
{
171177
if (subscriptions.Count > 1)
172178
{
@@ -195,15 +201,19 @@ private bool TryGetTenantSubscription(
195201
};
196202

197203
account.Properties[AzureAccount.Property.Tenants] = accessToken.TenantId;
204+
tenant = new AzureTenant();
205+
tenant.Id = new Guid(accessToken.TenantId);
206+
tenant.Domain = accessToken.GetDomain();
198207
return true;
199208
}
200209

201210
subscription = null;
211+
tenant = null;
202212
return false;
203213
}
204214
}
205215

206-
private string[] ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
216+
private List<AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
207217
{
208218
var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(
209219
account,
@@ -217,7 +227,9 @@ private string[] ListAccountTenants(AzureAccount account, AzureEnvironment envir
217227
new TokenCloudCredentials(commonTenantToken.AccessToken),
218228
environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
219229
{
220-
return subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray();
230+
return subscriptionClient.Tenants.List().TenantIds
231+
.Select(ti => new AzureTenant() { Id = new Guid(ti.TenantId), Domain = commonTenantToken.GetDomain() } )
232+
.ToList();
221233
}
222234
}
223235

src/Common/Commands.ResourceManager.Profile.Test/Commands.ResourceManager.Profile.Test.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@
179179
</ItemGroup>
180180
<ItemGroup>
181181
<Compile Include="ContextCmdletTests.Live.cs" />
182+
<Compile Include="TenantCmdletTests.cs" />
182183
<Compile Include="LoginCmdletTests.cs" />
183184
<Compile Include="ContextCmdletTests.Mocked.cs" />
184185
<Compile Include="ProfileCmdletTests.cs" />

src/Common/Commands.ResourceManager.Profile.Test/LoginCmdletTests.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ public void LoginWithSubscriptionAndTenant()
5757
cmdlt.InvokeEndProcessing();
5858

5959
Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
60+
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
6061
}
6162

6263
[Fact]
@@ -90,6 +91,7 @@ public void LoginWithSubscriptionAndNoTenant()
9091
cmdlt.InvokeEndProcessing();
9192

9293
Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
94+
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
9395
}
9496

9597
[Fact]
@@ -106,6 +108,7 @@ public void LoginWithNoSubscriptionAndNoTenant()
106108
cmdlt.InvokeEndProcessing();
107109

108110
Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
111+
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
109112
}
110113

111114
[Fact]
@@ -123,6 +126,7 @@ public void LoginWithNoSubscriptionAndTenant()
123126
cmdlt.InvokeEndProcessing();
124127

125128
Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
129+
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
126130
}
127131
}
128132
}
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
using Microsoft.WindowsAzure.Commands.Utilities.Common;
16+
using Microsoft.Azure.Commands.Profile;
17+
using Microsoft.Azure.Commands.ResourceManager.Common;
18+
using Microsoft.Azure.Common.Authentication;
19+
using Microsoft.Azure.Common.Authentication.Models;
20+
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
21+
using Microsoft.WindowsAzure.Commands.ScenarioTest;
22+
using System.Linq;
23+
using Xunit;
24+
using System;
25+
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
26+
using Hyak.Common;
27+
using System.Management.Automation;
28+
29+
namespace Microsoft.Azure.Commands.Profile.Test
30+
{
31+
public class TenantCmdletTests
32+
{
33+
private MemoryDataStore dataStore;
34+
private MockCommandRuntime commandRuntimeMock;
35+
36+
public TenantCmdletTests()
37+
{
38+
dataStore = new MemoryDataStore();
39+
AzureSession.DataStore = dataStore;
40+
commandRuntimeMock = new MockCommandRuntime();
41+
AzureRMCmdlet.DefaultProfile = new AzureRMProfile();
42+
}
43+
44+
[Fact]
45+
[Trait(Category.AcceptanceType, Category.LiveOnly)]
46+
public void GetTenantWithTenantParameter()
47+
{
48+
var cmdlt = new GetAzureRMTenantCommand();
49+
// Setup
50+
cmdlt.CommandRuntime = commandRuntimeMock;
51+
cmdlt.Tenant = "72f988bf-86f1-41af-91ab-2d7cd011db47";
52+
53+
// Act
54+
Login("2c224e7e-3ef5-431d-a57b-e71f4662e3a6", null);
55+
cmdlt.InvokeBeginProcessing();
56+
cmdlt.ExecuteCmdlet();
57+
cmdlt.InvokeEndProcessing();
58+
59+
Assert.True(commandRuntimeMock.OutputPipeline.Count == 2);
60+
Assert.Equal("72f988bf-86f1-41af-91ab-2d7cd011db47", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Id.ToString());
61+
Assert.Equal("microsoft.com", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Domain);
62+
}
63+
64+
[Fact]
65+
[Trait(Category.AcceptanceType, Category.LiveOnly)]
66+
public void GetTenantWithDomainParameter()
67+
{
68+
var cmdlt = new GetAzureRMTenantCommand();
69+
// Setup
70+
cmdlt.CommandRuntime = commandRuntimeMock;
71+
cmdlt.Tenant = "microsoft.com";
72+
73+
// Act
74+
Login("2c224e7e-3ef5-431d-a57b-e71f4662e3a6", null);
75+
cmdlt.InvokeBeginProcessing();
76+
cmdlt.ExecuteCmdlet();
77+
cmdlt.InvokeEndProcessing();
78+
79+
Assert.True(commandRuntimeMock.OutputPipeline.Count == 2);
80+
Assert.Equal("72f988bf-86f1-41af-91ab-2d7cd011db47", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Id.ToString());
81+
Assert.Equal("microsoft.com", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Domain);
82+
}
83+
84+
[Fact]
85+
[Trait(Category.AcceptanceType, Category.LiveOnly)]
86+
public void GetTenantWithoutParameters()
87+
{
88+
var cmdlt = new GetAzureRMTenantCommand();
89+
// Setup
90+
cmdlt.CommandRuntime = commandRuntimeMock;
91+
92+
// Act
93+
Login("2c224e7e-3ef5-431d-a57b-e71f4662e3a6", null);
94+
cmdlt.InvokeBeginProcessing();
95+
cmdlt.ExecuteCmdlet();
96+
cmdlt.InvokeEndProcessing();
97+
98+
Assert.True(commandRuntimeMock.OutputPipeline.Count == 2);
99+
Assert.Equal("72f988bf-86f1-41af-91ab-2d7cd011db47", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Id.ToString());
100+
Assert.Equal("microsoft.com", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Domain);
101+
}
102+
103+
private void Login(string subscriptionId, string tenantId)
104+
{
105+
var cmdlt = new LoginAzureRMAccountCommand();
106+
// Setup
107+
cmdlt.CommandRuntime = commandRuntimeMock;
108+
cmdlt.SubscriptionId = subscriptionId;
109+
cmdlt.Tenant = tenantId;
110+
111+
// Act
112+
cmdlt.InvokeBeginProcessing();
113+
cmdlt.ExecuteCmdlet();
114+
cmdlt.InvokeEndProcessing();
115+
116+
Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
117+
}
118+
}
119+
}

src/Common/Commands.ResourceManager.Profile/Commands.ResourceManager.Profile.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@
143143
<DesignTime>True</DesignTime>
144144
<DependentUpon>Resources.resx</DependentUpon>
145145
</Compile>
146+
<Compile Include="Tenant\GetAzureRMTenant.cs" />
146147
</ItemGroup>
147148
<ItemGroup>
148149
<Content Include="Microsoft.Azure.Commands.Profile.format.ps1xml">
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
using Microsoft.Azure.Commands.ResourceManager.Common;
16+
using Microsoft.Azure.Common.Authentication.Models;
17+
using System.Collections.Generic;
18+
using System.Management.Automation;
19+
20+
namespace Microsoft.Azure.Commands.Profile
21+
{
22+
/// <summary>
23+
/// Cmdlet to get user tenant information.
24+
/// </summary>
25+
[Cmdlet(VerbsCommon.Get, "AzureRMTenant")]
26+
[Alias("Get-AzureRMDomain")]
27+
[OutputType(typeof(List<AzureTenant>))]
28+
public class GetAzureRMTenantCommand : AzureRMCmdlet
29+
{
30+
[Parameter(Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)]
31+
[Alias("Domain")]
32+
[ValidateNotNullOrEmpty]
33+
public string Tenant { get; set; }
34+
35+
protected override void ProcessRecord()
36+
{
37+
var profileClient = new RMProfileClient(AzureRMCmdlet.DefaultProfile);
38+
39+
WriteObject(profileClient.ListTenants(Tenant), enumerateCollection: true);
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)