Exemple #1
0
        public IEnumerable <ScopeDto> GetAll()
        {
            using (var context = RepositoriesFactory.CreateContext())
            {
                var scopes    = new List <Scope>();
                var rsRepo    = RepositoriesFactory.GetRessourceServerRepository(context);
                var scopeRepo = RepositoriesFactory.GetScopeRepository(context);

                var validRs = rsRepo.GetAll().Where(rs => rs.IsValid.Equals(true)).Select(rs => rs.Id).ToList();

                scopes = scopeRepo.GetAll().Where(s => validRs.Contains(s.RessourceServerId)).ToList();

                return(scopes.ToDto());
            }
        }
Exemple #2
0
        public void Delete(DeleteRessourceServerDto toDelete)
        {
            Logger.LogInformation(String.Format("Try to delete ressource server for user {0}", toDelete != null ? toDelete.UserName : String.Empty));

            Validate(toDelete);

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

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

                var myRs = rsRepo.GetById(toDelete.Id);
                if (myRs == null)
                {
                    throw new DaOAuthServiceException("DeleteRessourceServerRessourceServerNotFound");
                }

                foreach (var s in myRs.Scopes.ToList())
                {
                    foreach (var cs in clientScopeRepo.GetAllByScopeId(s.Id).ToList())
                    {
                        clientScopeRepo.Delete(cs);
                    }
                    scopeRepo.Delete(s);
                }

                rsRepo.Delete(myRs);

                context.Commit();
            }
        }
Exemple #3
0
        private bool CheckIfScopesAreAuthorizedForClient(string clientPublicId, string scope)
        {
            string[] scopes = null;
            if (!String.IsNullOrEmpty(scope))
            {
                scopes = scope.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            }
            else
            {
                return(true);
            }

            using (var context = RepositoriesFactory.CreateContext())
            {
                var scopeRepo    = RepositoriesFactory.GetScopeRepository(context);
                var clientScopes = scopeRepo.GetByClientPublicId(clientPublicId).Select(s => s.Wording.ToUpper(CultureInfo.CurrentCulture));

                if ((scopes == null || scopes.Length == 0) && clientScopes.Count() == 0) // client sans scope défini
                {
                    return(true);
                }

                if ((scopes == null || scopes.Length == 0) && clientScopes.Count() > 0) // client avec scopes définis
                {
                    return(false);
                }

                foreach (var s in scopes)
                {
                    if (!clientScopes.Contains <string>(s.ToUpper(CultureInfo.InvariantCulture)))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemple #4
0
        public RessourceServerDto Update(UpdateRessourceServerDto toUpdate)
        {
            Logger.LogInformation(String.Format("Try to update ressource server for user {0}", toUpdate != null ? toUpdate.UserName : String.Empty));

            Validate(toUpdate);

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

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

                var myRs = rsRepo.GetById(toUpdate.Id);
                if (myRs == null)
                {
                    throw new DaOAuthServiceException("UpdateRessourceServerRessourceServerNotFound");
                }

                myRs.IsValid     = toUpdate.IsValid;
                myRs.Name        = toUpdate.Name;
                myRs.Description = toUpdate.Description;

                rsRepo.Update(myRs);

                if (toUpdate.Scopes == null)
                {
                    toUpdate.Scopes = new List <UpdateRessourceServerScopesDto>();
                }

                if (myRs.Scopes == null)
                {
                    myRs.Scopes = new List <Scope>();
                }

                IList <int> newScopesTempIds = new List <int>();

                foreach (var toUpdateScope in toUpdate.Scopes)
                {
                    if (toUpdateScope.IdScope.HasValue && myRs.Scopes.Select(s => s.Id).Contains(toUpdateScope.IdScope.Value))
                    {
                        var myScope = myRs.Scopes.Where(s => s.Id.Equals(toUpdateScope.IdScope.Value)).First();
                        myScope.NiceWording = toUpdateScope.NiceWording;
                        myScope.Wording     = toUpdateScope.NiceWording.ToScopeWording(toUpdateScope.IsReadWrite);
                        scopeRepo.Update(myScope);
                    }
                    else if (!toUpdateScope.IdScope.HasValue)
                    {
                        var toAdd = new Scope()
                        {
                            NiceWording       = toUpdateScope.NiceWording,
                            Wording           = toUpdateScope.NiceWording.ToScopeWording(toUpdateScope.IsReadWrite),
                            RessourceServerId = myRs.Id
                        };
                        scopeRepo.Add(toAdd);
                        newScopesTempIds.Add(toAdd.Id);
                    }
                }
                foreach (var toDeleteScope in myRs.Scopes.Where(s => s.Id > 0 && !newScopesTempIds.Contains(s.Id))) // only existings scopes
                {
                    if (!toUpdate.Scopes.Where(s => s.IdScope.HasValue).Select(s => s.IdScope.Value).Contains(toDeleteScope.Id))
                    {
                        foreach (var cs in clientScopeRepo.GetAllByScopeId(toDeleteScope.Id).ToList())
                        {
                            clientScopeRepo.Delete(cs);
                        }
                        scopeRepo.Delete(toDeleteScope);
                    }
                }

                context.Commit();

                return(myRs.ToDto());
            }
        }
Exemple #5
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);
        }
