Beispiel #1
0
        public IActionResult Post(CreateRessourceServerDto infos)
        {
            infos.UserName = User.Identity.Name;
            var createdId  = _service.CreateRessourceServer(infos);
            var currentUrl = UriHelper.GetDisplayUrl(Request);

            return(Created($"{currentUrl}/{createdId}", null));
        }
Beispiel #2
0
        public void Init()
        {
            _service = new RessourceServerService()
            {
                Configuration          = FakeConfigurationHelper.GetFakeConf(),
                RepositoriesFactory    = new FakeRepositoriesFactory(),
                StringLocalizerFactory = new FakeStringLocalizerFactory(),
                Logger           = new FakeLogger(),
                EncryptonService = new FakeEncryptionService()
            };

            _adminUser = new User()
            {
                CreationDate = DateTime.Now,
                EMail        = "*****@*****.**",
                FullName     = "Samadmin",
                Id           = 123,
                IsValid      = true,
                Password     = new byte[] { 0 },
                UserName     = "******"
            };
            _normalUser = new User()
            {
                CreationDate = DateTime.Now,
                EMail        = "*****@*****.**",
                FullName     = "SamPasadmin",
                Id           = 124,
                IsValid      = true,
                Password     = new byte[] { 0 },
                UserName     = "******"
            };
            _invalidUser = new User()
            {
                CreationDate = DateTime.Now,
                EMail        = "*****@*****.**",
                FullName     = "SamPasValid",
                Id           = 125,
                IsValid      = false,
                Password     = new byte[] { 0 },
                UserName     = "******"
            };

            FakeDataBase.Instance.Users.Add(_adminUser);
            FakeDataBase.Instance.Users.Add(_normalUser);
            FakeDataBase.Instance.Users.Add(_invalidUser);

            _adminRole = new Role()
            {
                Id      = (int)ERole.ADMIN,
                Wording = RoleName.Administrator
            };
            _normalRole = new Role()
            {
                Id      = (int)ERole.USER,
                Wording = RoleName.User
            };
            FakeDataBase.Instance.Roles.Clear();
            FakeDataBase.Instance.Roles.Add(_adminRole);
            FakeDataBase.Instance.Roles.Add(_normalRole);

            FakeDataBase.Instance.UsersRoles.Add(new UserRole()
            {
                Id     = 345,
                RoleId = _adminRole.Id,
                UserId = _adminUser.Id
            });
            FakeDataBase.Instance.UsersRoles.Add(new UserRole()
            {
                Id     = 346,
                RoleId = _normalRole.Id,
                UserId = _normalUser.Id
            });

            _existingRessourceServer = new RessourceServer()
            {
                CreationDate = DateTime.Now,
                Description  = "I Exist",
                Id           = 999,
                IsValid      = true,
                Login        = "******",
                Name         = "existing",
                ServerSecret = new byte[] { 0 }
            };
            _validRessourceServer = new RessourceServer()
            {
                CreationDate = DateTime.Now,
                Description  = "I am valid, yeah",
                Id           = 1999,
                IsValid      = true,
                Login        = "******",
                Name         = "valid_rs_name",
                ServerSecret = new byte[] { 0 }
            };
            _invalidRessourceServer = new RessourceServer()
            {
                CreationDate = DateTime.Now,
                Description  = "I am not valid, sad",
                Id           = 2000,
                IsValid      = false,
                Login        = "******",
                Name         = "invalid_rs_name",
                ServerSecret = new byte[] { 0 }
            };
            FakeDataBase.Instance.RessourceServers.Add(_existingRessourceServer);
            FakeDataBase.Instance.RessourceServers.Add(_validRessourceServer);
            FakeDataBase.Instance.RessourceServers.Add(_invalidRessourceServer);

            _existingScope = new Scope()
            {
                Id = 789,
                RessourceServerId = _existingRessourceServer.Id,
                NiceWording       = "I Exist",
                Wording           = "RW_I_Exist"
            };
            FakeDataBase.Instance.Scopes.Add(_existingScope);

            _createDto = new CreateRessourceServerDto()
            {
                Description    = "Test ressource server",
                Login          = "******",
                Name           = "R-Serv",
                Password       = "******",
                RepeatPassword = "******",
                Scopes         = new List <CreateRessourceServerScopesDto>()
                {
                    new CreateRessourceServerScopesDto()
                    {
                        IsReadWrite = true,
                        NiceWording = "scope1 nice wording"
                    },
                    new CreateRessourceServerScopesDto()
                    {
                        IsReadWrite = false,
                        NiceWording = "scope2 another nice wording"
                    },
                    new CreateRessourceServerScopesDto()
                    {
                        IsReadWrite = true,
                        NiceWording = "scope3 juste another nice wording"
                    }
                },
                UserName = _adminUser.UserName
            };
        }
