Beispiel #1
0
        public void UpdateUser(UpdateUserDto toUpdate)
        {
            IList <ValidationResult> ExtendValidation(UpdateUserDto toValidate)
            {
                var resource = this.GetErrorStringLocalizer();
                IList <ValidationResult> result = new List <ValidationResult>();

                using (var c = RepositoriesFactory.CreateContext())
                {
                    var repo = RepositoriesFactory.GetUserRepository(c);
                    var user = repo.GetByUserName(toUpdate.UserName);

                    if (user == null || !user.IsValid)
                    {
                        result.Add(new ValidationResult(resource["UpdateUserNoUserFound"]));
                    }

                    var errorResource = this.GetErrorStringLocalizer();
                    var getByMailUser = repo.GetByEmail(toValidate.EMail);
                    if (getByMailUser != null && getByMailUser.Id != user.Id)
                    {
                        result.Add(new ValidationResult(String.Format(errorResource["CreateUserEmailExists"], toValidate.EMail)));
                    }
                }

                return(result);
            }

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

            Validate(toUpdate, ExtendValidation);

            using (var c = RepositoriesFactory.CreateContext())
            {
                var repo = RepositoriesFactory.GetUserRepository(c);
                var user = repo.GetByUserName(toUpdate.UserName);

                user.BirthDate = toUpdate.BirthDate;
                user.EMail     = toUpdate.EMail;
                user.FullName  = toUpdate.FullName;

                repo.Update(user);

                c.Commit();
            }
        }
Beispiel #2
0
        public int CreateUserClient(CreateUserClientDto toCreate)
        {
            Validate(toCreate);

            var id = 0;

            var local = GetErrorStringLocalizer();

            using (var context = RepositoriesFactory.CreateContext())
            {
                var userClientRepo = RepositoriesFactory.GetUserClientRepository(context);
                var clientRepo     = RepositoriesFactory.GetClientRepository(context);
                var userRepo       = RepositoriesFactory.GetUserRepository(context);

                var user = userRepo.GetByUserName(toCreate.UserName);
                if (user == null || !user.IsValid)
                {
                    throw new DaOAuthServiceException(local["CreateUserClientInvalidUserName"]);
                }

                var client = clientRepo.GetByPublicId(toCreate.ClientPublicId);
                if (client == null || !client.IsValid)
                {
                    throw new DaOAuthServiceException(local["CreateUserClientInvalidClientPublicId"]);
                }

                var uc = userClientRepo.GetUserClientByClientPublicIdAndUserName(toCreate.ClientPublicId, toCreate.UserName);
                if (uc != null)
                {
                    throw new DaOAuthServiceException(local["CreateUserClientClientAlreadyRegister"]);
                }

                id = userClientRepo.Add(new UserClient()
                {
                    ClientId     = client.Id,
                    CreationDate = DateTime.Now,
                    IsActif      = toCreate.IsActif,
                    UserId       = user.Id
                });

                context.Commit();
            }

            return(id);
        }
Beispiel #3
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();
            }
        }
Beispiel #4
0
        public UserDto GetUser(string userName)
        {
            Logger.LogInformation($"Try get user {userName}");

            UserDto result = null;

            using (var c = RepositoriesFactory.CreateContext())
            {
                var repo = RepositoriesFactory.GetUserRepository(c);
                var user = repo.GetByUserName(userName);

                if (user != null && user.IsValid)
                {
                    result = user.ToDto();
                }
            }

            return(result);
        }
