Пример #1
0
 protected IdentityResult Failed(Exception exception)
 {
     return(exception == null?IdentityResult.Failed() : IdentityResult.Failed(new IdentityError {
         Description = exception.Message
     }));
 }
Пример #2
0
 public async Task <IdentityResult> DeleteAsync(Role role, CancellationToken cancel) =>
 await(await PostAsync($"{Address}/Delete", role, cancel).ConfigureAwait(false))
 .Content
 .ReadAsAsync <bool>(cancel)
         ? IdentityResult.Success
         : IdentityResult.Failed();
Пример #3
0
 public async Task <IdentityResult> DeleteAsync(User user, CancellationToken cancellationToken)
 {
     return(IdentityResult.Failed());
 }
Пример #4
0
 public MockUserManager()
     : base(new FakeUserStore().Build().Object, new FakePasswordHasher().Build().Object)
 {
     _creationResult = IdentityResult.Failed();
 }
 private async Task <IdentityResult> UserAlreadyInRoleError(ApplicationUser user, string role)
 {
     Logger.LogWarning(5, "User {userId} is already in role {role}.", await GetUserIdAsync(user), role);
     return(IdentityResult.Failed(ErrorDescriber.UserAlreadyInRole(role)));
 }
        public async Task <IdentityResult> SeedDatabaseWithAdminUserAsync()
        {
            var adminUserSeed = _adminUserSeedOptions.Value.AdminUserSeed;

            adminUserSeed.CheckArgumentIsNull(nameof(adminUserSeed));

            var name     = adminUserSeed.Username;
            var password = adminUserSeed.Password;
            var email    = adminUserSeed.Email;
            var roleName = adminUserSeed.RoleName;

            var thisMethodName = nameof(SeedDatabaseWithAdminUserAsync);

            var adminUser = await _applicationUserManager.FindByNameAsync(name);

            if (adminUser != null)
            {
                _logger.LogInformation($"{thisMethodName}: adminUser already exists.");
                return(IdentityResult.Success);
            }

            //Create the `Admin` Role if it does not exist
            var adminRole = await _roleManager.FindByNameAsync(roleName);

            if (adminRole == null)
            {
                adminRole = new Role(roleName);
                var adminRoleResult = await _roleManager.CreateAsync(adminRole);

                if (adminRoleResult == IdentityResult.Failed())
                {
                    _logger.LogError($"{thisMethodName}: adminRole CreateAsync failed. {adminRoleResult.DumpErrors()}");
                    return(IdentityResult.Failed());
                }
            }
            else
            {
                _logger.LogInformation($"{thisMethodName}: adminRole already exists.");
            }

            adminUser = new User
            {
                UserName       = name,
                Email          = email,
                EmailConfirmed = true,
                IsEmailPublic  = true,
                LockoutEnabled = true
            };
            var adminUserResult = await _applicationUserManager.CreateAsync(adminUser, password);

            if (adminUserResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser CreateAsync failed. {adminUserResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            var setLockoutResult = await _applicationUserManager.SetLockoutEnabledAsync(adminUser, enabled : false);

            if (setLockoutResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser SetLockoutEnabledAsync failed. {setLockoutResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            var addToRoleResult = await _applicationUserManager.AddToRoleAsync(adminUser, adminRole.Name);

            if (addToRoleResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser AddToRoleAsync failed. {addToRoleResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            return(IdentityResult.Success);
        }
Пример #7
0
        public async Task <ActionResult> CreateUserInvitation([FromBody] UsersInvitation invitation)
        {
            var result = IdentityResult.Success;

            TryValidateModel(invitation);

            if (ModelState.IsValid)
            {
                var organizationId = WorkContext.CurrentUser?.Contact?.Organization?.Id;
                //If it is organization invitation need to check authorization for this action
                if (!string.IsNullOrEmpty(organizationId))
                {
                    var authorizationResult = await _authorizationService.AuthorizeAsync(User, null, SecurityConstants.Permissions.CanInviteUsers);

                    if (!authorizationResult.Succeeded)
                    {
                        return(Unauthorized());
                    }
                }

                foreach (var email in invitation.Emails)
                {
                    var user = await _userManager.FindByEmailAsync(email);

                    if (user == null)
                    {
                        user = new User
                        {
                            UserName = email,
                            StoreId  = WorkContext.CurrentStore.Id,
                            Email    = email,
                        };
                        var roles = invitation.Roles?.Select(x => new Model.Security.Role {
                            Id = x
                        }).ToList();
                        //Add default role for organization member invitation
                        if (roles.IsNullOrEmpty() && !string.IsNullOrEmpty(organizationId))
                        {
                            roles = new[] { SecurityConstants.Roles.OrganizationEmployee }.ToList();
                        }
                        user.Roles = roles;
                        result     = await _userManager.CreateAsync(user);
                    }

                    if (result.Succeeded)
                    {
                        user = await _userManager.FindByNameAsync(user.UserName);

                        var token = await _userManager.GeneratePasswordResetTokenAsync(user);

                        var callbackUrl        = Url.Action("ConfirmInvitation", "Account", new { OrganizationId = organizationId, user.Email, Token = token }, Request.Scheme);
                        var inviteNotification = new RegistrationInvitationNotification(WorkContext.CurrentStore.Id, WorkContext.CurrentLanguage)
                        {
                            InviteUrl = callbackUrl,
                            Sender    = WorkContext.CurrentStore.Email,
                            Recipient = user.Email
                        };
                        var sendingResult = await _platformNotificationApi.SendNotificationAsync(inviteNotification.ToNotificationDto());

                        if (sendingResult.IsSuccess != true)
                        {
                            var errors = result.Errors.Concat(new IdentityError[] { new IdentityError()
                                                                                    {
                                                                                        Description = sendingResult.ErrorMessage
                                                                                    } }).ToArray();
                            result = IdentityResult.Failed(errors);
                        }
                    }
                }
            }
            else
            {
                result = IdentityResult.Failed(ModelState.Values.SelectMany(x => x.Errors).Select(x => new IdentityError {
                    Description = x.ErrorMessage
                }).ToArray());
            }
            return(Json(result));
        }
 public Task <IdentityResult> ValidateAsync(RoleManager <TRole> manager, TRole role)
 {
     return(Task.FromResult(IdentityResult.Failed(ErrorMessage)));
 }
 public Task <IdentityResult> ValidateAsync(UserManager <TUser> manager, TUser user)
 {
     return(Task.FromResult(IdentityResult.Failed(ErrorMessage)));
 }
Пример #10
0
        public override async Task <IdentityResult> ValidateAsync(UserManager <User> manager, User user, string password)
        {
            var errors = new List <IdentityError>();

            if (string.IsNullOrWhiteSpace(password))
            {
                errors.Add(new IdentityError
                {
                    Code        = "PasswordIsNotSet",
                    Description = "لطفا کلمه‌ی عبور را تکمیل کنید."
                });
                return(IdentityResult.Failed(errors.ToArray()));
            }

            if (string.IsNullOrWhiteSpace(user?.UserName))
            {
                errors.Add(new IdentityError
                {
                    Code        = "UserNameIsNotSet",
                    Description = "لطفا نام کاربری را تکمیل کنید."
                });
                return(IdentityResult.Failed(errors.ToArray()));
            }

            // First use the built-in validator
            var result = await base.ValidateAsync(manager, user, password).ConfigureAwait(false);

            errors = result.Succeeded ? new List <IdentityError>() : result.Errors.ToList();

            // Extending the built-in validator
            if (password.ToLower().Contains(user.UserName.ToLower()))
            {
                errors.Add(new IdentityError
                {
                    Code        = "PasswordContainsUserName",
                    Description = "کلمه‌ی عبور نمی‌تواند حاوی قسمتی از نام کاربری باشد."
                });
                return(IdentityResult.Failed(errors.ToArray()));
            }

            if (!isSafePasword(password))
            {
                errors.Add(new IdentityError
                {
                    Code        = "PasswordIsNotSafe",
                    Description = "کلمه‌ی عبور وارد شده به سادگی قابل حدس زدن است."
                });
                return(IdentityResult.Failed(errors.ToArray()));
            }

            if (await _usedPasswordsService.IsPreviouslyUsedPasswordAsync(user, password).ConfigureAwait(false))
            {
                errors.Add(new IdentityError
                {
                    Code        = "IsPreviouslyUsedPassword",
                    Description = "لطفا کلمه‌ی عبور دیگری را انتخاب کنید. این کلمه‌ی عبور پیشتر توسط شما استفاده شده‌است و تکراری می‌باشد."
                });
                return(IdentityResult.Failed(errors.ToArray()));
            }

            return(!errors.Any() ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()));
        }
Пример #11
0
        /// <inheritdoc />
        public async Task <IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken)
        {
            ThrowIfNullDisposedCancelled(user, cancellationToken);

            // Make sure we have a valid email address.
            if (string.IsNullOrWhiteSpace(user.Email))
            {
                throw new ArgumentException("The user's email address can't be null or empty.", nameof(user));
            }

            if (string.IsNullOrEmpty(user.Id))
            {
                var conventions = _store.Conventions;
                var entityName  = conventions.GetCollectionName(typeof(TUser));
                var prefix      = conventions.TransformTypeCollectionNameToDocumentIdPrefix(entityName);
                var separator   = conventions.IdentityPartsSeparator;
                var id          = $"{prefix}{separator}{user.Email}";
                user.Id = id;
            }

            if (string.IsNullOrEmpty(user.UserName))
            {
                user.UserName = user.Email;
            }

            cancellationToken.ThrowIfCancellationRequested();

            // See if the email address is already taken.
            // We do this using Raven's compare/exchange functionality, which works cluster-wide.
            // https://ravendb.net/docs/article-page/4.1/csharp/client-api/operations/compare-exchange/overview#creating-a-key
            //
            // Try to reserve a new user email
            // Note: This operation takes place outside of the session transaction it is a cluster-wide reservation.
            var compareExchangeKey    = GetCompareExchangeKeyFromEmail(user.Email);
            var reserveEmailOperation = new PutCompareExchangeValueOperation <string>(compareExchangeKey, user.Id, 0);
            var reserveEmailResult    = await _store.Operations.SendAsync(reserveEmailOperation);

            if (!reserveEmailResult.Successful)
            {
                return(IdentityResult.Failed(new[]
                {
                    new IdentityError
                    {
                        Code = "DuplicateEmail",
                        Description = $"The email address {user.Email} is already taken."
                    }
                }));
            }

            using (IAsyncDocumentSession session = _store.OpenAsyncSession())
            {
                // This model allows us to lookup a user by name in order to get the id
                await session.StoreAsync(user, cancellationToken);

                // Because this a a cluster-wide operation due to compare/exchange tokens,
                // we need to save changes here; if we can't store the user,
                // we need to roll back the email reservation.
                try
                {
                    await session.SaveChangesAsync(cancellationToken);
                }
                catch (Exception)
                {
                    // The compare/exchange email reservation is cluster-wide, outside of the session scope.
                    // We need to manually roll it back.
                    await this.DeleteUserEmailReservation(user.Email);

                    throw;
                }
            }

            return(IdentityResult.Success);
        }
Пример #12
0
        public async Task ConfirmEmailFailConfirmEmailError()
        {
            moqAspIdentity.mockUserManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(applicationUser);

            moqAspIdentity.mockUserManager.Setup(x => x.ConfirmEmailAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Failed(identityError));

            moqAspIdentity.mockSignInManager.Setup(x => x.SignInAsync(It.IsAny <ApplicationUser>(), It.IsAny <bool>(), null)).Returns(Task.FromException(new Exception()));


            // setup
            AccountModel model = new AccountModel(moqAspIdentity.mockUserManager.Object);

            // operation
            try
            {
                Dictionary <string, string> result = await model.ConfirmEmailAsync(moqAspIdentity.mockSignInManager.Object, "123", "123");

                // assert
                Assert.Fail("Supposed to throw exception");
            }
            catch (Exception ex)
            {
                if (ex is ApiException)
                {
                    Assert.AreEqual(((ApiException)ex).ExceptionType, ExceptionsTypes.LoginError);
                }
                else
                {
                    Assert.Fail("Wrong Type of exception thrown.");
                }
            }
        }
Пример #13
0
 protected IdentityResult Failed(params IdentityError[] errors)
 => IdentityResult.Failed(errors);
Пример #14
0
 protected IdentityResult Failed(string message)
 {
     return(message.IsEmpty() ? IdentityResult.Failed() : IdentityResult.Failed(new IdentityError {
         Description = message
     }));
 }
Пример #15
0
        public async Task <IdentityResult> SeedDatabaseWithAdminUserAsync()
        {
            var name     = "admin";
            var password = "******";
            var email    = "*****@*****.**";
            var roleName = "admin";

            var thisMethodName = nameof(SeedDatabaseWithAdminUserAsync);

            var adminUser = await _applicationUserManager.FindByNameAsync(name);

            if (adminUser != null)
            {
                _logger.LogInformation($"{thisMethodName}: adminUser already exists.");
                var role = _roleManager.GetRoleByUserGuid(adminUser.Id);
                if (_env.IsDevelopment() && role != null)
                {
                    await _roleManager.AddOrUpdateRoleClaims(role.Id, GlobalEnum.DynamicRole, _mvcActionsDiscoveryService.GetAllAdminActionRoute());
                }
                await _uow.SaveChangesAsync();

                return(IdentityResult.Success);
            }

            //Create the `Admin` Role if it does not exist
            var adminRole = await _roleManager.FindByNameAsync(roleName);

            if (adminRole == null)
            {
                adminRole    = new Role(roleName);
                adminRole.Id = new Guid();
                var adminRoleResult = await _roleManager.CreateAsync(adminRole);

                if (adminRoleResult == IdentityResult.Failed())
                {
                    _logger.LogError($"{thisMethodName}: adminRole CreateAsync failed. {adminRoleResult.DumpErrors()}");
                    return(IdentityResult.Failed());
                }
                else
                {
                    // await _roleManager.AddOrUpdateRoleClaims(adminRole.Id, GlobalEnum.DynamicRole, _mvcControllerDiscovery.GetAllAdminActionRoute());
                }
            }
            else
            {
                _logger.LogInformation($"{thisMethodName}: adminRole already exists.");
            }

            adminUser = new User
            {
                UserName       = name,
                Email          = email,
                EmailConfirmed = true,
                IsEmailPublic  = true,
                LockoutEnabled = true
            };
            var adminUserResult = await _applicationUserManager.CreateAsync(adminUser, password);

            if (adminUserResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser CreateAsync failed. {adminUserResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            var setLockoutResult = await _applicationUserManager.SetLockoutEnabledAsync(adminUser, enabled : false);

            if (setLockoutResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser SetLockoutEnabledAsync failed. {setLockoutResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            var addToRoleResult = await _applicationUserManager.AddToRoleAsync(adminUser, adminRole.Name);

            if (addToRoleResult == IdentityResult.Failed())
            {
                _logger.LogError($"{thisMethodName}: adminUser AddToRoleAsync failed. {addToRoleResult.DumpErrors()}");
                return(IdentityResult.Failed());
            }

            return(IdentityResult.Success);
        }
        public async Task Register_WhenAddPasswordFails_ExpectUpdateToNotBeCalledAndModelStateToHaveErrors()
        {
            //arrange
            var controller = new AccountController(mockInteraction.Object, mockClientStore.Object, mockAccessor.Object, mockUserManager.Object, mockSchemeProvider.Object, mockEvents.Object, mockUrlHelper.Object);

            mockUserManager.Setup(x => x.FindByNameAsync(It.IsAny <string>())).ReturnsAsync(new IdentityExpressUser());
            mockUserManager.Setup(x => x.AddPasswordAsync(It.IsAny <IdentityExpressUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Failed(new IdentityError {
                Description = "Error"
            }));

            var model = new RegisterInputModel
            {
                Username = "******"
            };

            //act
            var result = await controller.Register(model);

            //assert
            var viewResult = Assert.IsType <ViewResult>(result);

            Assert.False(viewResult.ViewData.ModelState.IsValid);
            mockUserManager.Verify(x => x.UpdateAsync(It.IsAny <IdentityExpressUser>()), Times.Never);
        }
Пример #17
0
        // IUserStore

        public async Task <IdentityResult> CreateAsync(User user, CancellationToken cancellationToken)
        {
            var success = await _identityRepository.CreateUser(user);

            return(success ? IdentityResult.Success : IdentityResult.Failed());
        }
 public void CheckResult_ThrowException_WhenIdentityResultIsFalse()
 {
     Assert.Throws <ResultException>(
         () => IdentityResult.Failed("Error").CheckResult());
 }
Пример #19
0
        public async Task AssignRolePermissions_AddingOfPermissionFails_ThrowsUserManagementException()
        {
            // Arrange

            var oldPermissions = new[]
            {
                "Permission #1",
                "Permission #3",
            };

            var newPermissions = new[]
            {
                "Permission #1",
                "Permission #2",
                "Permission #3",
                "Permission #4",
            };

            var role = new IdentityRole();

            var mocker = new AutoMocker();

            var roleManagerMock = new Mock <IRoleManager <IdentityRole, string> >();

            roleManagerMock.Setup(x => x.FindByIdAsync("SomeRoleId")).ReturnsAsync(role);
            roleManagerMock.Setup(x => x.GetClaimsAsync(role)).ReturnsAsync(ToClaims(oldPermissions));
            roleManagerMock.Setup(x => x.AddClaimAsync(It.IsAny <IdentityRole>(), It.IsAny <Claim>())).ReturnsAsync(IdentityResult.Failed());
            mocker.Use(roleManagerMock);

            var target = mocker.CreateInstance <RoleService <IdentityRole, string> >();

            // Act

            var call = () => target.AssignRolePermissions("SomeRoleId", newPermissions, CancellationToken.None);

            // Assert

            await call.Should().ThrowAsync <UserManagementException>();
        }
Пример #20
0
        public async Task RegisterReturnsViewResultAndCorrectModelWhenUserCreationIsNotSuccessful()
        {
            var model = new RegisterViewModel();

            var generalSettings = new Mock <IOptions <GeneralSettings> >();

            generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());

            var userManager = CreateUserManagerMock();

            userManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).Returns(() => Task.FromResult(IdentityResult.Failed()));

            var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object);

            sut.SetFakeHttpRequestSchemeTo(It.IsAny <string>());

            var result = await sut.Register(model) as ViewResult;

            var modelResult = result.ViewData.Model as RegisterViewModel;

            Assert.IsType <ViewResult>(result);
            Assert.IsType <RegisterViewModel>(modelResult);
            Assert.Same(model, modelResult);
        }
Пример #21
0
 public MockUserManager(IUserStore <User, int> store, IAppliedSystemsPasswordHasher passwordHasher)
     : base(store, passwordHasher)
 {
     _creationResult = IdentityResult.Failed();
 }
Пример #22
0
        public async Task ConfirmEmailInvokesConfirmEmailAsyncWithCorrectUserAndCode()
        {
            const string code = "code";
            var          user = new ApplicationUser();

            var userManager = CreateUserManagerMock();

            userManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).Returns(() => Task.FromResult(user));
            userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).Returns(() => Task.FromResult(IdentityResult.Failed()));

            var sut = new AdminController(userManager.Object, null, null, null, null);
            await sut.ConfirmEmail(null, code);

            userManager.Verify(x => x.ConfirmEmailAsync(user, code), Times.Once);
        }
Пример #23
0
        public async Task Given_A_Valid_ResetPassword_Credentials_If_ResetPassword_Fails_Should_Return_BadRequestResult()
        {
            // Arrange
            const string expected = "Reset password code expired.";

            var resetPasswordViewModel = new ResetPasswordViewModel
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var resetPasswordQueryParameters = new ResetPasswordQueryParameters();

            _userManager.FindByEmailAsync(Arg.Any <string>()).Returns(new ApplicationUser());
            _userManager.ResetPasswordAsync(Arg.Any <ApplicationUser>(), Arg.Any <string>(), Arg.Any <string>()).Returns(IdentityResult.Failed(new IdentityError
            {
                Description = "Reset password code expired."
            }));

            // Act
            var result = await _sut.ResetPassword(resetPasswordViewModel, resetPasswordQueryParameters) as BadRequestObjectResult;

            // Assert
            result.Should().BeOfType <BadRequestObjectResult>();
            var errors = result?.Value as IEnumerable <string>;

            errors.Should().ContainSingle(expected);
        }
Пример #24
0
        public async Task ConfirmEmailReturnsCorrectViewWhenUsersConfirmationIsUnsuccessful()
        {
            var userManager = CreateUserManagerMock();

            userManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).Returns(() => Task.FromResult(new ApplicationUser()));
            userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).Returns(() => Task.FromResult(IdentityResult.Failed()));

            var sut    = new AdminController(userManager.Object, null, null, null, null);
            var result = await sut.ConfirmEmail("userId", "code") as ViewResult;

            Assert.Equal(result.ViewName, "Error");
        }
Пример #25
0
 public async Task <IdentityResult> UpdateAsync(IdentityRole role, CancellationToken cancel) =>
 await(await PutAsync(_serviceAddress, role, cancel))
 .Content
 .ReadAsAsync <bool>(cancel)
                         ? IdentityResult.Success
                         : IdentityResult.Failed();
Пример #26
0
        public async Task RegisterInvokesCreateAsyncWithCorrectUserAndPassword()
        {
            const string defaultTimeZone = "DefaultTimeZone";

            var model = new RegisterViewModel {
                Email = "email", Password = "******"
            };

            var generalSettings = new Mock <IOptions <GeneralSettings> >();

            generalSettings.Setup(x => x.Value).Returns(new GeneralSettings {
                DefaultTimeZone = defaultTimeZone
            });

            var userManager = CreateUserManagerMock();

            userManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).Returns(() => Task.FromResult(IdentityResult.Failed()));

            var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object);

            await sut.Register(model);

            userManager.Verify(x => x.CreateAsync(It.Is <ApplicationUser>(au =>
                                                                          au.UserName == model.Email &&
                                                                          au.Email == model.Email &&
                                                                          au.TimeZoneId == defaultTimeZone),
                                                  model.Password));
        }
        public Mock <UserManager <HoundDogUser> > MockUserManager()
        {
            IList <IUserValidator <HoundDogUser> >     UserValidators     = new List <IUserValidator <HoundDogUser> >();
            IList <IPasswordValidator <HoundDogUser> > PasswordValidators = new List <IPasswordValidator <HoundDogUser> >();

            var store = new Mock <IUserStore <HoundDogUser> >();

            UserValidators.Add(new UserValidator <HoundDogUser>());
            PasswordValidators.Add(new PasswordValidator <HoundDogUser>());
            var mgr = new Mock <UserManager <HoundDogUser> >(store.Object, null, null, UserValidators, PasswordValidators, null, null, null, null);

            mgr.Setup(x => x.FindByIdAsync(_testUser.Id)).ReturnsAsync(_testUser); // allow search by username
            mgr.Setup(x => x.GetRolesAsync(_testUser)).ReturnsAsync(new List <string>()
            {
                "User"
            });                                                                            // allow search of roles

            mgr.Setup(x => x.FindByIdAsync(_testUserFail.Id)).ReturnsAsync(_testUserFail); // allow search by username
            mgr.Setup(x => x.GetRolesAsync(_testUserFail)).ReturnsAsync(new List <string>()
            {
                "User"
            });                                                                          // allow search of roles

            mgr.Setup(x => x.FindByIdAsync(_testUser2FA.Id)).ReturnsAsync(_testUser2FA); // allow search by username
            mgr.Setup(x => x.GetRolesAsync(_testUser2FA)).ReturnsAsync(new List <string>()
            {
                "User"
            });                                                                                  // allow search of roles

            mgr.Setup(x => x.FindByIdAsync(_testUserFail2FA.Id)).ReturnsAsync(_testUserFail2FA); // allow search by username
            mgr.Setup(x => x.GetRolesAsync(_testUserFail2FA)).ReturnsAsync(new List <string>()
            {
                "User"
            });                                                                                    // allow search of roles

            mgr.Setup(x => x.FindByIdAsync(_testUserFail2FAK.Id)).ReturnsAsync(_testUserFail2FAK); // allow search by username
            mgr.Setup(x => x.GetRolesAsync(_testUserFail2FAK)).ReturnsAsync(new List <string>()
            {
                "User"
            });                                                                                             // allow search of roles

            mgr.Setup(x => x.ResetAuthenticatorKeyAsync(_testUser)).ReturnsAsync(IdentityResult.Success);
            mgr.Setup(x => x.ResetAuthenticatorKeyAsync(_testUser2FA)).ReturnsAsync(IdentityResult.Success);
            mgr.Setup(x => x.ResetAuthenticatorKeyAsync(_testUserFail2FAK)).ReturnsAsync(IdentityResult.Failed(new IdentityError()
            {
                Code = "FailReset", Description = "FailReset"
            }));

            mgr.Setup(x => x.GetAuthenticatorKeyAsync(_testUser)).ReturnsAsync("ANewCode");

            mgr.Setup(x => x.VerifyTwoFactorTokenAsync(_testUser, "Authenticator", "999999")).ReturnsAsync(true);
            mgr.Setup(x => x.VerifyTwoFactorTokenAsync(_testUser, "Authenticator", "123456")).ReturnsAsync(false);
            mgr.Setup(x => x.VerifyTwoFactorTokenAsync(_testUserFail, "Authenticator", "999999")).ReturnsAsync(true);

            mgr.Setup(x => x.SetTwoFactorEnabledAsync(_testUser, true)).ReturnsAsync(IdentityResult.Success);
            mgr.Setup(x => x.SetTwoFactorEnabledAsync(_testUser, false)).ReturnsAsync(IdentityResult.Success);
            mgr.Setup(x => x.SetTwoFactorEnabledAsync(_testUser2FA, false)).ReturnsAsync(IdentityResult.Success);
            mgr.Setup(x => x.SetTwoFactorEnabledAsync(_testUser2FA, true)).ReturnsAsync(IdentityResult.Success);
            mgr.Setup(x => x.SetTwoFactorEnabledAsync(_testUserFail, true)).ReturnsAsync(IdentityResult.Failed(new IdentityError()
            {
                Code = "Fail2FA", Description = "Fail2FA"
            }));
            mgr.Setup(x => x.SetTwoFactorEnabledAsync(_testUserFail2FA, false)).ReturnsAsync(IdentityResult.Failed(new IdentityError()
            {
                Code = "Fail2FA", Description = "Fail2FA"
            }));
            mgr.Setup(x => x.SetTwoFactorEnabledAsync(_testUserFail2FAK, false)).ReturnsAsync(IdentityResult.Success);
            return(mgr);
        }
