Example #1
0
        public async Task <IActionResult> DoRegister(SigninUserViewModel userViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View("Register"));
            }

            var newUser = new User
            {
                UserName     = userViewModel.UserName,
                DisplayName  = userViewModel.UserName,
                CreatedAtUtc = DateTime.UtcNow
            };

            var result = await _userManager.CreateAsync(newUser, userViewModel.Password);

            if (!result.Succeeded)
            {
                var errorMessage = string.Join(";", result.Errors.Select(err => err.Description));
                ModelState.AddModelError("UserName", errorMessage);
                return(View("Register"));
            }

            await _signInManager.PasswordSignInAsync(
                userViewModel.UserName,
                userViewModel.Password,
                isPersistent : false,
                lockoutOnFailure : true);

            return(RedirectTo("/"));
        }
Example #2
0
        public async Task <IActionResult> DoSignin([FromForm] SigninUserViewModel viewModel, [FromQuery] string returnUrl)
        {
            if (HttpContext.IsAuthenticated())
            {
                return(RedirectTo(returnUrl));
            }

            var result = Microsoft.AspNetCore.Identity.SignInResult.Failed;

            if (ModelState.IsValid)
            {
                result = await _signInManager.PasswordSignInAsync(
                    viewModel.UserName,
                    viewModel.Password,
                    isPersistent : false,
                    lockoutOnFailure : true);

                _logger.LogInformation($"用户 {viewModel.UserName} 尝试登录,结果 {result}");
            }
            else
            {
                _logger.LogInformation($"用户 {viewModel.UserName} 尝试登录,但用户名密码的格式不正确");
            }

            if (!result.Succeeded)
            {
                ModelState.Clear();   // 将真正的验证结果隐藏掉(如果有的话)
                ModelState.AddModelError("UserName", "用户名或密码错误");
            }

            return(ModelState.IsValid ? RedirectTo(returnUrl) : View("Signin"));
        }
        public async Task should_not_register_an_user_with_existing_username()
        {
            var userName = "******";

            _userRepo.Save(new User
            {
                UserName     = userName,
                DisplayName  = "old user",
                CreatedAtUtc = new DateTime(2018, 02, 14)
            });
            var accountCtrl = _myApp.CreateController <AccountController>();


            var newUser = new SigninUserViewModel
            {
                UserName = userName.ToUpper(),
                Password = "******"
            };
            var registerResult = await accountCtrl.DoRegister(newUser);


            Assert.False(accountCtrl.ModelState.IsValid);
            accountCtrl.ModelState.Keys.ShouldContain("UserName");

            var allUsers = _userRepo.All().Where(user => user.UserName == userName).ToList();

            allUsers.Count.ShouldEqual(1);
            allUsers[0].DisplayName.ShouldEqual("old user");

            registerResult.IsType <ViewResult>();
            var viewResult = registerResult as ViewResult;

            // ReSharper disable once PossibleNullReferenceException
            viewResult.ViewName.ShouldEqual("Register");
        }
        public async Task should_return_signin_view_when_incorrect_password()
        {
            var passwordHasher = _myApp.GetService <IPasswordHasher <User> >();
            var accountCtrl    = _myApp.CreateController <AccountController>();

            _userRepo.Save(new User
            {
                UserName       = "******",
                DisplayName    = "Jim Green",
                HashedPassword = passwordHasher.HashPassword(null, "11111F"),
                CreatedAtUtc   = DateTime.UtcNow
            });
            var userModel = new SigninUserViewModel
            {
                UserName = "******",
                Password = "******"
            };

            var sigininResult = await accountCtrl.DoSignin(userModel, null);

            Assert.False(accountCtrl.HttpContext.IsAuthenticated());
            Assert.False(accountCtrl.ModelState.IsValid);
            Assert.Equal("用户名或密码错误", accountCtrl.ModelState["UserName"].Errors.First().ErrorMessage);

            var viewResult = sigininResult as ViewResult;

            Assert.NotNull(viewResult);
            viewResult.ViewName.ShouldEqual("Signin");
        }
        public async Task should_signin_user_and_redirect_when_signin_with_valid_user()
        {
            // Arrange
            ClaimsPrincipal signedInClaimsPrincipal = null;
            var             authService             = new Mock <IAuthenticationService>();

            authService.Setup(auth => auth.SignInAsync(It.IsAny <HttpContext>(), It.IsAny <string>(), It.IsAny <ClaimsPrincipal>(), It.IsAny <AuthenticationProperties>()))
            .Returns(Task.CompletedTask)
            .Callback((HttpContext ctx, string scheme, ClaimsPrincipal claimsPrincipal, AuthenticationProperties props) =>
            {
                signedInClaimsPrincipal = claimsPrincipal;
            })
            .Verifiable();
            ReplacableServiceProvider.Replace(services =>
            {
                services.AddSingleton(authService.Object);
            });

            var accountCtrl = _myApp.CreateController <AccountController>();
            var userManager = _myApp.GetService <UserManager <User> >();
            var userRepo    = _myApp.GetService <IRepository <User> >();

            const string password = "******";
            await userManager.CreateAsync(new User
            {
                UserName     = "******",
                DisplayName  = "Jim Green",
                CreatedAtUtc = DateTime.UtcNow
            }, password);


            // Act
            var userModel = new SigninUserViewModel
            {
                UserName = "******",
                Password = password
            };
            var sigininResult = await accountCtrl.DoSignin(userModel, null);

            // Assert
            Assert.True(accountCtrl.ModelState.IsValid);
            sigininResult.IsType <RedirectResult>();

            authService.Verify();
            Assert.Equal("jim", signedInClaimsPrincipal.ToDiscussionUser(userRepo).UserName);
        }
        public async Task should_return_signin_view_when_username_does_not_exist()
        {
            var accountCtrl = _myApp.CreateController <AccountController>();
            var userModel   = new SigninUserViewModel
            {
                UserName = "******",
                Password = "******"
            };

            var sigininResult = await accountCtrl.DoSignin(userModel, null);


            Assert.False(accountCtrl.HttpContext.IsAuthenticated());
            Assert.False(accountCtrl.ModelState.IsValid);
            Assert.Equal("用户名或密码错误", accountCtrl.ModelState["UserName"].Errors.First().ErrorMessage);

            var viewResult = sigininResult as ViewResult;

            Assert.NotNull(viewResult);
            viewResult.ViewName.ShouldEqual("Signin");
        }
        public async Task should_register_new_user()
        {
            var accountCtrl = _myApp.CreateController <AccountController>();
            var userName    = "******";
            var newUser     = new SigninUserViewModel
            {
                UserName = userName,
                Password = "******"
            };

            var registerResult = await accountCtrl.DoRegister(newUser);

            registerResult.IsType <RedirectResult>();

            var registeredUser = _userRepo.All().FirstOrDefault(user => user.UserName == newUser.UserName);

            registeredUser.ShouldNotBeNull();
            // ReSharper disable once PossibleNullReferenceException
            registeredUser.UserName.ShouldEqual(userName);
            registeredUser.Id.ShouldGreaterThan(0);
        }
        public async Task should_hash_password_for_user()
        {
            var accountCtrl   = _myApp.CreateController <AccountController>();
            var userName      = "******";
            var clearPassword = "******";
            var newUser       = new SigninUserViewModel
            {
                UserName = userName,
                Password = clearPassword
            };

            var registerResult = await accountCtrl.DoRegister(newUser);

            registerResult.IsType <RedirectResult>();

            var registeredUser = _userRepo.All().FirstOrDefault(user => user.UserName == newUser.UserName);

            registeredUser.ShouldNotBeNull();
            // ReSharper disable once PossibleNullReferenceException
            registeredUser.UserName.ShouldEqual(userName);
            registeredUser.HashedPassword.ShouldNotEqual(clearPassword);
        }
        public async Task should_not_register_with_invalid_request()
        {
            var accountCtrl    = _myApp.CreateController <AccountController>();
            var notToBeCreated = "not-to-be-created";
            var newUser        = new SigninUserViewModel
            {
                UserName = notToBeCreated,
                Password = "******"
            };

            accountCtrl.ModelState.AddModelError("UserName", "Some Error");
            var registerResult = await accountCtrl.DoRegister(newUser);


            var userIsRegistered = _userRepo.All().Any(user => user.UserName == notToBeCreated);

            Assert.False(userIsRegistered);

            registerResult.IsType <ViewResult>();
            var viewResult = registerResult as ViewResult;

            // ReSharper disable once PossibleNullReferenceException
            viewResult.ViewName.ShouldEqual("Register");
        }