Beispiel #5
0
        public void UpdateReturnUrl(UpdateReturnUrlDto toUpdate)
        {
            this.Validate(toUpdate);

            var resource = this.GetErrorStringLocalizer();

            if (!Uri.TryCreate(toUpdate.ReturnUrl, UriKind.Absolute, out var u))
            {
                throw new DaOAuthServiceException(resource["UpdateReturnUrlReturnUrlIncorrect"]);
            }

            using (var context = RepositoriesFactory.CreateContext())
            {
                var returnUrlRepo = RepositoriesFactory.GetClientReturnUrlRepository(context);
                var myReturnUrl   = returnUrlRepo.GetById(toUpdate.IdReturnUrl);

                if (myReturnUrl == null)
                {
                    throw new DaOAuthServiceException(resource["UpdateReturnUrlUnknowReturnUrl"]);
                }

                var userRepo = RepositoriesFactory.GetUserRepository(context);
                var user     = userRepo.GetByUserName(toUpdate.UserName);
                if (user == null || !user.IsValid)
                {
                    throw new DaOAuthServiceException(resource["UpdateReturnUrlInvalidUser"]);
                }

                var ucRepo = RepositoriesFactory.GetUserClientRepository(context);
                var uc     = ucRepo.GetUserClientByClientPublicIdAndUserName(myReturnUrl.Client.PublicId, toUpdate.UserName);
                if (uc == null)
                {
                    throw new DaOAuthServiceException(resource["UpdateReturnUrlBadUserNameOrClientId"]);
                }

                myReturnUrl.ReturnUrl = toUpdate.ReturnUrl;

                returnUrlRepo.Update(myReturnUrl);

                context.Commit();
            }
        }
Beispiel #6
0
        public void ChangeUserPassword(ChangePasswordDto infos)
        {
            Logger.LogInformation($"Change password from user {infos.UserName}");

            Validate(infos);

            using (var context = RepositoriesFactory.CreateContext())
            {
                var local    = this.GetErrorStringLocalizer();
                var userRepo = RepositoriesFactory.GetUserRepository(context);

                var user = userRepo.GetByUserName(infos.UserName);

                if (user == null || !user.IsValid)
                {
                    throw new DaOAuthServiceException(local["ChangeUserPasswordUserInvalid"]);
                }

                if (!EncryptionService.AreEqualsSha256(
                        String.Concat(Configuration.PasswordSalt, infos.OldPassword), user.Password))
                {
                    throw new DaOAuthServiceException(local["ChangeUserPasswordPasswordInvalid"]);
                }

                if (!infos.NewPassword.Equals(infos.NewPasswordRepeat, StringComparison.Ordinal))
                {
                    throw new DaOAuthServiceException(local["ChangeUserPasswordDifferentsNewPasswords"]);
                }

                if (!infos.NewPassword.IsMatchPasswordPolicy())
                {
                    throw new DaOAuthServiceException(local["ChangeUserPasswordNewPasswordDontMatchPolicy"]);
                }

                user.Password = EncryptionService.Sha256Hash(String.Concat(Configuration.PasswordSalt, infos.NewPassword));

                userRepo.Update(user);

                context.Commit();
            }
        }
Beispiel #7
0
        public IEnumerable <AdminUsrDto> Search(AdminUserSearchDto criterias)
        {
            Validate(criterias, ExtendValidationSearchCriterias);

            IList <User> users = null;

            using (var context = RepositoriesFactory.CreateContext())
            {
                var userRepo = RepositoriesFactory.GetUserRepository(context);

                users = userRepo.GetAllByCriterias(criterias.UserName, criterias.Email, criterias.IsValid,
                                                   criterias.Skip, criterias.Limit).ToList();
            }

            if (users != null)
            {
                return(users.ToAdminDto());
            }

            return(new List <AdminUsrDto>());
        }
Beispiel #8
0
        public void ActivateUser(string userName)
        {
            Logger.LogInformation($"Try to activate user {userName}");

            using (var c = RepositoriesFactory.CreateContext())
            {
                var repo  = RepositoriesFactory.GetUserRepository(c);
                var user  = repo.GetByUserName(userName);
                var local = this.GetErrorStringLocalizer();

                if (user == null || user.IsValid)
                {
                    throw new DaOAuthServiceException(local["DeleteUserNoUserFound"]);
                }

                user.IsValid = true;
                repo.Update(user);

                c.Commit();
            }
        }
Beispiel #9
0
        private IList <ValidationResult> ExtendValidationSearchCriterias(UserClientSearchDto c)
        {
            var resource = this.GetErrorStringLocalizer();
            IList <ValidationResult> result = new List <ValidationResult>();

            using (var context = RepositoriesFactory.CreateContext())
            {
                var userRepo = RepositoriesFactory.GetUserRepository(context);
                var user     = userRepo.GetByUserName(c.UserName);
                if (user == null || !user.IsValid)
                {
                    result.Add(new ValidationResult(String.Format(resource["SearchClientInvalidUser"], c)));
                }
            }

            if (c.Limit - c.Skip > 50)
            {
                result.Add(new ValidationResult(String.Format(resource["SearchClientAskTooMuch"], c)));
            }

            return(result);
        }
Beispiel #10
0
        public UserDto GetUser(LoginUserDto credentials)
        {
            Logger.LogInformation($"Try to log user {credentials.UserName}");

            Validate(credentials);

            UserDto result = null;

            using (var c = RepositoriesFactory.CreateContext())
            {
                var repo = RepositoriesFactory.GetUserRepository(c);
                var user = repo.GetByUserName(credentials.UserName);

                if (user != null && user.IsValid && EncryptionService.AreEqualsSha256(
                        String.Concat(Configuration.PasswordSalt, credentials.Password), user.Password))
                {
                    result = user.ToDto();
                    Logger.LogInformation($"Log successfull for user {credentials.UserName}");
                }
            }

            return(result);
        }
Beispiel #11
0
        public UserDto ValidateUser(ValidateUserDto infos)
        {
            Logger.LogInformation($"Validate user {infos.UserName}");

            Validate(infos);

            using (var context = RepositoriesFactory.CreateContext())
            {
                var local    = this.GetErrorStringLocalizer();
                var userRepo = RepositoriesFactory.GetUserRepository(context);

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

                if (myUser == null)
                {
                    throw new DaOAuthServiceException(local["ValidateUserNoUserFound"]);
                }

                if (!infos.Token.Equals(myUser.ValidationToken, StringComparison.Ordinal))
                {
                    throw new DaOAuthServiceException(local["ValidateUserInvalidToken"]);
                }

                if (myUser.IsValid)
                {
                    throw new DaOAuthServiceException(local["ValidateUserEverValidated"]);
                }

                myUser.IsValid = true;

                userRepo.Update(myUser);

                context.Commit();

                return(myUser.ToDto());
            }
        }
Beispiel #12
0
        public void SetNewUserPassword(NewPasswordDto infos)
        {
            Logger.LogInformation($"Define a new password using JWT token {infos.Token}");

            Validate(infos);

            var local = this.GetErrorStringLocalizer();

            var tokenInfos = JwtService.ExtractMailToken(infos.Token);

            if (!tokenInfos.IsValid)
            {
                throw new DaOAuthServiceException(local["SetNewUserPasswordInvalidToken"]);
            }

            if (!infos.NewPassword.IsMatchPasswordPolicy())
            {
                throw new DaOAuthServiceException(local["SetNewUserPasswordNewPasswordDontMatchPolicy"]);
            }

            if (!infos.NewPassword.Equals(infos.NewPasswordRepeat, StringComparison.Ordinal))
            {
                throw new DaOAuthServiceException(local["SetNewUserPasswordDifferentsNewPasswords"]);
            }

            using (var context = RepositoriesFactory.CreateContext())
            {
                var userRepo = RepositoriesFactory.GetUserRepository(context);
                var user     = userRepo.GetByUserName(tokenInfos.UserName);

                user.Password = EncryptionService.Sha256Hash(String.Concat(Configuration.PasswordSalt, infos.NewPassword));

                userRepo.Update(user);

                context.Commit();
            }
        }