Пример #28
0
        public void SetUp()
        {
            var roles = new List <ApplicationRole>()
            {
                new ApplicationRole()
                {
                    Id = "1", Name = "admin"
                },
                new ApplicationRole()
                {
                    Id = "2", Name = "user"
                },
                new ApplicationRole()
                {
                    Id = "3", Name = "manager"
                }
            }.AsQueryable();

            var users = new List <ApplicationUser>()
            {
                new ApplicationUser()
                {
                    Id    = "1", UserName = "******",
                    Roles =
                    {
                        new IdentityUserRole()
                        {
                            RoleId = "1"
                        },
                        new IdentityUserRole()
                        {
                            RoleId = "2"
                        }
                    }
                },
                new ApplicationUser()
                {
                    Id    = "2", UserName = "******",
                    Roles = { new IdentityUserRole()
                              {
                                  RoleId = "2"
                              } }
                },
                new ApplicationUser()
                {
                    Id    = "3", UserName = "******",
                    Roles = { new IdentityUserRole()
                              {
                                  RoleId = "2"
                              } }
                },
                new ApplicationUser()
                {
                    Id    = "4", UserName = "******",
                    Roles = { new IdentityUserRole()
                              {
                                  RoleId = "2"
                              } }
                },
            }.AsQueryable();

            _userManager = new Mock <ApplicationUserManager>(new UserStore <ApplicationUser>());
            _roleManager = new Mock <ApplicationRoleManager>(new RoleStore <ApplicationRole>());

            _roleManager.Setup(m => m.Roles).Returns(roles.AsQueryable());
            _userManager.Setup(m => m.Users).Returns(users.AsQueryable());

            _roleManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(
                (string id) => { return(_roleManager.Object.Roles.FirstOrDefault(x => x.Id == id)); });

            _userManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(
                (string id) => { return(_userManager.Object.Users.FirstOrDefault(x => x.Id == id)); });

            _userManager.Setup(x => x.DeleteAsync(It.IsAny <ApplicationUser>())).ReturnsAsync(
                (ApplicationUser user) =>
            {
                if (_userManager.Object.Users.Contains(user))
                {
                    return(IdentityResult.Success);
                }
                return(IdentityResult.Failed("Error"));
            });

            _roleManager.As <IQueryable <ApplicationRole> >().Setup(m => m.Expression).Returns(roles.Expression);
            _roleManager.As <IQueryable <ApplicationRole> >().Setup(m => m.ElementType).Returns(roles.ElementType);
            _roleManager.As <IQueryable <ApplicationRole> >().Setup(m => m.GetEnumerator()).Returns(roles.GetEnumerator());

            _uow = new Mock <IIdentityUnitOfWork <ApplicationUserManager, ApplicationRoleManager> >();
            _uow.Setup(u => u.UserManager).Returns(_userManager.Object);
            _uow.Setup(u => u.RoleManager).Returns(_roleManager.Object);
            //   uow.Setup(u => u.SaveAsync()).Returns(Task.Run(() => { }));

            service = new IdentityService(_uow.Object, new MapperFactory());
        }
