Example #1
0
        public async Task TestDeleteClient_SuccessAsync(string id)
        {
            var clientToAdd = new ClientApiModel
            {
                Id   = id,
                Name = id,
                TopLevelSecurableItem = new SecurableItemApiModel
                {
                    Name = id
                }
            };

            var getResponse = await _browser.Post("/clients", with =>
            {
                with.HttpRequest();
                with.JsonBody(clientToAdd);
            });

            var delete = await _browser.Delete($"/clients/{id}", with =>
            {
                with.HttpRequest();
            });

            Assert.Equal(HttpStatusCode.NoContent, delete.StatusCode);
        }
Example #2
0
        public void UpdateClient(ClientApiModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            Client currentClient = _configurationDbContext.Clients
                                   .Include(client => client.ClientSecrets)
                                   .Include(client => client.RedirectUris)
                                   .FirstOrDefault(client => client.ClientId == model.ClientId);

            if (currentClient == null)
            {
                throw new ArgumentNullException(nameof(currentClient));
            }

            AddOrUpdateClientSecret(currentClient, model.ClientSecret);
            AddOrUpdateClientRedirectUrl(currentClient, model.RedirectUrl);

            currentClient.ClientId                     = model.ClientId;
            currentClient.ClientName                   = model.ClientName;
            currentClient.Enabled                      = model.Enabled;
            currentClient.AccessTokenLifetime          = model.AccessTokenLifetime;
            currentClient.AbsoluteRefreshTokenLifetime = model.RefreshTokenLifetime;

            _configurationDbContext.Clients.Update(currentClient);
            _configurationDbContext.SaveChanges();
        }
Example #3
0
        public async Task TestAddNewClient_FailAsync(string id)
        {
            var clientToAdd = new ClientApiModel
            {
                Id   = id,
                Name = id,
                TopLevelSecurableItem = new SecurableItemApiModel
                {
                    Name = id
                }
            };

            var postResponse = await _browser.Post("/clients", with =>
            {
                with.HttpRequest();
                with.JsonBody(clientToAdd);
            });

            Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);

            // Repeat
            postResponse = await _browser.Post("/clients", with =>
            {
                with.HttpRequest();
                with.JsonBody(clientToAdd);
            });

            Assert.Equal(HttpStatusCode.Conflict, postResponse.StatusCode);
            Assert.Contains(
                $"Client {id} already exists. Please provide a new client id",
                postResponse.Body.AsString());
        }
        public void AddClient_PreventsOverposting()
        {
            var clientsModule = CreateBrowser(new Claim(Claims.Scope, Scopes.ManageClientsScope),
                                              new Claim(Claims.Scope, Scopes.WriteScope));
            var clientToPost = new ClientApiModel
            {
                Id                    = "another-sample-app",
                Name                  = "Another Sample App",
                CreatedBy             = "someone",
                CreatedDateTimeUtc    = DateTime.UtcNow.AddDays(-45),
                ModifiedBy            = "someone",
                ModifiedDateTimeUtc   = DateTime.UtcNow.AddDays(-45),
                TopLevelSecurableItem = new SecurableItemApiModel
                {
                    Id   = Guid.NewGuid(),
                    Name = "somesecurable"
                }
            };
            var result = clientsModule.Post("/clients", with => with.JsonBody(clientToPost)).Result;

            Assert.Equal(HttpStatusCode.Created, result.StatusCode);
            var newClient = result.Body.DeserializeJson <ClientApiModel>();

            Assert.NotNull(newClient.TopLevelSecurableItem);
            Assert.Equal(clientToPost.Id, newClient.TopLevelSecurableItem.Name);
            Assert.NotEqual(clientToPost.CreatedDateTimeUtc, newClient.CreatedDateTimeUtc);
            Assert.NotEqual(clientToPost.ModifiedDateTimeUtc, newClient.ModifiedDateTimeUtc);
            Assert.NotEqual(clientToPost.TopLevelSecurableItem.Id, newClient.TopLevelSecurableItem.Id);
            Assert.True(string.IsNullOrEmpty(newClient.CreatedBy));
            Assert.True(string.IsNullOrEmpty(newClient.ModifiedBy));
        }
        public ActionResult Create()
        {
            var clientModel = new ClientApiModel
            {
                Enabled = true
            };

            return(View(ViewNames.AdminApiClientsCreate, clientModel));
        }