Beispiel #13
0
        public int CreateClient(CreateClientDto toCreate)
        {
            IList <ValidationResult> ExtendValidation(CreateClientDto toValidate)
            {
                var resource = this.GetErrorStringLocalizer();
                IList <ValidationResult> result = new List <ValidationResult>();

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

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

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

                using (var context = RepositoriesFactory.CreateContext())
                {
                    var userRepo = RepositoriesFactory.GetUserRepository(context);
                    var user     = userRepo.GetByUserName(toValidate.UserName);
                    if (user == null || !user.IsValid)
                    {
                        result.Add(new ValidationResult(String.Format(resource["CreateClientDtoInvalidUser"], toCreate.UserName)));
                    }

                    var userClientRepo = RepositoriesFactory.GetUserClientRepository(context);
                    if (!String.IsNullOrEmpty(toValidate.Name) && userClientRepo.GetAllByCriteriasCount(toValidate.UserName, toValidate.Name, null, null) > 0)
                    {
                        result.Add(new ValidationResult(resource["CreateClientDtoNameAlreadyUse"]));
                    }
                }

                return(result);
            }

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

            this.Validate(toCreate, ExtendValidation);

            using (var context = RepositoriesFactory.CreateContext())
            {
                var returnUrlRepo   = RepositoriesFactory.GetClientReturnUrlRepository(context);
                var clientRepo      = RepositoriesFactory.GetClientRepository(context);
                var userClientRepo  = RepositoriesFactory.GetUserClientRepository(context);
                var userRepo        = RepositoriesFactory.GetUserRepository(context);
                var clientScopeRepo = RepositoriesFactory.GetClientScopeRepository(context);

                var user = userRepo.GetByUserName(toCreate.UserName);

                var client = new Client()
                {
                    ClientSecret  = RandomService.GenerateRandomString(16),
                    ClientTypeId  = toCreate.ClientType.Equals(ClientTypeName.Confidential, StringComparison.OrdinalIgnoreCase) ? (int)EClientType.CONFIDENTIAL : (int)EClientType.PUBLIC,
                    CreationDate  = DateTime.Now,
                    Description   = toCreate.Description,
                    IsValid       = true,
                    Name          = toCreate.Name,
                    PublicId      = RandomService.GenerateRandomString(16),
                    UserCreatorId = user.Id
                };

                clientRepo.Add(client);

                foreach (var ur in toCreate.ReturnUrls)
                {
                    var clientReturnUrl = new ClientReturnUrl()
                    {
                        ReturnUrl = ur,
                        ClientId  = client.Id
                    };

                    returnUrlRepo.Add(clientReturnUrl);
                }

                var userClient = new UserClient()
                {
                    ClientId     = client.Id,
                    CreationDate = DateTime.Now,
                    IsActif      = true,
                    RefreshToken = String.Empty,
                    UserId       = user.Id
                };

                userClientRepo.Add(userClient);

                if (toCreate.ScopesIds != null)
                {
                    foreach (var sId in toCreate.ScopesIds)
                    {
                        clientScopeRepo.Add(new ClientScope()
                        {
                            ClientId = client.Id,
                            ScopeId  = sId
                        });
                    }
                }

                context.Commit();

                return(client.Id);
            }
        }
 public UserProvider GetUserProvider()
 {
     return(new UserProvider(_repositoriesFactory.GetUserRepository()));
 }