Beispiel #3
0
        public async Task Post_Should_Create_Ressource_Server()
        {
            var scopeIsReadWrite = true;

            var toCreateRessourceServer = new CreateRessourceServerDto()
            {
                Description    = "new ressource server",
                Login          = "******",
                Name           = "newRs",
                Password       = "******",
                RepeatPassword = "******",
                Scopes         = new List <CreateRessourceServerScopesDto>()
                {
                    new CreateRessourceServerScopesDto()
                    {
                        IsReadWrite = scopeIsReadWrite,
                        NiceWording = "a new scope"
                    }
                }
            };

            var httpResponseMessage = await _client.PostAsJsonAsync("ressourcesServers", toCreateRessourceServer);

            Assert.AreEqual(HttpStatusCode.Created, httpResponseMessage.StatusCode);
            Assert.IsTrue(httpResponseMessage.Headers.Contains("location"));

            var location = httpResponseMessage.Headers.GetValues("location").Single();

            Assert.IsTrue(location.Length > 0);

            var ressourceServerId = Int32.Parse(location.Split('/', StringSplitOptions.RemoveEmptyEntries).Last());

            RessourceServer myNewRessourceServer = null;
            Scope           myNewScopes          = null;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                myNewRessourceServer = context.RessourceServers.Where(c => c.Id.Equals(ressourceServerId)).SingleOrDefault();
                myNewScopes          = context.Scopes.Where(s => s.RessourceServerId.Equals(ressourceServerId)).SingleOrDefault();
            }

            Assert.IsNotNull(myNewRessourceServer);

            Assert.AreEqual(toCreateRessourceServer.Description, myNewRessourceServer.Description);
            Assert.AreEqual(toCreateRessourceServer.Login, myNewRessourceServer.Login);
            Assert.AreEqual(toCreateRessourceServer.Name, myNewRessourceServer.Name);

            var encryptionServce = new EncryptionService();

            Assert.IsTrue(encryptionServce.AreEqualsSha256(
                              String.Concat(GuiApiTestStartup.Configuration.PasswordSalt, toCreateRessourceServer.Password),
                              myNewRessourceServer.ServerSecret));

            Assert.IsTrue(myNewRessourceServer.IsValid);
            Assert.AreEqual(DateTime.Now.Date, myNewRessourceServer.CreationDate.Date);

            Assert.IsNotNull(myNewScopes);
            Assert.AreEqual(toCreateRessourceServer.Scopes.Single().NiceWording, myNewScopes.NiceWording);
            Assert.AreEqual(ressourceServerId, myNewScopes.RessourceServerId);
            Assert.IsTrue(myNewScopes.Wording.Length > 0);

            if (scopeIsReadWrite)
            {
                Assert.IsTrue(myNewScopes.Wording.StartsWith("RW_"));
            }
            else
            {
                Assert.IsTrue(myNewScopes.Wording.StartsWith("R_"));
            }
        }
