Exemplo n.º 1
0
        public async Task <IActionResult> Index()
        {
            var response = await _graphClient.GetAllUsersAsync();

            var accounts = GraphAccounts.Parse(response);

            return(View(accounts.value.Select(x => new UserViewModel(x))));
        }
Exemplo n.º 2
0
        static async Task Main(string[] args)
        {
            var tenantName    = "";
            var applicationId = "";
            var clientSecret  = "";

            var storageName = "";
            var storagekey  = "";

            var b2cGraphClient = new B2CGraphClient(tenantName, applicationId, clientSecret);

            var response = await b2cGraphClient.GetAllUsersAsync();

            var accounts = GraphAccounts.Parse(response);

            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageName, storagekey), true);

            //Client
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            //Table
            CloudTable table = tableClient.GetTableReference("Ticket");

            TableQuery <TicketTableEntity> query = new TableQuery <TicketTableEntity>();

            List <TicketTableEntity> results           = new List <TicketTableEntity>();
            TableContinuationToken   continuationToken = null;

            do
            {
                TableQuerySegment <TicketTableEntity> queryResults =
                    await table.ExecuteQuerySegmentedAsync(query, continuationToken);

                continuationToken = queryResults.ContinuationToken;
                results.AddRange(queryResults.Results);
            } while (continuationToken != null);

            using (var textWriter = new StreamWriter("accounts.csv"))
            {
                var csv = new CsvWriter(textWriter);

                csv.WriteHeader <CsvItem>();
                csv.NextRecord();

                foreach (var account in accounts.value)
                {
                    var tickets = results.Where(x => x.AttendeeId == account.Id);

                    if (tickets.Count() == 0)
                    {
                        var item = new CsvItem
                        {
                            Id        = account.Id,
                            Email     = account.OtherMails.FirstOrDefault(),
                            FirstName = account.GivenName,
                            LastName  = account.Surname,
                        };
                        csv.WriteRecord(item);
                        csv.NextRecord();
                    }

                    foreach (var ticket in tickets)
                    {
                        var item = new CsvItem
                        {
                            Id          = account.Id,
                            Email       = account.OtherMails.FirstOrDefault(),
                            FirstName   = account.GivenName,
                            LastName    = account.Surname,
                            TicketType  = ticket.TicketType,
                            CouponCode  = ticket.CouponCode,
                            IsPayed     = ticket.IsPayed,
                            PaymentType = ticket.PaymentType,
                            Price       = ticket.Price,
                            WorkshopId  = ticket.WorkshopId,
                            City        = account.city,
                            Company     = account.extension_d6245cc8578e4908b91662ccd12132e2_Company,
                            JobTitle    = account.jobTitle
                        };

                        csv.WriteRecord(item);
                        csv.NextRecord();
                    }
                }
                csv.Flush();
                csv.Dispose();
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                log.LogInformation("Request started");
                string           requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                ChangeEmailModel data        = JsonConvert.DeserializeObject <ChangeEmailModel>(requestBody);
                log.LogInformation(requestBody);

                string         tenant       = _appSettings.B2CTenantId;                       // Environment.GetEnvironmentVariable("B2CTenantId", EnvironmentVariableTarget.Process);
                string         clientId     = _appSettings.B2CGraphAccessClientId.ToString(); // Environment.GetEnvironmentVariable("B2CGraphAccessClientId", EnvironmentVariableTarget.Process);
                string         clientSecret = _appSettings.B2CGraphAccessClientSecret;        // Environment.GetEnvironmentVariable("B2CGraphAccessClientSecret", EnvironmentVariableTarget.Process);
                B2CGraphClient client       = new B2CGraphClient(clientId, clientSecret, tenant);

                var newUser = await client.GetAllUsersAsync("$filter=signInNames/any(x:x/value eq '" + HttpUtility.UrlEncode(data.NewEmail) + "')");

                UserDetailsModel newUserDetails = JsonConvert.DeserializeObject <UserDetailsModel>(newUser);

                if (newUserDetails.value.Count > 0)
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Sorry, This email already exists",
                    }));
                }

                var currentUser = await client.GetUserByObjectId(data.ObjectId);

                if (!String.IsNullOrEmpty(currentUser))
                {
                    UserValueModel user = JsonConvert.DeserializeObject <UserValueModel>(currentUser);
                    log.LogInformation(currentUser);

                    if (user == null)
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, This user doesn't exists.",
                        }));
                    }

                    bool updateResult = false;

                    if (!data.IsResend)
                    {
                        var    extensionAppId = _appSettings.ExtensionAppId;// Environment.GetEnvironmentVariable("ExtensionAppId", EnvironmentVariableTarget.Process);
                        string json           = "{\"extension_" + extensionAppId + "_IsEmailChangeRequested\":\"true\",\"extension_" + extensionAppId + "_NewEmail\":\"" + data.NewEmail + "\"}";
                        try
                        {
                            updateResult = await client.UpdateUser(data.ObjectId, json);
                        }
                        catch (Exception)
                        {
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "Sorry, something happened unexpectedly while updating AD user.",
                            }));
                        }
                    }

                    if (updateResult || data.IsResend)
                    {
                        var accountActivationEmailExpiryInSeconds = _appSettings.AccountActivationEmailExpiryInSeconds;// Convert.ToInt32(Environment.GetEnvironmentVariable("AccountActivationEmailExpiryInSeconds", EnvironmentVariableTarget.Process));


                        string token = TokenBuilder.BuildIdToken(user.signInNames.FirstOrDefault().value, data.NewEmail, DateTime.UtcNow.AddSeconds(accountActivationEmailExpiryInSeconds), req.Scheme, req.Host.Value, req.PathBase.Value, data.ObjectId, "changeemail", _appSettings.ClientSigningKey, _appSettings.RelyingPartyAppClientId.ToString());

                        string b2cURL         = _appSettings.B2CAuthorizationUrl;                // Environment.GetEnvironmentVariable("B2CAuthorizationUrl", EnvironmentVariableTarget.Process);
                        string b2cTenant      = _appSettings.B2CTenant;                          // Environment.GetEnvironmentVariable("B2CTenant", EnvironmentVariableTarget.Process);
                        string b2cPolicyId    = _appSettings.B2CChangeEmailPolicy;               // Environment.GetEnvironmentVariable("B2CChangeEmailPolicy", EnvironmentVariableTarget.Process);
                        string b2cClientId    = _appSettings.RelyingPartyAppClientId.ToString(); // Environment.GetEnvironmentVariable("RelyingPartyAppClientId", EnvironmentVariableTarget.Process);
                        string b2cRedirectUri = _appSettings.B2CRedirectUri.ToString();          // Environment.GetEnvironmentVariable("B2CRedirectUri", EnvironmentVariableTarget.Process);
                        string url            = UrlBuilder.BuildUrl(token, b2cURL, b2cTenant, b2cPolicyId, b2cClientId, b2cRedirectUri);

                        string htmlTemplateOldEmail = _appSettings.NotifyEmailChangeConfirmationEmailOldEmailTemplateId.ToString(); // Environment.GetEnvironmentVariable("NotifyEmailChangeConfirmationEmailOldEmailTemplateId", EnvironmentVariableTarget.Process);
                        string htmlTemplateNewEmail = _appSettings.NotifyEmailChangeConfirmationEmailNewEmailTemplateId.ToString(); //Environment.GetEnvironmentVariable("NotifyEmailChangeConfirmationEmailNewEmailTemplateId", EnvironmentVariableTarget.Process);

                        bool       result2 = false;
                        EmailModel model   = new EmailModel
                        {
                            EmailTemplate   = htmlTemplateNewEmail,
                            To              = data.NewEmail.ToString(),
                            Personalisation = new Dictionary <string, dynamic>
                            {
                                { "name", user.givenName },
                                { "link", url }
                            }
                        };

                        var result1 = EmailService.Send(_appSettings.NotifyApiKey, model);

                        if (!data.IsResend)
                        {
                            model = new EmailModel
                            {
                                EmailTemplate   = htmlTemplateOldEmail,
                                To              = user.signInNames.FirstOrDefault().value,
                                Personalisation = new Dictionary <string, dynamic>
                                {
                                    { "name", user.givenName }
                                }
                            };

                            result2 = EmailService.Send(_appSettings.NotifyApiKey, model);
                        }
                        else
                        {
                            result2 = true;
                        }

                        if (result1 && result2 & data.SendTokenBackRequired)
                        {
                            return((ActionResult) new OkObjectResult(new { id_token_hint = token }));
                        }

                        return(result1 && result2
                            ? (ActionResult) new OkObjectResult(true)
                            : new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Failed to sent email, please contact support."
                        }));
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, Something happened unexpectedly. Please try after sometime."
                        }));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Sorry, This user doesn't exists.",
                    }));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, Something happened unexpectedly. Please try after sometime.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }