Beispiel #1
0
        public HttpResponseMessage Export(string search)
        {
            try
            {
                if (!bool.Parse(Utils.GetTabModuleSetting(ActiveModule.TabModuleID, "EnableExport", "True")))
                {
                    return(Request.CreateResponse(HttpStatusCode.Forbidden, "You are not allowed to export users"));
                }
                var settings          = new AzureConfig(AzureConfig.ServiceName, PortalSettings.PortalId);
                var graphClient       = new GraphClient(settings.AADApplicationId, settings.AADApplicationKey, settings.TenantId);
                var portalUserMapping = UserMappingsRepository.Instance.GetUserMapping("PortalId", settings.UseGlobalSettings ? -1 : PortalSettings.PortalId);
                var idUserMapping     = UserMappingsRepository.Instance.GetUserMapping("Id", settings.UseGlobalSettings ? -1 : PortalSettings.PortalId);

                var query  = "$orderby=displayName";
                var filter = ConfigurationManager.AppSettings["AzureADB2C.GetAllUsers.Filter"];
                if (!string.IsNullOrEmpty(search))
                {
                    if (!string.IsNullOrEmpty(filter))
                    {
                        filter += " and ";
                    }
                    filter += $"startswith(displayName, '{search}')";
                }
                var userMapping = UserMappingsRepository.Instance.GetUserMapping("PortalId", settings.UseGlobalSettings ? -1 : PortalSettings.PortalId);
                if (userMapping != null && !string.IsNullOrEmpty(userMapping.GetB2cCustomAttributeName(PortalSettings.PortalId)))
                {
                    if (!string.IsNullOrEmpty(filter))
                    {
                        filter += " and ";
                    }
                    filter += $"{userMapping.GetB2cCustomAttributeName(PortalSettings.PortalId)} eq {PortalSettings.PortalId}";
                }
                if (!string.IsNullOrEmpty(filter))
                {
                    query = $"$filter={filter}";
                }

                var customAttributes = Utils.GetTabModuleSetting(ActiveModule.TabModuleID, "CustomFields").Replace(" ", "");

                var opId     = Guid.NewGuid().ToString();
                var filename = Path.Combine(Path.GetTempPath(), $"{opId}.tmp");
                File.AppendAllText(filename, $"userPrincipalName,displayName,surname,givenName,issuer,mail,objectId,userType,jobTitle,department,accountEnabled,usageLocation,streetAddress,state,country,physicalDeliveryOfficeName,city,postalCode,telephoneNumber,mobile,ageGroup,legalAgeGroupClassification{(!string.IsNullOrEmpty(customAttributes) ? "," + customAttributes : "")}\n", System.Text.Encoding.UTF8);
                var users = graphClient.GetAllUsers(query);
                while (users.Values.Count > 0)
                {
                    foreach (var user in users.Values)
                    {
                        var mail     = user.Mail ?? user.OtherMails?.FirstOrDefault() ?? user.SignInNames?.FirstOrDefault()?.Value;
                        var userLine = $"{user.UserPrincipalName},{user.DisplayName},{user.Surname},{user.GivenName},{user.UserIdentities?.FirstOrDefault()?.Issuer},{mail},{user.ObjectId},{user.UserType},{user.JobTitle},{user.Department},{user.AccountEnabled},{user.UsageLocation},{user.StreetAddress},{user.State},{user.Country},\"{user.OfficeLocation}\",{user.City},{user.PostalCode},{user.BusinessPhones?.FirstOrDefault()},{user.MobilePhone},{user.AgeGroup},{user.LegalAgeGroupClassification}";

                        foreach (string attr in customAttributes.Split(','))
                        {
                            userLine += ",";
                            var extensionName = $"extension_{settings.B2cApplicationId.Replace("-", "")}_{attr}";
                            if (user?.AdditionalData != null && user.AdditionalData.ContainsKey(extensionName))
                            {
                                userLine += $"{user.AdditionalData[extensionName]}";
                            }
                        }

                        userLine += "\n";
                        File.AppendAllText(filename, userLine, System.Text.Encoding.UTF8);
                    }
                    if (string.IsNullOrEmpty(users.ODataNextLink))
                    {
                        break;
                    }
                    users = graphClient.GetNextUsers(users.ODataNextLink);
                }

                // Return the impersonation URL
                var url = Request.RequestUri.ToString().ToLowerInvariant();
                url = url.Substring(0, url.IndexOf("/export")) + "/downloadusers?id=" + opId;
                return(Request.CreateResponse(HttpStatusCode.OK, new
                {
                    downloadUrl = url
                }));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }