예제 #1
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model)
        {
            // Model is valid
            if (ModelState.IsValid)
            {
                // Ensure only create user if Kong consumer was created
                using (var transaction = _context.Database.BeginTransaction())
                {
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        var kongService    = new KongService();
                        var createConsumer = await kongService.CreateConsumer(user.Id);

                        if (createConsumer.IsSuccessStatusCode)
                        {
                            transaction.Commit();
                            return(Ok(new { succeeded = true }));
                        }
                        else
                        {
                            return(BadRequest(new { succeeded = false, errors = new string[] { "Cannot create Kong consumer." } }));
                        }
                    }

                    return(BadRequest(result));
                }
            }

            return(BadRequest(new { succeeded = false, errors = GetValidationErrors() }));
        }
        private async Task ConvergeServiceChildren(KongService existing, KongService target)
        {
            async Task PutRoute(KongRoute route, KongService service)
            {
                service.AssignParentId(route);
                await _kongWriter.PutRoute(route);
            }

            async Task DeleteRoute(KongRoute route)
            {
                await _kongWriter.DeleteRoute(route.Id);

                _deletedStats.Increment <KongPlugin>(route.Plugins.Count);
            }

            var parent = $"{KongService.ObjectName} {target}";

            await ConvergeChildrenPlugins(parent, existing, target);
            await ConvergeObjects(
                parent,
                KongRoute.ObjectName,
                existing?.Routes,
                target.Routes,
                DeleteRoute,
                x => PutRoute(x, target),
                x => PutRoute(x, target),
                (e, t) => ConvergeChildrenPlugins($"{KongRoute.ObjectName} {t} attached to {KongService.ObjectName} {target}", e, t));
        }
예제 #3
0
        public void Scenario4()
        {
            KongService service = null;

            this.Given(() =>
            {
                service = Fixture.Create <KongService>();
                GetMock <FakeHttpMessageHandler>()
                .Setup(x => x.Send(It.Is <HttpRequestMessage>(m => m.Method == HttpMethod.Get && m.RequestUri.PathAndQuery == $"/services/{service.Id}/routes")))
                .Returns(OkResponse(new PagedResponse <KongRoute>
                {
                    Data = service.Routes.ToArray()
                }));
            }, "An existing kong service with routes")
            .And(s => s.KongRespondsCorrectly(HttpMethod.Delete, $"/services/{service.Id}"), KongRespondsCorrectlyToMethodAtPathTextTemplate)
            .And(() =>
            {
                foreach (var serviceRoute in service.Routes)
                {
                    KongRespondsCorrectly(HttpMethod.Delete, $"/routes/{serviceRoute.Id}");
                }
            }, "kong responds correctly to deleting service routes")
            .When(async() => await Subject.DeleteService(service.Id), Invoking(nameof(KongAdminWriter.DeleteService)))
            .Then(() =>
            {
                foreach (var serviceRoute in service.Routes)
                {
                    GetMock <FakeHttpMessageHandler>()
                    .Verify(x => x.Send(It.Is <HttpRequestMessage>(m => m.Method == HttpMethod.Delete && m.RequestUri.PathAndQuery == $"/routes/{serviceRoute.Id}")));
                }
            }, "The service routes are deleted first")
            .BDDfy();
        }
예제 #4
0
 private static void PopulateServiceTree(KongService service, IReadOnlyCollection <KongRoute> routes, IReadOnlyCollection <KongPlugin> plugins)
 {
     service.Plugins = plugins.Where(x => x.ServiceId == service.Id).ToArray();
     service.Routes  = routes.Where(x => x.Service.Id == service.Id).ToArray();
     foreach (var serviceRoute in service.Routes)
     {
         serviceRoute.Plugins = plugins.Where(x => x.RouteId == serviceRoute.Id).ToArray();
     }
 }
예제 #5
0
        public static KongService AsTarget(this KongService kongService, bool modified = false)
        {
            var target = kongService.Clone();

            if (modified)
            {
                target.Host = Guid.NewGuid().ToString();
            }
            return(target);
        }
