public ViewResult RemoveAppRoleFromUser()
        {
            AddAppRoleToUserModel model = new AddAppRoleToUserModel();

            try
            {
                var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);

                var apps           = azureClient.Applications.ExecuteAsync().Result;
                var enumeratedApps = AzureADExtensions.EnumerateAllAsync(apps).Result;

                foreach (var app in enumeratedApps)
                {
                    model.TenantApplications.Add(new SelectListItem()
                    {
                        Text = app.DisplayName, Value = app.DisplayName
                    });
                }

                model.isOk = true;
            }
            catch (Exception ex)
            {
                model.message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
            }

            return(View("RemoveAppRoleFromUser", model));
        }
        public ActionResult GetApplicationExtAttribs(string appName)
        {
            List <ResultsItem> lst = new List <ResultsItem>();

            try
            {
                var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);
                var application = azureClient.Applications.Where(a => a.DisplayName == appName).ExecuteAsync().Result.CurrentPage.FirstOrDefault();
                if (application != null)
                {
                    var exts = azureClient.Applications[application.ObjectId].ExtensionProperties;

                    foreach (IExtensionProperty r in exts.ExecuteAsync().Result.EnumerateAllAsync().Result)
                    {
                        lst.Add(new ResultsItem()
                        {
                            Id = r.Name, Display = r.Name
                        });
                    }
                }
            }
            catch (Exception ex)
            { }

            return(Json(lst, JsonRequestBehavior.AllowGet));
        }
        public ActionResult GetApplicationRoles(string appName)
        {
            List <ResultsItem> lst = new List <ResultsItem>();

            try
            {
                var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);
                var application = azureClient.Applications.Where(a => a.DisplayName == appName).ExecuteAsync().Result;
                if (application != null)
                {
                    var approles = application.CurrentPage.FirstOrDefault().AppRoles;

                    foreach (AppRole r in approles)
                    {
                        lst.Add(new ResultsItem()
                        {
                            Id = r.DisplayName, Display = r.Description
                        });
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(Json(lst, JsonRequestBehavior.AllowGet));
        }
        public async Task <ActionResult> UpdateUser(UpdateUserModel model)
        {
            List <ResultsItem> items = new List <ResultsItem>();

            if (ModelState.IsValid)
            {
                try
                {
                    var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);

                    Tuple <bool, string, string> tup = await usersService.UpdateUser(azureClient, model.UserEmailAddress, model.Jobtitle,
                                                                                     model.department, model.City, model.phone);


                    Microsoft.Azure.ActiveDirectory.GraphClient.User user = (Microsoft.Azure.ActiveDirectory.GraphClient.User)azureClient.Users.Where(u => u.Mail.Equals(
                                                                                                                                                          model.UserEmailAddress, StringComparison.CurrentCultureIgnoreCase) ||
                                                                                                                                                      u.UserPrincipalName.Equals(model.UserEmailAddress, StringComparison.CurrentCultureIgnoreCase)).ExecuteAsync().Result.CurrentPage.FirstOrDefault();


                    return(View("ShowUser", new Tuple <bool, string, string, Microsoft.Azure.ActiveDirectory.GraphClient.User>(
                                    tup.Item1, tup.Item2, model.UserEmailAddress, user)));
                }
                catch (Exception ex)
                {
                    model.status           = false;
                    model.resultantMessage = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
                }
            }

            return(View("UpdateUser", model));
        }
        public ViewResult ListTenantApps()
        {
            List <ResultsItem> lst = new List <ResultsItem>();
            bool   isok            = false;
            string message         = "";

            try
            {
                var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);

                var apps           = azureClient.Applications.ExecuteAsync().Result;
                var enumeratedApps = AzureADExtensions.EnumerateAllAsync(apps).Result;

                foreach (var app in enumeratedApps.OrderBy(a => a.DisplayName))
                {
                    lst.Add(new ResultsItem()
                    {
                        Id = app.DisplayName, Display = app.DisplayName
                    });
                }

                isok = true;
            }
            catch (Exception ex)
            {
                message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
            }

            return(View(new Tuple <bool, string, List <ResultsItem> >(isok, message, lst)));
        }
        public async Task <ActionResult> RemoveAppRoleFromUser(AddAppRoleToUserModel model)
        {
            List <ResultsItem> items = new List <ResultsItem>();

            if (ModelState.IsValid)
            {
                try
                {
                    var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);

                    string token = await GraphAuthService.GetTokenForApplication(ConfigHelper.UseApplicationPermissions);

                    Tuple <bool, string, string, string, string> tup = await usersService.RemoveApplicationRoleFromUser(azureClient, token,
                                                                                                                        ConfigHelper.AzureADGraphUrl, ConfigHelper.Tenant, model.AppName, model.UserEmailAddress, model.AppRoleName);

                    // Get group members.
                    var appRoleAssignmentsPaged = await azureClient.ServicePrincipals
                                                  .GetByObjectId(tup.Item5)
                                                  .AppRoleAssignedTo
                                                  .ExecuteAsync();

                    var appRoleAssignments = await AzureADExtensions.EnumerateAllAsync(appRoleAssignmentsPaged);

                    Guid approleid = Guid.Parse(tup.Item4);

                    var users = appRoleAssignments
                                .Where(a => a.Id == approleid && a.PrincipalType == "User")
                                .Select(a => new { Id = a.PrincipalId.ToString(), Name = a.PrincipalDisplayName })
                                .ToList();

                    if (users != null)
                    {
                        foreach (var s in users)
                        {
                            items.Add(new ResultsItem()
                            {
                                Id = s.Id, Display = s.Name
                            });
                        }
                    }

                    return(View("ListRoleMembers", new Tuple <bool, string, string, List <ResultsItem> >(tup.Item1, tup.Item2, model.AppRoleName, items)));
                }
                catch (Exception ex)
                {
                    model.isOk    = false;
                    model.message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
                }
            }

            return(View("RemoveAppRoleFromUser", model));
        }
        public async Task <ActionResult> AssignExtAttribToUser(ManageApplicationExtensionsAssignment model)
        {
            List <ResultsItem> items = new List <ResultsItem>();

            if (ModelState.IsValid)
            {
                try
                {
                    var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);

                    Tuple <bool, string, string, string, string> tup = await usersService.AssignExtensionAttributeToUser(azureClient, model.UserEmailAddress, model.AppName,
                                                                                                                         model.AppExtAttribName, model.ExtAttribValue);


                    Microsoft.Azure.ActiveDirectory.GraphClient.User user = (Microsoft.Azure.ActiveDirectory.GraphClient.User)azureClient.Users.Where(u => u.Mail.Equals(
                                                                                                                                                          model.UserEmailAddress, StringComparison.CurrentCultureIgnoreCase) ||
                                                                                                                                                      u.UserPrincipalName.Equals(model.UserEmailAddress, StringComparison.CurrentCultureIgnoreCase)
                                                                                                                                                      ).ExecuteAsync().Result.CurrentPage.FirstOrDefault();

                    if (user != null)
                    {
                        foreach (var s in user.GetExtendedProperties())
                        {
                            items.Add(new ResultsItem()
                            {
                                Id = s.Key, Display = (s.Value == null ? "" : s.Value.ToString())
                            });
                        }
                    }

                    return(View("ListuserExtAttributes", new Tuple <bool, string, string, List <ResultsItem> >(tup.Item1, tup.Item2, model.UserEmailAddress, items)));
                }
                catch (Exception ex)
                {
                    model.isOk    = false;
                    model.message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
                }
            }

            return(View("AssignExtAttribToUser", model));
        }
        public ActionResult GetUserApplicationRoles(string appName, string useremail)
        {
            List <ResultsItem> lst = new List <ResultsItem>();

            try
            {
                var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);

                var user = azureClient.Users.Where(a => a.Mail.Equals(useremail, StringComparison.InvariantCultureIgnoreCase) || a.UserPrincipalName.Equals(useremail, StringComparison.InvariantCultureIgnoreCase)
                                                   ).Expand(p => p.AppRoleAssignments).ExecuteAsync().Result.CurrentPage.FirstOrDefault();
                if (user != null)
                {
                    var cc = user.AppRoleAssignments;
                    var approlesassigns = AzureADExtensions.EnumerateAllAsync(cc).Result;
                    var filtered        = approlesassigns.Where(a => a.PrincipalType == "User");

                    //now get role names for those
                    var fapplication = azureClient.Applications.Where(a => a.DisplayName == appName).ExecuteAsync().Result;
                    if (fapplication != null)
                    {
                        var myroles = fapplication.CurrentPage.FirstOrDefault().AppRoles.Where(a => filtered.Select(b => b.Id).Contains(a.Id));

                        foreach (AppRole r in myroles)
                        {
                            lst.Add(new ResultsItem()
                            {
                                Id = r.DisplayName, Display = r.Description
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            { }


            return(Json(lst, JsonRequestBehavior.AllowGet));
        }
        public ViewResult GetUser(GuestUserModel model)
        {
            List <Tuple <string, List <ResultsItem> > > tupAppRoles = new List <Tuple <string, List <ResultsItem> > >();
            List <ResultsItem> lstUserAppRoles = new List <ResultsItem>();
            List <ResultsItem> exts            = new List <ResultsItem>();
            List <string>      groups          = new List <string>();

            Microsoft.Azure.ActiveDirectory.GraphClient.User myuser = null;

            if (ModelState.IsValid)
            {
                try
                {
                    var azureClient = GraphAuthService.GetActiveDirectoryClient(ConfigHelper.UseApplicationPermissions);

                    var user = azureClient.Users.Where(a => a.UserPrincipalName.Equals(model.UserEmailAddress, StringComparison.InvariantCultureIgnoreCase) ||
                                                       a.Mail.Equals(model.UserEmailAddress, StringComparison.InvariantCultureIgnoreCase)
                                                       ).Expand(p => p.AppRoleAssignments).ExecuteAsync().Result.CurrentPage.FirstOrDefault();

                    if (user != null)
                    {
                        var cc = user.AppRoleAssignments;
                        var approlesassigns = AzureADExtensions.EnumerateAllAsync(cc).Result;
                        var filtered        = approlesassigns.Where(a => a.PrincipalType == "User");

                        //now get role names for those
                        var fapplications = azureClient.Applications.ExecuteAsync().Result;
                        if (fapplications != null)
                        {
                            IEnumerable <IApplication> allapps = AzureADExtensions.EnumerateAllAsync(fapplications).Result;

                            foreach (IApplication app in allapps)
                            {
                                string applicationname = app.DisplayName;

                                var fapplication = azureClient.Applications.Where(a => a.DisplayName == applicationname).ExecuteAsync().Result;
                                if (fapplication != null)
                                {
                                    lstUserAppRoles = new List <ResultsItem>();

                                    var myroles = fapplication.CurrentPage.FirstOrDefault().AppRoles.Where(a => filtered.Select(b => b.Id).Contains(a.Id));

                                    foreach (AppRole r in myroles)
                                    {
                                        lstUserAppRoles.Add(new ResultsItem()
                                        {
                                            Id = r.DisplayName, Display = r.Description
                                        });
                                    }

                                    tupAppRoles.Add(new Tuple <string, List <ResultsItem> >(app.DisplayName, lstUserAppRoles));
                                }
                            }
                        }


                        //get extension attributes
                        myuser = (Microsoft.Azure.ActiveDirectory.GraphClient.User)user;

                        foreach (var s in myuser.GetExtendedProperties())
                        {
                            exts.Add(new ResultsItem()
                            {
                                Id = s.Key, Display = (s.Value == null ? "" : s.Value.ToString())
                            });
                        }

                        IUserFetcher retrievedUserFetcher = myuser;
                        Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.IPagedCollection <IDirectoryObject> pagedCollection =
                            retrievedUserFetcher.MemberOf.ExecuteAsync().Result;

                        List <IDirectoryObject> directoryObjects = pagedCollection.EnumerateAllAsync().Result.ToList();

                        foreach (IDirectoryObject directoryObject in directoryObjects)
                        {
                            if (directoryObject is Microsoft.Azure.ActiveDirectory.GraphClient.Group)
                            {
                                Microsoft.Azure.ActiveDirectory.GraphClient.Group group = directoryObject as Microsoft.Azure.ActiveDirectory.GraphClient.Group;
                                groups.Add(group.DisplayName);
                            }
                        }
                    }

                    return(View("GetUserDetails", new UserDetails()
                    {
                        isOk = true, message = "", exts = exts, tupAppRoles = tupAppRoles, user = myuser, Groups = groups
                    }));
                }
                catch (Exception ex)
                {
                    model.status           = false;
                    model.resultantMessage = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
                }
            }

            return(View("GetUser", model));
        }