aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Azure/Tango.AzureUtils/ActiveDirectory/ActiveDirectoryManager.cs
blob: fad95df287ff094dab53354855081e8be32c235f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;
using Microsoft.Azure.Management.Fluent;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace Tango.AzureUtils.ActiveDirectory
{
    public class ActiveDirectoryManager : AzureUtilsComponentBase
    {
        private AuthenticationResult _authResult;
        private ActiveDirectoryClient _adClient;

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ActiveDirectoryManager"/> class.
        /// </summary>
        /// <param name="azure">The azure instance.</param>
        public ActiveDirectoryManager(IAzure azure) : base(azure)
        {

        }

        #endregion

        #region Private Methods

        private ActiveDirectoryClient GetActiveDirectoryClient()
        {
            if (_adClient == null)
            {
                var credentials = AzureUtilsAuthenticationFactory.GetGlobalCredentials();
                _adClient = new ActiveDirectoryClient(new Uri($"https://graph.windows.net/{credentials.TenantID}"), async () => await Task.FromResult(_authResult.AccessToken));
            }
            return _adClient;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Authenticates using application credentials.
        /// </summary>
        /// <param name="credentials">The credentials.</param>
        /// <returns></returns>
        public async Task Authenticate(AzureUtilsCredentials credentials)
        {
            if (_authResult == null)
            {
                var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{credentials.TenantID}");
                ClientCredential clientCredentials = new ClientCredential(credentials.ClientID, credentials.ClientSecret);
                _authResult = await authContext.AcquireTokenAsync("https://graph.windows.net/", clientCredentials);
            }
        }

        /// <summary>
        /// Authenticates using an AD account.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public async Task Authenticate(String email, String password)
        {
            OnProgress(AzureUtilsStage.ActiveDirectory, $"Authenticating with active directory graph...");
            if (_authResult == null)
            {
                var credentials = AzureUtilsAuthenticationFactory.GetGlobalCredentials();
                var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{credentials.TenantID}");
                authContext.TokenCache.Clear();
                UserCredential userCredential = new UserPasswordCredential(email, password);
                _authResult = await authContext.AcquireTokenAsync("https://graph.windows.net/", "ec612854-7abc-457b-808a-5d0c5ba80c57", userCredential);
            }
        }

        /// <summary>
        /// Determines whether the specified group name exists.
        /// </summary>
        /// <param name="groupName">Name of the group.</param>
        /// <returns></returns>
        public async Task<bool> IsGroupExists(String groupName)
        {
            try
            {
                var client = GetActiveDirectoryClient();
                var g = await client.Groups.Where(x => x.DisplayName == groupName).Take(1).ExecuteSingleAsync();
                return g != null;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Adds the specified group.
        /// </summary>
        /// <param name="groupName">Name of the group.</param>
        /// <returns></returns>
        public async Task AddGroup(String groupName)
        {
            OnProgress(AzureUtilsStage.ActiveDirectory, $"Creating group '{groupName}'...");
            var client = GetActiveDirectoryClient();

            await client.Groups.AddGroupAsync(new Group()
            {
                DisplayName = groupName,
                MailEnabled = false,
                MailNickname = Guid.NewGuid().ToString().ToLower(),
                SecurityEnabled = true
            });
        }

        /// <summary>
        /// Removes the specified group.
        /// </summary>
        /// <param name="groupName">Name of the group.</param>
        /// <returns></returns>
        public async Task RemoveGroup(String groupName)
        {
            OnProgress(AzureUtilsStage.ActiveDirectory, $"Removing group '{groupName}'...");
            var client = GetActiveDirectoryClient();

            var g = await client.Groups.OfType<Group>().Where(x => x.DisplayName == groupName).Take(1).ExecuteSingleAsync();

            await g.DeleteAsync();
        }

        /// <summary>
        /// Adds the specified user to the specified group.
        /// </summary>
        /// <param name="groupName">Name of the group.</param>
        /// <param name="userEmail">The user email.</param>
        /// <returns></returns>
        public async Task AddUserToGroup(String groupName, String userEmail)
        {
            OnProgress(AzureUtilsStage.ActiveDirectory, $"Adding environment group user '{userEmail}'...");

            var client = GetActiveDirectoryClient();

            List<Group> groups = new List<Group>();

            var user = await client.Users.Where(x => x.UserPrincipalName == userEmail).ExecuteSingleAsync();

            var g = await client.Groups.Where(x => x.DisplayName == groupName).Take(1).ExecuteSingleAsync();

            var gg = g as Group;

            gg.Members.Add(user as DirectoryObject);
            await gg.UpdateAsync();
        }

        /// <summary>
        /// Gets all users.
        /// </summary>
        /// <returns></returns>
        public async Task<List<User>> GetAllUsers()
        {
            OnProgress(AzureUtilsStage.ActiveDirectory, $"Retrieving active directory users...");

            var client = GetActiveDirectoryClient();

            List<User> users = new List<User>();

            var userPages = await client.Users.OfType<User>().ExecuteAsync();

            do
            {
                List<User> directoryObjects = userPages.CurrentPage.ToList();
                foreach (User u in directoryObjects)
                {
                    users.Add(u);
                }

                userPages = await userPages.GetNextPageAsync();

            } while (userPages != null);

            return users;
        }

        public List<Group> GetUserGroups(String email)
        {
            var client = GetActiveDirectoryClient();

            var user = client.Users.Where(x => x.UserPrincipalName == email).ExecuteSingleAsync().Result;

            var userFetcher = (IUserFetcher)user;

            List<Group> groups = new List<Group>();

            IPagedCollection<IDirectoryObject> pagedCollection = userFetcher.MemberOf.ExecuteAsync().Result;
            do
            {
                List<IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
                foreach (IDirectoryObject directoryObject in directoryObjects)
                {
                    if (directoryObject is Group)
                    {
                        var group = directoryObject as Group;
                        groups.Add(group);
                    }
                }
                pagedCollection = pagedCollection.GetNextPageAsync().Result;
            } while (pagedCollection != null);

            return groups;
        }

        public bool IsUserMemberOf(String group, String email)
        {
            return GetUserGroups(email).Exists(x => x.DisplayName == group);
        }

        #endregion
    }
}