Example #6
0
        public async Task <ClientApiModel> AddClient(string accessToken, ClientApiModel clientModel)
        {
            var message = new HttpRequestMessage(HttpMethod.Post, new ClientRouteBuilder().Route)
                          .AddContent(clientModel)
                          .AddAcceptHeader()
                          .AddBearerToken(accessToken);

            return(await SendAndParseJson <ClientApiModel>(message).ConfigureAwait(false));
        }
        public async Task <IActionResult> Add([FromBody] ClientApiModel apiModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(new UnprocessableEntityResult());
            }

            await this.clientsRepository.Add(apiModel.ToDomainModel());

            return(new EntityCreatedResult());
        }
Example #8
0
        public async Task TestGetClients_SuccessAsync(string clientId1, string clientId2)
        {
            var getInitialCountResponse = await _browser.Get("/clients", with =>
            {
                with.HttpRequest();
            });

            Assert.Equal(HttpStatusCode.OK, getInitialCountResponse.StatusCode);
            var initialClients     = getInitialCountResponse.Body.DeserializeJson <IEnumerable <ClientApiModel> >();
            var initialClientCount = initialClients.Count();
            var clientIds          = new[] { clientId1, clientId2 };

            //add two clients
            foreach (var clientId in clientIds)
            {
                var client = new ClientApiModel {
                    Id = clientId, Name = clientId
                };

                var postResponse = await _browser.Post("/clients", with =>
                {
                    with.HttpRequest();
                    with.JsonBody(client);
                });

                Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
            }
            //confirm you can get two clients back
            var getResponse = await _browser.Get("/clients", with =>
            {
                with.HttpRequest();
            });

            Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
            var clients = getResponse.Body.DeserializeJson <IEnumerable <ClientApiModel> >();

            Assert.Equal(initialClientCount + 2, clients.Count());
            //delete one client
            var delete = await _browser.Delete($"/clients/{clientIds[0]}", with =>
            {
                with.HttpRequest();
            });

            Assert.Equal(HttpStatusCode.NoContent, delete.StatusCode);
            //confirm you get one client back
            getResponse = await _browser.Get("/clients", with =>
            {
                with.HttpRequest();
            });

            Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
            clients = getResponse.Body.DeserializeJson <IEnumerable <ClientApiModel> >();
            Assert.Equal(initialClientCount + 1, clients.Count());
        }
        public async Task <IActionResult> Edit(ClientApiModel model, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                _clientService.UpdateClient(model);

                SuccessNotification(_localizationService.GetResource("Plugins.Api.Admin.Client.Edit"));
                return(continueEditing ? RedirectToAction("Edit", new { id = model.Id }) : RedirectToAction("List"));
            }

            return(RedirectToAction("List"));
        }
        public ActionResult Create(ClientApiModel model, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                int clientId = _clientService.InsertClient(model);

                SuccessNotification(_localizationService.GetResource("Plugins.Api.Admin.Client.Created"));
                return(continueEditing ? RedirectToAction("Edit", new { id = clientId }) : RedirectToAction("List"));
            }

            return(RedirectToAction("List"));
        }
        public void AddClient_DuplicateReturnsConflict()
        {
            var clientsModule = CreateBrowser(new Claim(Claims.Scope, Scopes.ManageClientsScope),
                                              new Claim(Claims.Scope, Scopes.WriteScope));
            var clientToPost =
                new ClientApiModel {
                Id = "sample-fabric-app", Name = "Sample Fabric Client Application"
            };
            var result = clientsModule.Post("/clients", with => with.JsonBody(clientToPost)).Result;

            Assert.Equal(HttpStatusCode.Conflict, result.StatusCode);
        }
        public async Task <IActionResult> GetClient(string clientId)
        {
            var client = await this.clientsRepository.GetClient(clientId);

            if (client == null)
            {
                return(this.HttpNotFound());
            }

            var clientApiModel = new ClientApiModel(client);

            return(this.Ok(clientApiModel));
        }
