Example #1
0
        public async void ChangePassword_success()
        {
            // Arrange
            var securityAdapter = new Mock <ISecurityAdapter>();
            var controller      = new AccountApiController(securityAdapter.Object);

            var userIdentity  = new ClaimsIdentity();
            var userPrincipal = new ClaimsPrincipal(userIdentity);

            controller.ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext {
                    User = userPrincipal
                }
            };

            var model = new ChangePasswordModel
            {
                OldPassword     = "******",
                NewPassword     = "******",
                ConfirmPassword = "******"
            };

            securityAdapter.Setup(x => x.CheckPassword(userIdentity.Name, model.OldPassword)).Returns(_BoolFromTaskFunction(true));
            securityAdapter.Setup(x => x.ChangePassword(userIdentity.Name, model.OldPassword, model.NewPassword)).Returns(_BoolFromTaskFunction(true));

            // Act
            var result = await controller.ChangePassword(model);

            // Assert
            Assert.IsType <StatusCodeResult>(result);

            securityAdapter.Verify(x => x.CheckPassword(userIdentity.Name, model.OldPassword), Times.Once);
            securityAdapter.Verify(x => x.ChangePassword(userIdentity.Name, model.OldPassword, model.NewPassword), Times.Once);
        }
        public async Task Delete_validId_shouldInvokeDelete()
        {
            var mockUserStore = Mock.Of <IDragonUserStore <AppMember> >(x =>
                                                                        x.FindByIdAsync(It.IsAny <string>()) == Task.FromResult(new AppMember()) &&
                                                                        x.GetRolesAsync(It.IsAny <AppMember>()) == Task.FromResult((IList <string>) new List <string> {
                "r1", "r2"
            }) &&
                                                                        (IUserRoleStore <AppMember, string>)(x).IsInRoleAsync(It.IsAny <AppMember>(), It.IsAny <string>()) == Task.FromResult(true) &&
                                                                        (IUserRoleStore <AppMember, string>)(x).RemoveFromRoleAsync(It.IsAny <AppMember>(), It.IsAny <string>()) == Task.FromResult(0) &&
                                                                        x.GetLoginsAsync(It.IsAny <AppMember>()) == Task.FromResult((IList <UserLoginInfo>) new List <UserLoginInfo> {
                new UserLoginInfo("p1", "k1")
            }) &&
                                                                        (IUserLoginStore <AppMember, string>)(x).RemoveLoginAsync(It.IsAny <AppMember>(), It.IsAny <UserLoginInfo>()) == Task.FromResult(true) &&
                                                                        x.RemoveServiceRegistrations(It.IsAny <AppMember>()) == Task.FromResult <object>(null) &&
                                                                        x.RemoveAppRegistrations(It.IsAny <AppMember>()) == Task.FromResult <object>(null)
                                                                        );
            var mockUserActivityRepository = Mock.Of <IRepository <UserActivity> >(x =>
                                                                                   x.GetByWhere(It.IsAny <Dictionary <string, object> >()) == new List <UserActivity> {
                new UserActivity()
            });
            var controller = new AccountApiController(mockUserStore, new ApplicationUserManager(mockUserStore), mockUserActivityRepository);

            var result = await controller.Delete(Guid.NewGuid().ToString());

            Assert.IsInstanceOfType(result, typeof(OkResult));

            Mock.Get(mockUserStore).Verify(x => x.RemoveServiceRegistrations(It.IsAny <AppMember>()), Times.Once);
            Mock.Get(mockUserStore).Verify(x => x.RemoveAppRegistrations(It.IsAny <AppMember>()), Times.Once);
            Mock.Get(mockUserStore).Verify(x => x.RemoveLoginAsync(It.IsAny <AppMember>(), It.IsAny <UserLoginInfo>()), Times.Once);
            Mock.Get(mockUserStore).Verify(x => x.RemoveFromRoleAsync(It.IsAny <AppMember>(), It.IsAny <string>()), Times.Exactly(2));
            Mock.Get(mockUserActivityRepository).Verify(x => x.Delete(It.IsAny <UserActivity>()), Times.Once);
            Mock.Get(mockUserStore).Verify(x => x.DeleteAsync(It.IsAny <AppMember>()), Times.Once);
        }