Beispiel #15
0
        public int CreateUser(CreateUserDto toCreate)
        {
            Logger.LogInformation($"Try creating a new user {toCreate.UserName}");

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

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

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

                using (var c = RepositoriesFactory.CreateContext())
                {
                    var repo = RepositoriesFactory.GetUserRepository(c);

                    if (repo.GetByUserName(toCreate.UserName) != null)
                    {
                        result.Add(new ValidationResult(String.Format(errorResource["CreateUserUserNameExists"], toCreate.UserName)));
                    }

                    if (repo.GetByEmail(toCreate.EMail) != null)
                    {
                        result.Add(new ValidationResult(String.Format(errorResource["CreateUserEmailExists"], toCreate.EMail)));
                    }
                }

                return(result);
            }

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

            Validate(toCreate, ExtendValidation);

            var idCreated    = 0;
            var mailResource = this.GetMailStringLocalizer();

            var u = new User()
            {
                BirthDate       = toCreate.BirthDate,
                CreationDate    = DateTime.Now,
                EMail           = toCreate.EMail,
                FullName        = toCreate.FullName,
                IsValid         = false,
                ValidationToken = RandomService.GenerateRandomString(32),
                Password        = EncryptionService.Sha256Hash(string.Concat(Configuration.PasswordSalt, toCreate.Password)),
                UserName        = toCreate.UserName
            };

            using (var c = RepositoriesFactory.CreateContext())
            {
                var repo = RepositoriesFactory.GetUserRepository(c);
                repo.Add(u);

                var userRoleRepo = RepositoriesFactory.GetUserRoleRepository(c);
                var roleRepo     = RepositoriesFactory.GetRoleRepository(c);

                var myRole = roleRepo.GetById((int)ERole.USER);
                if (myRole != null)
                {
                    userRoleRepo.Add(new UserRole()
                    {
                        RoleId = myRole.Id,
                        UserId = u.Id
                    });
                }

                var link = new Uri(String.Format(Configuration.ValidateAccountPageUrl, u.UserName, u.ValidationToken));

                MailService.SendEmail(new SendEmailDto()
                {
                    Body      = String.Format(mailResource["MailValidateAccountBody"], u.UserName, link.AbsoluteUri),
                    IsHtml    = true,
                    Receviers = new Dictionary <string, string>()
                    {
                        { u.EMail, u.EMail }
                    },
                    Sender  = new KeyValuePair <string, string>("*****@*****.**", "no reply"),
                    Subject = mailResource["MailValidateAccountSubject"]
                });

                c.Commit();
                idCreated = u.Id;
            }

            return(idCreated);
        }
Beispiel #16
0
        private TokenInfoDto GenerateTokenForPasswordGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal)
        {
            TokenInfoDto toReturn = null;

            if (String.IsNullOrWhiteSpace(tokenInfo.ParameterUsername))
            {
                throw new DaOAuthTokenException()
                      {
                          Error       = OAuthConvention.ErrorNameInvalidRequest,
                          Description = errorLocal["UserNameParameterError"]
                      };
            }

            if (String.IsNullOrWhiteSpace(tokenInfo.Password))
            {
                throw new DaOAuthTokenException()
                      {
                          Error       = OAuthConvention.ErrorNameInvalidRequest,
                          Description = errorLocal["PasswordParameterError"]
                      };
            }

            using (var context = RepositoriesFactory.CreateContext())
            {
                var clientRepo = RepositoriesFactory.GetClientRepository(context);
                var myClient   = clientRepo.GetByPublicId(tokenInfo.ClientPublicId);

                if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameUnauthorizedClient,
                              Description = errorLocal["UnauthorizedClient"]
                          };
                }

                var repo = RepositoriesFactory.GetUserRepository(context);
                var user = repo.GetByUserName(tokenInfo.ParameterUsername);

                if (user == null || !user.IsValid || !EncryptonService.AreEqualsSha256(
                        String.Concat(Configuration.PasswordSalt, tokenInfo.Password), user.Password))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameInvalidGrant,
                              Description = errorLocal["UserCredentialsIncorrects"]
                          };
                }

                if (!CheckIfScopesAreAuthorizedForClient(myClient.PublicId, tokenInfo.Scope))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameInvalidScope,
                              Description = errorLocal["UnauthorizedScope"]
                          };
                }

                toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, tokenInfo.ParameterUsername);

                context.Commit();
            }

            return(toReturn);
        }
Beispiel #17
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);
        }
Beispiel #18
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));
            }
        }
Beispiel #19
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());
            }
        }