Example #13
0
        public ActionResult Create()
        {
            var clientModel = new ClientApiModel
            {
                Enabled              = true,
                ClientSecret         = Guid.NewGuid().ToString(),
                ClientId             = Guid.NewGuid().ToString(),
                AccessTokenLifetime  = Configurations.DefaultAccessTokenExpiration,
                RefreshTokenLifetime = Configurations.DefaultRefreshTokenExpiration
            };

            return(View(ViewNames.AdminApiClientsCreate, clientModel));
        }
        public async Task <IActionResult> UpdateClient(string clientId, [FromBody] ClientApiModel apiModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(new UnprocessableEntityResult());
            }

            apiModel.Id = clientId;
            var client = apiModel.ToDomainModel();

            await this.clientsRepository.Update(client);

            return(new EntityCreatedResult());
        }
Example #15
0
        public async Task TestAddNewClient_SuccessAsync(string id)
        {
            var clientToAdd = new ClientApiModel
            {
                Id   = id,
                Name = id,
                TopLevelSecurableItem = new SecurableItemApiModel
                {
                    Name = id
                }
            };

            var postResponse = await _browser.Post("/clients", with =>
            {
                with.HttpRequest();
                with.JsonBody(clientToAdd);
            });


            var getResponse = await _browser.Get($"/clients/{id}", with =>
            {
                with.HttpRequest();
            });


            Assert.Equal(HttpStatusCode.Created, postResponse.StatusCode);
            Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
            Assert.Contains(id, getResponse.Body.AsString());

            var clientBrowser = _fixture.GetBrowser(GetPrincipalForClient(clientToAdd.Id), _storageProvider);

            var rolesResponse = await clientBrowser.Get($"/roles/{Domain.Defaults.Authorization.AppGrain}/{clientToAdd.Id}",
                                                        with =>
            {
                with.HttpRequest();
            });

            Assert.Equal(HttpStatusCode.OK, rolesResponse.StatusCode);

            var roles = JsonConvert.DeserializeObject <List <RoleApiModel> >(rolesResponse.Body.AsString());

            Assert.Single(roles);

            var permissions = roles.First().Permissions;

            Assert.Single(roles.First().Permissions);
            Assert.Equal(Domain.Defaults.Authorization.ManageAuthorizationPermissionName, permissions.First().Name);
        }
Example #16
0
        public void TestAddClient_InvalidContentTypeHeaderSet_BadRequestException()
        {
            var clientToAdd = new ClientApiModel {
                Id = "foo", Name = "foo"
            };

            var postResponse = _browser.Post("/clients", with =>
            {
                with.HttpRequest();
                with.Body(JsonConvert.SerializeObject(clientToAdd), "text/plain"); //default if nothing provided
            }).Result;

            Assert.Equal(HttpStatusCode.BadRequest, postResponse.StatusCode);
            Assert.Contains(
                "Content-Type header must be application/json or application/xml when attempting a POST or PUT",
                postResponse.Body.AsString());
        }
        public void AddClient_Successful()
        {
            var clientsModule = CreateBrowser(new Claim(Claims.Scope, Scopes.ManageClientsScope),
                                              new Claim(Claims.Scope, Scopes.WriteScope));
            var clientToPost = new ClientApiModel
            {
                Id   = "sample-fabric-app2",
                Name = "Sample Fabric App V2"
            };
            var result = clientsModule.Post("/clients", with => with.JsonBody(clientToPost)).Result;

            Assert.Equal(HttpStatusCode.Created, result.StatusCode);
            var newClient = result.Body.DeserializeJson <ClientApiModel>();

            Assert.NotNull(newClient.TopLevelSecurableItem);
            Assert.Equal(clientToPost.Id, newClient.TopLevelSecurableItem.Name);
            Assert.NotEqual(DateTime.MinValue, newClient.CreatedDateTimeUtc);
        }