Example #3
0
        public async void Login_success()
        {
            // Arrange
            var securityAdapter = new Mock <ISecurityAdapter>();
            var controller      = new AccountApiController(securityAdapter.Object);

            var model = new LoginModel
            {
                LoginEmail = "*****@*****.**",
                Password   = "******",
                RememberMe = false
            };

            securityAdapter.Setup(x => x.UserExists(model.LoginEmail)).Returns(_BoolFromTaskFunction(true));
            securityAdapter.Setup(x => x.CheckPassword(model.LoginEmail, model.Password)).Returns(_BoolFromTaskFunction(true));
            securityAdapter.Setup(x => x.Login(model.LoginEmail, model.Password, model.RememberMe)).Returns(_BoolFromTaskFunction(true));

            // Act
            var result = await controller.Login(model);

            // Assert
            Assert.IsType <ObjectResult>(result);

            ObjectResult objectResult = result as ObjectResult;

            Assert.True(objectResult.StatusCode == (int)HttpStatusCode.OK);

            securityAdapter.Verify(x => x.UserExists(model.LoginEmail), Times.Once);
            securityAdapter.Verify(x => x.CheckPassword(model.LoginEmail, model.Password), Times.Once);
            securityAdapter.Verify(x => x.Login(model.LoginEmail, model.Password, model.RememberMe), Times.Once);
        }
Example #4
0
        public async Task TestFetchDocuments()
        {
            var falseDatabaseService = new FalseDatabaseService();
            var draftAccount         = new Account(Guid.NewGuid(), "Alfa", "*****@*****.**", Array.Empty <byte>());
            var decoyAccount         = new Account(Guid.NewGuid(), "Bravo", "*****@*****.**", Array.Empty <byte>());
            await falseDatabaseService.SaveAccountAsync(draftAccount, true);

            await falseDatabaseService.SaveAccountAsync(decoyAccount, true);

            var draftDocumentKeys = new[] {
                await falseDatabaseService.AddDocumentAsync(draftAccount.Id, "alfa", string.Empty, Enumerable.Empty <MD5Sum>()),
                await falseDatabaseService.AddDocumentAsync(draftAccount.Id, "bravo", string.Empty, Enumerable.Empty <MD5Sum>())
            };
            var decoyDocumentKeys = new[] {
                await falseDatabaseService.AddDocumentAsync(decoyAccount.Id, "charlie", string.Empty, Enumerable.Empty <MD5Sum>()),
                await falseDatabaseService.AddDocumentAsync(decoyAccount.Id, "delta", string.Empty, Enumerable.Empty <MD5Sum>())
            };
            var serviceProvider      = new ServiceCollection().AddLogging().BuildServiceProvider();
            var factory              = serviceProvider.GetService <ILoggerFactory>();
            var logger               = factory.CreateLogger <AccountApiController>();
            var accountApiController = new AccountApiController(falseDatabaseService, logger);
            var encodedId            = WebEncoders.Base64UrlEncode(draftAccount.Id.ToByteArray());
            var result               = (OkObjectResult)await accountApiController.GetAccountDocuments(encodedId);

            var resultBody = (IEnumerable <MD5Sum>)result.Value;

            Assert.Equal(resultBody.Count(), draftDocumentKeys.Count());
            Assert.True(resultBody.SequenceEqual(draftDocumentKeys));
        }
Example #5
0
        public async void Login_fail()
        {
            // Arrange
            var securityAdapter = new Mock <ISecurityAdapter>();
            var controller      = new AccountApiController(securityAdapter.Object);

            var model = new LoginModel {
                LoginEmail = "", Password = "",
            };

            // Act
            var result = await controller.Login(model);

            // Assert
            Assert.IsType <ObjectResult>(result);

            var objectResult = result as ObjectResult;

            Assert.True(objectResult.StatusCode == (int)HttpStatusCode.BadRequest);

            Assert.IsType <List <string> >(objectResult.Value);

            var errors = objectResult.Value as List <string>;

            Assert.True(errors.Count == 4);
        }
Example #6
0
        public async void ChangePassword_fail()
        {
            // Arrange
            var securityAdapter = new Mock <ISecurityAdapter>();
            var controller      = new AccountApiController(securityAdapter.Object);

            var userIdentity  = new ClaimsIdentity();
            var userPrincipal = new ClaimsPrincipal(userIdentity);

            controller.ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext {
                    User = userPrincipal
                }
            };

            // Act
            var result = await controller.ChangePassword(new ChangePasswordModel());

            // Assert
            Assert.IsType <ObjectResult>(result);

            ObjectResult objectResult = result as ObjectResult;

            Assert.True(objectResult.StatusCode == (int)HttpStatusCode.BadRequest);

            Assert.IsType <List <string> >(objectResult.Value);

            var errors = objectResult.Value as List <string>;

            Assert.True(errors.Count > 0);

            securityAdapter.Verify(x => x.ChangePassword(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.Never);
        }