Exemple #6
0
        public ClientDto Update(UpdateClientDto toUpdate)
        {
            IList <ValidationResult> ExtendValidation(UpdateClientDto toValidate)
            {
                var resource = this.GetErrorStringLocalizer();
                IList <ValidationResult> result = new List <ValidationResult>();

                if (toValidate.ReturnUrls == null || toValidate.ReturnUrls.Count() == 0)
                {
                    result.Add(new ValidationResult(resource["UpdateClientDtoDefaultReturnUrlRequired"]));
                }

                if (toValidate.ReturnUrls != null)
                {
                    foreach (var ur in toValidate.ReturnUrls)
                    {
                        if (!Uri.TryCreate(ur, UriKind.Absolute, out var u))
                        {
                            result.Add(new ValidationResult(resource["UpdateClientDtoReturnUrlIncorrect"]));
                        }
                    }
                }

                if (toValidate.ClientType != ClientTypeName.Confidential && toValidate.ClientType != ClientTypeName.Public)
                {
                    result.Add(new ValidationResult(resource["UpdateClientDtoTypeIncorrect"]));
                }

                if (!toValidate.ClientSecret.IsMatchClientSecretPolicy())
                {
                    result.Add(new ValidationResult(resource["UpdateClientDtoClientSecretDontMatchPolicy"]));
                }

                return(result);
            }

            Logger.LogInformation(String.Format("Try to update client for user {0}", toUpdate != null ? toUpdate.UserName : String.Empty));

            Validate(toUpdate, ExtendValidation);

            using (var context = RepositoriesFactory.CreateContext())
            {
                var resource = this.GetErrorStringLocalizer();

                var clientRepo          = RepositoriesFactory.GetClientRepository(context);
                var userClientRepo      = RepositoriesFactory.GetUserClientRepository(context);
                var scopeRepo           = RepositoriesFactory.GetScopeRepository(context);
                var userRepo            = RepositoriesFactory.GetUserRepository(context);
                var clientReturnUrlRepo = RepositoriesFactory.GetClientReturnUrlRepository(context);
                var clientScopeRepo     = RepositoriesFactory.GetClientScopeRepository(context);

                var myClient = clientRepo.GetById(toUpdate.Id);

                if (myClient == null || !myClient.IsValid)
                {
                    throw new DaOAuthServiceException(resource["UpdateClientInvalidClient"]);
                }

                var ucs = userClientRepo.GetAllByCriterias(toUpdate.UserName, toUpdate.Name, null, null, 0, 50);
                if (ucs != null && ucs.Count() > 0)
                {
                    var myUc = ucs.First();
                    if (myUc.ClientId != myClient.Id)
                    {
                        throw new DaOAuthServiceException(resource["UpdateClientNameAlreadyUsed"]);
                    }
                }

                var cl = clientRepo.GetByPublicId(toUpdate.PublicId);
                if (cl != null && cl.Id != myClient.Id)
                {
                    throw new DaOAuthServiceException(resource["UpdateClientpublicIdAlreadyUsed"]);
                }

                var scopes = scopeRepo.GetAll();
                if (toUpdate.ScopesIds != null)
                {
                    IList <int> ids = scopes.Select(s => s.Id).ToList();
                    foreach (var scopeId in toUpdate.ScopesIds)
                    {
                        if (!ids.Contains(scopeId))
                        {
                            throw new DaOAuthServiceException(resource["UpdateClientScopeDontExists"]);
                        }
                    }
                }

                var myUser = userRepo.GetByUserName(toUpdate.UserName);

                if (myUser == null || !myUser.IsValid)
                {
                    throw new DaOAuthServiceException(resource["UpdateClientInvalidUser"]);
                }

                var myUserClient = userClientRepo.
                                   GetUserClientByClientPublicIdAndUserName(myClient.PublicId, toUpdate.UserName);

                if (myUserClient == null || !myUserClient.Client.UserCreator.UserName.Equals(toUpdate.UserName, StringComparison.OrdinalIgnoreCase))
                {
                    throw new DaOAuthServiceException(resource["UpdateClientInvalidUser"]);
                }

                // update returns urls
                foreach (var ru in clientReturnUrlRepo.GetAllByClientPublicId(myClient.PublicId).ToList())
                {
                    clientReturnUrlRepo.Delete(ru);
                }

                foreach (var ru in toUpdate.ReturnUrls)
                {
                    clientReturnUrlRepo.Add(new ClientReturnUrl()
                    {
                        ClientId  = myClient.Id,
                        ReturnUrl = ru
                    });
                }

                // updates clients scopes
                foreach (var s in clientScopeRepo.GetAllByClientId(myClient.Id).ToList())
                {
                    clientScopeRepo.Delete(s);
                }
                if (toUpdate.ScopesIds != null)
                {
                    foreach (var s in toUpdate.ScopesIds)
                    {
                        clientScopeRepo.Add(new ClientScope()
                        {
                            ClientId = myClient.Id,
                            ScopeId  = s
                        });
                    }
                }

                // update client
                myClient.ClientSecret = toUpdate.ClientSecret;
                myClient.ClientTypeId = toUpdate.ClientType.Equals(
                    ClientTypeName.Confidential, StringComparison.OrdinalIgnoreCase)
                        ? (int)EClientType.CONFIDENTIAL : (int)EClientType.PUBLIC;
                myClient.Description = toUpdate.Description;
                myClient.Name        = toUpdate.Name;
                myClient.PublicId    = toUpdate.PublicId;

                clientRepo.Update(myClient);

                context.Commit();

                return(myClient.ToDto(true));
            }
        }