Example #18
0
        //// GET: api/Postes
        //public List<PosteViewModel> GetPostes()
        //{
        //    //instance List de type PostesDansCategorie
        //    List<PosteViewModel> ListPos = new List<PosteViewModel>();
        //    // instance objet de PostesDansCategorie

        //    //recuperer tout les valeur de categories
        //    var pos = db.Postes.ToList();
        //    //boucler sur cat pour recuperer les categorie
        //    foreach (var p in pos)
        //    {
        //        //instance d'objet
        //        PosteViewModel pvm = new PosteViewModel();
        //        pvm.ID = p.ID;
        //        pvm.CategorieID = p.CategorieID;
        //        pvm.ClientID2 = p.ClientID2;
        //        pvm.Poste_title = p.Poste_title;
        //        pvm.Poste_image = p.Poste_image;
        //        pvm.Poste_description = p.Poste_description;
        //        pvm.Date_debut = p.Date_debut;
        //        pvm.Date_fin = p.Date_fin;
        //        pvm.Etat = p.Etat;
        //        ListPos.Add(pvm);
        //    }
        //    return (ListPos);
        //}

        public IHttpActionResult GetPostesAvis(int prend = 0, string option = "")
        {
            //instance List de type PostesDansCategorie
            List <PosteViewModelAvis> ListPos = new List <PosteViewModelAvis>();

            // instance objet de PostesDansCategorie

            if (option == "best")
            {
                //recuperer tout les valeur de categories
                // var pos1= db.Postes.OrderByDescending(p => p.Avis.Average(l => l.Note)).Take(prend).ToList();
                var pos = db.Postes.OrderByDescending(p => p.Avis.Average(l => l.Note)).Take(prend).ToList();;
                //boucler sur cat pour recuperer les categorie
                foreach (var p in pos)
                {
                    //instance d'objet
                    PosteViewModelAvis pvm = new PosteViewModelAvis();
                    pvm.ID                = p.ID;
                    pvm.CategorieID       = p.CategorieID;
                    pvm.ClientID2         = p.ClientID2;
                    pvm.Poste_title       = p.Poste_title;
                    pvm.Poste_image       = p.Poste_image;
                    pvm.Poste_description = p.Poste_description;
                    pvm.Date_debut        = p.Date_debut;
                    pvm.Date_fin          = p.Date_fin;
                    pvm.Etat              = p.Etat;
                    pvm.Pay               = p.Pay;
                    pvm.nombreAvis        = p.Avis.Count();
                    pvm.noteAvis          = (p.Avis.Average(f => f.Note)) / 2;
                    pvm.Categorie         = p.Categorie.Catégorie_title;
                    List <AvisViewModel> avm = new List <AvisViewModel>();
                    foreach (var a in p.Avis)
                    {
                        AvisViewModel amv = new AvisViewModel();
                        amv.Id          = a.Id;
                        amv.Nom         = a.Nom;
                        amv.Description = a.Description;
                        amv.Note        = a.Note;
                        amv.IdPoste     = a.IdPoste;
                        amv.DateAvi     = a.DateAvi;
                        amv.IdClient    = a.IdClient;
                        avm.Add(amv);
                    }

                    pvm.ClientID       = p.ClientID;
                    pvm.Client_Prenom  = p.Client.Client_Prenom;
                    pvm.Client_Nom     = p.Client.Client_Nom;
                    pvm.Client_image   = p.Client.Client_image;
                    pvm.Email          = p.Client.Email;
                    pvm.Client_adresse = p.Client.Client_adresse;

                    pvm.avis = avm;

                    ListPos.Add(pvm);
                }
            }

            else if (option == "date")
            {
                var pos = db.Postes.OrderByDescending(p => p.Date_CreationPost).Take(prend).ToList();
                //boucler sur cat pour recuperer les categorie
                foreach (var p in pos)
                {
                    //instance d'objet
                    PosteViewModelAvis pvm = new PosteViewModelAvis();
                    pvm.ID                = p.ID;
                    pvm.CategorieID       = p.CategorieID;
                    pvm.ClientID2         = p.ClientID2;
                    pvm.Poste_title       = p.Poste_title;
                    pvm.Poste_image       = p.Poste_image;
                    pvm.Poste_description = p.Poste_description;
                    pvm.Date_debut        = p.Date_debut;
                    pvm.Date_fin          = p.Date_fin;
                    pvm.Etat              = p.Etat;
                    pvm.nombreAvis        = p.Avis.Count();
                    pvm.noteAvis          = (p.Avis.Average(f => f.Note)) / 2;
                    List <AvisViewModel> avm = new List <AvisViewModel>();
                    foreach (var a in p.Avis)
                    {
                        AvisViewModel amv = new AvisViewModel();
                        amv.Id          = a.Id;
                        amv.Nom         = a.Nom;
                        amv.Description = a.Description;
                        amv.Note        = a.Note;
                        amv.IdPoste     = a.IdPoste;
                        amv.DateAvi     = a.DateAvi;
                        amv.IdClient    = a.IdClient;
                        avm.Add(amv);
                    }



                    pvm.ClientID       = p.ClientID;
                    pvm.Client_Prenom  = p.Client.Client_Prenom;
                    pvm.Client_Nom     = p.Client.Client_Nom;
                    pvm.Client_image   = p.Client.Client_image;
                    pvm.Email          = p.Client.Email;
                    pvm.Client_adresse = p.Client.Client_adresse;



                    pvm.avis = avm;

                    ListPos.Add(pvm);
                }
            }
            else
            {
                var pos = db.Postes.OrderBy(x => Guid.NewGuid()).Take(prend).ToList();
                //boucler sur cat pour recuperer les categorie
                foreach (var p in pos)
                {
                    //instance d'objet
                    PosteViewModelAvis pvm = new PosteViewModelAvis();
                    pvm.ID                = p.ID;
                    pvm.CategorieID       = p.CategorieID;
                    pvm.ClientID2         = p.ClientID2;
                    pvm.Poste_title       = p.Poste_title;
                    pvm.Poste_image       = p.Poste_image;
                    pvm.Poste_description = p.Poste_description;
                    pvm.Date_debut        = p.Date_debut;
                    pvm.Date_fin          = p.Date_fin;
                    pvm.Etat              = p.Etat;
                    pvm.nombreAvis        = p.Avis.Count();
                    pvm.noteAvis          = (p.Avis.Average(f => f.Note)) / 2;
                    List <AvisViewModel> avm = new List <AvisViewModel>();
                    foreach (var a in p.Avis)
                    {
                        AvisViewModel amv = new AvisViewModel();
                        amv.Id          = a.Id;
                        amv.Nom         = a.Nom;
                        amv.Description = a.Description;
                        amv.Note        = a.Note;
                        amv.IdPoste     = a.IdPoste;
                        amv.DateAvi     = a.DateAvi;
                        amv.IdClient    = a.IdClient;
                        avm.Add(amv);
                    }

                    ClientApiModel cam = new ClientApiModel();

                    cam.ID             = p.Client.ID;
                    cam.Client_Prenom  = p.Client.Client_Prenom;
                    cam.Client_Nom     = p.Client.Client_Nom;
                    cam.Client_image   = p.Client.Client_image;
                    cam.Email          = p.Client.Email;
                    cam.Client_adresse = p.Client.Client_adresse;

                    pvm.Client = cam;



                    pvm.avis = avm;

                    ListPos.Add(pvm);
                }
            }

            return(Ok(ListPos));
        }