Example #7
0
        public async Task TestFetchAccountFastFail(string id)
        {
            var serviceProvider      = new ServiceCollection().AddLogging().BuildServiceProvider();
            var factory              = serviceProvider.GetService <ILoggerFactory>();
            var logger               = factory.CreateLogger <AccountApiController>();
            var accountApiController = new AccountApiController(new FalseDatabaseService(), logger);
            var result               = await accountApiController.GetAccountMetadata(id);

            Assert.True(result is BadRequestResult);
        }
        public void ClearCache_shouldInvokeClearCache()
        {
            var mockUserStore = Mock.Of <IDragonUserStore <AppMember> >();
            var controller    = new AccountApiController(mockUserStore, null, null);

            var result = controller.ClearCache();

            Assert.IsInstanceOfType(result, typeof(OkResult));

            Mock.Get(mockUserStore).Verify(x => x.ClearCache(), Times.Once);
        }
        public async Task Update_passwordOnly_shouldInvokeUpdate()
        {
            var mockUserStore = Mock.Of <IDragonUserStore <AppMember> >(x =>
                                                                        x.FindByIdAsync(It.IsAny <string>()) == Task.FromResult(new AppMember()) &&
                                                                        x.UpdateAsync(It.IsAny <AppMember>()) == Task.FromResult <object>(null)
                                                                        );
            var controller = new AccountApiController(mockUserStore, new ApplicationUserManager(mockUserStore), null);

            var password = Guid.NewGuid().ToString();
            var result   = await controller.Update(new UpdateViewModel { Password = password });

            Assert.IsInstanceOfType(result, typeof(OkResult));

            Mock.Get(mockUserStore).Verify(x => x.UpdateAsync(It.Is <AppMember>(y => !string.IsNullOrEmpty(y.PasswordHash))), Times.Once);
            Mock.Get(mockUserStore).Verify(x => x.UpdateAsync(It.Is <AppMember>(y => !string.IsNullOrEmpty(y.PasswordHash))), Times.Once);
        }
        public async Task Update_emailOnly_shouldInvokeUpdate()
        {
            var mockUserStore = Mock.Of <IDragonUserStore <AppMember> >(x =>
                                                                        x.FindByIdAsync(It.IsAny <string>()) == Task.FromResult(new AppMember()) &&
                                                                        x.UpdateAsync(It.IsAny <AppMember>()) == Task.FromResult <object>(null)
                                                                        );
            var controller = new AccountApiController(mockUserStore, null, null);

            const string email  = "*****@*****.**";
            var          result = await controller.Update(new UpdateViewModel { Email = email });

            Assert.IsInstanceOfType(result, typeof(OkResult));

            Mock.Get(mockUserStore).Verify(x => x.UpdateAsync(It.Is <AppMember>(y => y.Email == email)), Times.Once);
            Mock.Get(mockUserStore).Verify(x => x.UpdateAsync(It.Is <AppMember>(y => y.Email == email)), Times.Once);
        }
Example #11
0
        public async Task TestFetchDocumentsForNonExistentAccount()
        {
            var serviceProvider      = new ServiceCollection().AddLogging().BuildServiceProvider();
            var factory              = serviceProvider.GetService <ILoggerFactory>();
            var logger               = factory.CreateLogger <AccountApiController>();
            var falseDatabaseService = new FalseDatabaseService();
            var draftAccount         = new Account(Guid.NewGuid(), "Alfa", "*****@*****.**", Array.Empty <byte>());
            await falseDatabaseService.SaveAccountAsync(draftAccount, true);

            var accountApiController = new AccountApiController(falseDatabaseService, logger);
            var idWhichIsNotRepresentedInTheDatabase = WebEncoders.Base64UrlEncode(Guid.NewGuid().ToByteArray());
            var result = (OkObjectResult)await accountApiController.GetAccountDocuments(idWhichIsNotRepresentedInTheDatabase);

            var resultBody = (IEnumerable <MD5Sum>)result.Value;

            Assert.Empty(resultBody);
        }
Example #12
0
        public async Task TestFetchAccount()
        {
            var falseDatabaseService = new FalseDatabaseService();
            var draftAccount         = new Account(Guid.NewGuid(), "Alfa", "*****@*****.**", Array.Empty <byte>());
            await falseDatabaseService.SaveAccountAsync(draftAccount, true);

            var serviceProvider      = new ServiceCollection().AddLogging().BuildServiceProvider();
            var factory              = serviceProvider.GetService <ILoggerFactory>();
            var logger               = factory.CreateLogger <AccountApiController>();
            var accountApiController = new AccountApiController(falseDatabaseService, logger);
            var encodedId            = WebEncoders.Base64UrlEncode(draftAccount.Id.ToByteArray());
            var result               = (OkObjectResult)await accountApiController.GetAccountMetadata(encodedId);

            var resultBody = (AccountMetadata)result.Value;

            Assert.Equal(draftAccount.DisplayName, resultBody.DisplayName);
            Assert.Equal(draftAccount.Email.ToGravatarHash(), resultBody.GravatarHash);
            Assert.Equal(draftAccount.Id, resultBody.Id);
        }