Пример #29
0
        public async Task AssignUserRoles_RemovingOfRolesFails_ThrowsUserManagementException()
        {
            // Arrange

            var oldRoles = new[]
            {
                "Role #1",
                "Role #2",
                "Role #3",
                "Role #4",
            };

            var newRoles = new[]
            {
                "Role #1",
                "Role #3",
            };

            var user = new IdentityUser();

            var mocker = new AutoMocker();

            var userManagerMock = new Mock <IUserManager <IdentityUser, string> >();

            userManagerMock.Setup(x => x.FindByIdAsync("SomeUserId")).ReturnsAsync(user);
            userManagerMock.Setup(x => x.GetRolesAsync(user)).ReturnsAsync(oldRoles);
            userManagerMock.Setup(x => x.RemoveFromRolesAsync(It.IsAny <IdentityUser>(), It.IsAny <IEnumerable <string> >())).ReturnsAsync(IdentityResult.Failed());
            mocker.Use(userManagerMock);

            var target = mocker.CreateInstance <UserService <IdentityUser, string> >();

            // Act

            var call = () => target.AssignUserRoles("SomeUserId", newRoles, CancellationToken.None);

            // Assert

            await call.Should().ThrowAsync <UserManagementException>();
        }
        public async Task Delete_WhenDeleteFails_ReturnsErrorView()
        {
            MockSetupFindByIdAsyncMethod(_user);
            _userManager.Setup(um => um.DeleteAsync(It.IsAny <AppUser>())).ReturnsAsync(IdentityResult.Failed("test"));

            ActionResult result = await _controller.Delete("");

            AssertErrorViewReturns <ViewResult>(result);
        }