Example #19
0
        public int InsertClient(ClientApiModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var client = new Client()
            {
                ClientId   = model.ClientId,
                Enabled    = model.Enabled,
                ClientName = model.ClientName,
                // Needed to be able to obtain refresh token.
                AllowOfflineAccess           = true,
                AccessTokenLifetime          = model.AccessTokenLifetime,
                AbsoluteRefreshTokenLifetime = model.RefreshTokenLifetime
            };

            AddOrUpdateClientSecret(client, model.ClientSecret);
            AddOrUpdateClientRedirectUrl(client, model.RedirectUrl);

            client.AllowedGrantTypes = new List <ClientGrantType>()
            {
                new ClientGrantType()
                {
                    Client    = client,
                    GrantType = OidcConstants.GrantTypes.AuthorizationCode
                },
                new ClientGrantType()
                {
                    Client    = client,
                    GrantType = OidcConstants.GrantTypes.RefreshToken
                },
                new ClientGrantType()
                {
                    Client    = client,
                    GrantType = OidcConstants.GrantTypes.JwtBearer
                },
                new ClientGrantType()
                {
                    Client    = client,
                    GrantType = OidcConstants.GrantTypes.ClientCredentials
                }
            };

            client.AllowedScopes = new List <ClientScope>()
            {
                new ClientScope()
                {
                    Client = client,
                    Scope  = "nop_api"
                }
            };

            client.Claims = new List <ClientClaim>()
            {
                new ClientClaim()
                {
                    Client = client,
                    Type   = JwtClaimTypes.Subject,
                    Value  = client.ClientId
                },
                new ClientClaim()
                {
                    Client = client,
                    Type   = JwtClaimTypes.Name,
                    Value  = client.ClientName
                }
            };

            _configurationDbContext.Clients.Add(client);
            _configurationDbContext.SaveChanges();

            return(client.Id);
        }
        public IActionResult Edit(int id)
        {
            ClientApiModel clientModel = _clientService.FindClientByIdAsync(id);

            return(View(ViewNames.AdminApiClientsEdit, clientModel));
        }