Beispiel #4
0
        public int CreateRessourceServer(CreateRessourceServerDto toCreate)
        {
            var rsId = 0;

            IList <ValidationResult> ExtendValidation(CreateRessourceServerDto toValidate)
            {
                var resource = this.GetErrorStringLocalizer();
                IList <ValidationResult> result = new List <ValidationResult>();

                if (!String.IsNullOrEmpty(toCreate.Password) &&
                    !toCreate.Password.Equals(toCreate.RepeatPassword, StringComparison.Ordinal))
                {
                    result.Add(new ValidationResult(resource["CreateRessourceServerPasswordDontMatch"]));
                }

                if (!toValidate.Password.IsMatchPasswordPolicy())
                {
                    result.Add(new ValidationResult(resource["CreateRessourceServerPasswordPolicyFailed"]));
                }

                // check empties or multiple scopes names
                if (toValidate.Scopes != null)
                {
                    if (toValidate.Scopes.Where(s => String.IsNullOrWhiteSpace(s.NiceWording)).Any())
                    {
                        result.Add(new ValidationResult(resource["CreateRessourceServerEmptyScopeWording"]));
                    }

                    if (toValidate.Scopes.Where(s => !String.IsNullOrWhiteSpace(s.NiceWording)).GroupBy(s => s.NiceWording.ToUpper()).Where(x => x.Count() > 1).Any())
                    {
                        result.Add(new ValidationResult(resource["CreateRessourceServerMultipleScopeWording"]));
                    }
                }

                return(result);
            }

            Logger.LogInformation(String.Format("Try to create ressource server for user {0}", toCreate != null ? toCreate.UserName : String.Empty));

            Validate(toCreate, ExtendValidation);

            using (var context = RepositoriesFactory.CreateContext())
            {
                var userRepo  = RepositoriesFactory.GetUserRepository(context);
                var rsRepo    = RepositoriesFactory.GetRessourceServerRepository(context);
                var scopeRepo = RepositoriesFactory.GetScopeRepository(context);

                var myUser = userRepo.GetByUserName(toCreate.UserName);
                if (myUser == null || !myUser.IsValid)
                {
                    throw new DaOAuthServiceException("CreateRessourceServerInvalidUserName");
                }
                if (myUser.UsersRoles.FirstOrDefault(r => r.RoleId.Equals((int)ERole.ADMIN)) == null)
                {
                    throw new DaOAuthServiceException("CreateRessourceServerNonAdminUserName");
                }

                var existingRs = rsRepo.GetByLogin(toCreate.Login);
                if (existingRs != null)
                {
                    throw new DaOAuthServiceException("CreateRessourceServerExistingLogin");
                }

                // create ressource server
                var myRs = new RessourceServer()
                {
                    CreationDate = DateTime.Now,
                    Description  = toCreate.Description,
                    IsValid      = true,
                    Login        = toCreate.Login,
                    Name         = toCreate.Name,
                    ServerSecret = EncryptonService.Sha256Hash(string.Concat(Configuration.PasswordSalt, toCreate.Password))
                };
                rsId = rsRepo.Add(myRs);

                // check for existing scope, if ok, create
                if (toCreate.Scopes != null)
                {
                    foreach (var s in toCreate.Scopes)
                    {
                        var s1 = s.NiceWording.ToScopeWording(true);
                        var s2 = s.NiceWording.ToScopeWording(false);

                        var scope = scopeRepo.GetByWording(s1);
                        if (scope != null)
                        {
                            throw new DaOAuthServiceException("CreateRessourceServerExistingScope");
                        }

                        scope = scopeRepo.GetByWording(s2);
                        if (scope != null)
                        {
                            throw new DaOAuthServiceException("CreateRessourceServerExistingScope");
                        }

                        scope = new Scope()
                        {
                            NiceWording       = s.NiceWording,
                            Wording           = s.NiceWording.ToScopeWording(s.IsReadWrite),
                            RessourceServerId = rsId
                        };

                        scopeRepo.Add(scope);
                    }
                }

                context.Commit();

                rsId = myRs.Id;
            }

            return(rsId);
        }