Example #13
0
        public void PostEntity_False_Test()
        {
            // Arrange
            var authentication              = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <IAuthentication>();
            var viewElementRoleService      = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <IViewElementRoleService>();
            var companyChartService         = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <ICompanyChartService>();
            var userService                 = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <IUserService>();
            var coreUserLogService          = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <IServiceBase <CoreUserLog> >();
            var userProfileService          = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <IUserProfileService>();
            var constantService             = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <IConstantService>();
            var domainAuthenticationService = Core.Cmn.AppBase.DependencyInjectionManager.Resolve <IDomainAuthenticationService>();


            var controller = new AccountApiController(authentication, viewElementRoleService, companyChartService, userService, coreUserLogService, userProfileService, constantService, domainAuthenticationService);

            controller.Request = new HttpRequestMessage {
                RequestUri = new Uri("http://localhost:15660/api/AccountApi/PostEntity"),
                Method     = new HttpMethod("POST"),
                Content    = new StringContent("UserName\":\"admin\", \"Password\":\"98989\", \"RememberMe\":false, \"HiddenId\":\"b00efd89ff88cf37b6f350c563f649dc6d13593f\", \"CaptchaCode\":\"7894\", \"Domain\":\"\" "
                                               , UTF8Encoding.UTF8, "application/json")
            };

            controller.Configuration = new HttpConfiguration();
            var token = new System.Threading.CancellationToken();

            controller.ExecuteAsync(controller.ControllerContext, token);

            // Act
            var response = controller.PostEntity(new Core.Mvc.ViewModel.Account.LogOnViewModel
            {
                UserName    = "******",
                Password    = "******",
                RememberMe  = false,
                HiddenId    = "44ef4a84913c86839c4def0e52cbcf3e9b336b1b",
                CaptchaCode = "656656",
                Domain      = string.Empty
            });

            // Assert
            Assert.IsFalse(response.IsSuccessStatusCode);
        }
Example #14
0
        public async Task TestFetchNonExistentAccount()
        {
            var falseDatabaseService = new FalseDatabaseService();
            var draftAccount         = new Account(Guid.NewGuid(), "Alfa", "*****@*****.**", Array.Empty <byte>());
            await falseDatabaseService.SaveAccountAsync(draftAccount, true);

            var serviceProvider      = new ServiceCollection().AddLogging().BuildServiceProvider();
            var factory              = serviceProvider.GetService <ILoggerFactory>();
            var logger               = factory.CreateLogger <AccountApiController>();
            var accountApiController = new AccountApiController(falseDatabaseService, logger);
            var idWhichIsNotRepresentedInTheDatabase = WebEncoders.Base64UrlEncode(Guid.NewGuid().ToByteArray());

            try
            {
                var result = await accountApiController.GetAccountMetadata(idWhichIsNotRepresentedInTheDatabase);

                Assert.True(false);
            }
            catch (Exception ex)
            {
                Assert.True(ex is FileNotFoundException);
            }
        }
Example #15
0
        public async void Register_success()
        {
            // Arrange
            var securityAdapter = new Mock <ISecurityAdapter>();
            var controller      = new AccountApiController(securityAdapter.Object);

            var model = new RegisterModel
            {
                FirstName       = "first name",
                LastName        = "last name",
                LoginEmail      = "*****@*****.**",
                Password        = "******",
                ConfirmPassword = "******",
                RememberMe      = false
            };


            securityAdapter.Setup(x => x.UserExists(model.LoginEmail)).Returns(_BoolFromTaskFunction(false));
            securityAdapter.Setup(x => x.Register(model.LoginEmail, model.FirstName, model.LastName, model.Password)).Returns(_BoolFromTaskFunction(true));

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

            // Assert
            Assert.IsType <ObjectResult>(result);

            ObjectResult objectResult = result as ObjectResult;

            Assert.True(objectResult.StatusCode == (int)HttpStatusCode.Created);

            Assert.Same(model.LoginEmail, objectResult.Value);

            securityAdapter.Verify(x => x.UserExists(model.LoginEmail), Times.Once);
            securityAdapter.Verify(x => x.Register(model.LoginEmail, model.FirstName, model.LastName, model.Password), Times.Once);
            securityAdapter.Verify(x => x.Login(model.LoginEmail, model.Password, model.RememberMe));
        }
Example #16
0
 public void TestInitialize()
 {
     accountServiceMock   = MockRepository.Create <IAccountService>();
     accountApiController = new AccountApiController(accountServiceMock.Object);
 }
 public void Init()
 {
     unitOfWork = new UnitOfWorkMock();
     cache      = new CacheMock();
     controller = new AccountApiController(unitOfWork, null, null, null, cache);
 }
Example #18
0
 public AccountController(IUserAccountService userAccountService)
 {
     UserAccounService    = userAccountService;
     AccountApiController = new AccountApiController(UserAccounService);
 }