예제 #6
0
        public async Task AddService(KongService service)
        {
            var content  = service.ToJsonStringContent();
            var response = await HttpClient.PostAsync("/services/", content);

            var responseBody = await response.Content.ReadAsStringAsync();

            var added = JsonConvert.DeserializeObject <KongService>(responseBody);

            service.Id = added.Id;
        }
예제 #7
0
        public void Scenario2()
        {
            KongService service = null;

            this.Given(() => service = Fixture.Create <KongService>(), "An existing kong service")
            .And(s => s.KongRespondsCorrectly <KongService>(new HttpMethod("PATCH"), $"/services/{service.Id}", service.ToJsonStringContent(), x => x.WithIdAndCreatedAt()),
                 KongRespondsCorrectlyToMethodAtPathTextTemplate)
            .When(async() => await Subject.UpdateService(service), Invoking(nameof(KongAdminWriter.UpdateService)))
            .Then("it succeeds")
            .BDDfy();
        }
예제 #8
0
        public void Scenario3()
        {
            KongService service = null;

            this.Given(() => service = Fixture.Create <KongService>(), "A kong service")
            .And(s => s.KongRespondsCorrectly <KongService>(HttpMethod.Put, $"/services/{service.Id}", service.ToJsonStringContent()),
                 KongRespondsCorrectlyToMethodAtPathTextTemplate)
            .When(async() => await Subject.PutService(service), Invoking(nameof(KongAdminWriter.PutService)))
            .Then("it succeeds")
            .BDDfy();
        }
예제 #9
0
 private async Task ConvergeServiceChildren(KongService existing, KongService target)
 {
     await ConvergeChildrenPlugins(existing, target);
     await ConvergeObjects(
         existing?.Routes,
         target.Routes,
         x => _kongWriter.DeleteRoute(x.Id),
         x => _kongWriter.AddRoute(target.Id, x),
         null,
         ConvergeChildrenPlugins);
 }
예제 #10
0
        public void Scenario1()
        {
            KongService service = null;

            this.Given(() => service = Fixture.Build <KongService>().Without(x => x.Id).Create(), "A new kong service")
            .And(s => s.KongRespondsCorrectly <KongService>(HttpMethod.Post, "/services/", service.ToJsonStringContent(), x => x.WithIdAndCreatedAt()),
                 KongRespondsCorrectlyToMethodAtPathTextTemplate)
            .When(async() => await Subject.AddService(service), Invoking(nameof(KongAdminWriter.AddService)))
            .Then(() => service.Id.Should().NotBeNullOrWhiteSpace(), "the Id is set")
            .BDDfy();
        }
예제 #11
0
        private async Task ConvergeServiceChildren(KongService existing, KongService target)
        {
            var parent = $"{KongService.ObjectName} {target}";

            await ConvergeChildrenPlugins(parent, existing, target);
            await ConvergeObjects(
                parent,
                KongRoute.ObjectName,
                existing?.Routes,
                target.Routes,
                x => _kongWriter.DeleteRoute(x.Id),
                x => _kongWriter.AddRoute(target.Id, x),
                null,
                (e, t) => ConvergeChildrenPlugins($"{KongRoute.ObjectName} {t} attached to {KongService.ObjectName} {target}", e, t));
        }
예제 #12
0
        public async Task UpdateService(KongService service)
        {
            Log.Information("Updating service {name}", service.Name);
            var content = service.ToJsonStringContent();

            try
            {
                await HttpClient.PatchAsync($"/services/{service.Id}", content);
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                throw;
            }
        }
예제 #13
0
        public async Task AddService(KongService service)
        {
            Log.Information($"Adding service {service.Name}");
            var content = service.ToJsonStringContent();

            try
            {
                var response = await HttpClient.PostAsync("/services/", content);

                var responseBody = await response.Content.ReadAsStringAsync();

                var added = JsonConvert.DeserializeObject <KongService>(responseBody);
                service.Id = added.Id;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                throw;
            }
        }
예제 #14
0
        public async Task <IActionResult> Edit(string id, [FromBody] EditUserViewModel model)
        {
            var user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                return(NotFound());
            }

            string kongAction = "";

            if (user.LockoutEnd == DateTime.MaxValue && model.IsEnabled)
            {
                // Unlock user
                user.LockoutEnd = null;
                kongAction      = "create";
            }
            else if (user.LockoutEnd != DateTime.MaxValue && !model.IsEnabled)
            {
                // Lock user
                user.LockoutEnd = DateTime.MaxValue;
                kongAction      = "delete";
            }

            Utils.CopyProperties(model, user);

            if (ModelState.IsValid)
            {
                // Ensure only update user if Kong consumer was created or deleted
                using (var transaction = _context.Database.BeginTransaction())
                {
                    // Catch update database concurrency error
                    try
                    {
                        // if (newAvatar != null && newAvatar.Length > 0)
                        // {
                        //     // Todo: Validate upload files, resize images

                        //     // Catch save thumbnail error
                        //     try
                        //     {
                        //         var fileName = DateTime.Now.Ticks.ToString() + Path.GetExtension(newAvatar.FileName);

                        //         using (var stream = new FileStream(Path.Combine(_uploadPath, fileName), FileMode.Create))
                        //         {
                        //             // Copy new avatar
                        //             await newAvatar.CopyToAsync(stream);

                        //             // Delete old avatar
                        //             //System.IO.File.Delete(Path.Combine(_uploadPath, user.Avatar));

                        //             // Update new avatar
                        //             //user.Avatar = fileName;
                        //         }
                        //     }
                        //     catch
                        //     {
                        //         ModelState.AddModelError("Avatar", "Cannot save Avatar!");
                        //         return BadRequest(new { succeeded = false, errors = GetValidationErrors() });
                        //     }
                        // }

                        // Update User
                        await _userManager.UpdateAsync(user);
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!UserExists(user.Id))
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }

                    var kongService            = new KongService();
                    HttpResponseMessage action = null;

                    if (kongAction == "create")
                    {
                        action = await kongService.CreateConsumer(id);
                    }
                    else if (kongAction == "delete")
                    {
                        action = await kongService.DeleteConsumer(id);
                    }

                    if (action != null && !action.IsSuccessStatusCode)
                    {
                        return(BadRequest(new { succeeded = false, errors = new string[] { $"Cannot {kongAction} Kong consumer." } }));
                    }

                    transaction.Commit();
                    return(Ok(new { succeeded = true }));
                }
            }

            return(BadRequest(new { succeeded = false, errors = GetValidationErrors() }));
        }
예제 #15
0
 public static bool CorrespondsToKongService(this KongPlugin kongPlugin, KongService kongService) =>
 kongPlugin.Service?.Id == kongService.Id &&
 !string.IsNullOrWhiteSpace(kongPlugin.Service?.Id) &&
 kongPlugin.Consumer?.Id == null &&
 kongPlugin.Route?.Id == null;
예제 #16
0
 public Task PutService(KongService service) => PutKongObject("/services", service);
예제 #17
0
 public Task AddService(KongService service) => Task.CompletedTask;
예제 #18
0
 protected void ARandomInstance() => Instance = this.Create <KongService>();
예제 #19
0
 public async Task UpdateService(KongService service)
 {
     var content = service.ToJsonStringContent();
     await HttpClient.PatchAsync($"/services/{service.Id}", content);
 }
예제 #20
0
 public Task UpdateService(KongService service) => Task.CompletedTask;
예제 #21
0
 public Task UpdateService(KongService service)
 {
     Log.Information($"Updating service {service.Name}");
     return(Task.CompletedTask);
 }
예제 #22
0
 public Task AddService(KongService service)
 {
     Log.Information("Adding service {name}", service.Name);
     service.Id = Guid.NewGuid().ToString();
     return(Task.CompletedTask);
 }