public void BeLocalRedirectResult_GivenLocalRedirectResult_ShouldPass() { const string testLocalUrl = "testLocalUrl"; ActionResult result = new LocalRedirectResult(testLocalUrl); result.Should().BeLocalRedirectResult(); }
public void Login_LogInUser() { // Arrange Moq.Mock <ILogger <HomeController> > moqLogger = new Mock <ILogger <HomeController> >(); Moq.Mock <IHttpContextAccessor> moqHttpContextAccessor = new Mock <IHttpContextAccessor>(); Moq.Mock <IOptions <ServiceRepositorySettings> > moqServiceRepositorySettings = SettingsHelper.GetMoqServiceRepositorySettings(); Moq.Mock <IGitea> moqGiteaWrappeer = IGiteaMockHelper.GetMock(); IGiteaMockHelper.AddSevenReposForOrg1(moqGiteaWrappeer); Moq.Mock <ISourceControl> moqSourceControl = GetMoqSourceControlForIndexTest(); moqGiteaWrappeer.Setup(g => g.GetUserNameFromUI()).ReturnsAsync("Test"); moqGiteaWrappeer.Setup(g => g.GetSessionAppKey(null)).ReturnsAsync(new System.Collections.Generic.KeyValuePair <string, string>("123", "Test")); AltinnCore.Designer.Controllers.HomeController controller = new AltinnCore.Designer.Controllers.HomeController( moqLogger.Object, moqServiceRepositorySettings.Object, moqGiteaWrappeer.Object, moqHttpContextAccessor.Object, moqSourceControl.Object) { ControllerContext = ControllerContextHelper.GetControllerContextWithValidGiteaSession("234543556", true) }; // Act Task <IActionResult> result = controller.Login(); // Assert LocalRedirectResult redirectResult = Assert.IsType <LocalRedirectResult>(result.Result); Assert.Equal("/", redirectResult.Url); }
public virtual void Execute(ActionContext context, LocalRedirectResult result) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (result == null) { throw new ArgumentNullException(nameof(result)); } var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context); // IsLocalUrl is called to handle Urls starting with '~/'. if (!urlHelper.IsLocalUrl(result.Url)) { throw new InvalidOperationException(Resources.UrlNotLocal); } var destinationUrl = urlHelper.Content(result.Url); _logger.LocalRedirectResultExecuting(destinationUrl); if (result.PreserveMethod) { context.HttpContext.Response.StatusCode = result.Permanent ? StatusCodes.Status308PermanentRedirect : StatusCodes.Status307TemporaryRedirect; context.HttpContext.Response.Headers[HeaderNames.Location] = destinationUrl; } else { context.HttpContext.Response.Redirect(destinationUrl, result.Permanent); } }
public void Login_LogOutUser() { // Arrange Moq.Mock <ILogger <HomeController> > moqLogger = new Mock <ILogger <HomeController> >(); Moq.Mock <IHttpContextAccessor> moqHttpContextAccessor = new Mock <IHttpContextAccessor>(); Moq.Mock <IOptions <ServiceRepositorySettings> > moqServiceRepositorySettings = SettingsHelper.GetMoqServiceRepositorySettings(); Moq.Mock <IGitea> moqGiteaWrapper = IGiteaMockHelper.GetMock(); IGiteaMockHelper.AddSevenReposForOrg1(moqGiteaWrapper); Moq.Mock <ISourceControl> moqSourceControl = GetMoqSourceControlForIndexTest(); User user = new User(); user.Login = "******"; moqGiteaWrapper.Setup(g => g.GetCurrentUser()).ReturnsAsync(user); AltinnCore.Designer.Controllers.HomeController controller = new AltinnCore.Designer.Controllers.HomeController( moqLogger.Object, moqServiceRepositorySettings.Object, moqGiteaWrapper.Object, moqHttpContextAccessor.Object, moqSourceControl.Object) { ControllerContext = ControllerContextHelper.GetControllerContextWithValidGiteaSession("234543556", true) }; // Act Task <IActionResult> result = controller.Logout(); // Assert LocalRedirectResult redirectResult = Assert.IsType <LocalRedirectResult>(result.Result); Assert.Equal("/repos/user/logout", redirectResult.Url); }
public async void Account_LoginPost_ReturnsRedirect_WhenAuthenticationPasswordSuccess() { // Arrange // mocking async context object var authServiceMock = new Mock <IAuthenticationService>(); authServiceMock .Setup(s => s.SignInAsync(It.IsAny <HttpContext>(), CookieAuthenticationDefaults.AuthenticationScheme, Mock.Of <ClaimsPrincipal>(), It.IsAny <AuthenticationProperties>())). Returns(Task.FromResult(true)); var servicesProviderMock = new Mock <IServiceProvider>(); servicesProviderMock .Setup(sp => sp.GetService(typeof(IAuthenticationService))) .Returns(authServiceMock.Object); servicesProviderMock .Setup(sp => sp.GetService(typeof(IUrlHelperFactory))).Returns(new UrlHelperFactory()); ITempDataProvider tempDataProvider = Mock.Of <ITempDataProvider>(); servicesProviderMock .Setup(sp => sp.GetService(typeof(ITempDataDictionaryFactory))) .Returns(new TempDataDictionaryFactory(tempDataProvider)); var context = new ControllerContext { HttpContext = new DefaultHttpContext() }; context.HttpContext.RequestServices = servicesProviderMock.Object; // Getting configuration files string projectPath = string.Concat(AppDomain.CurrentDomain.BaseDirectory.Split(new String[] { @"bin\" }, StringSplitOptions.None)[0], @"AppSettingsFiles"); IConfiguration _configuration = new ConfigurationBuilder() .SetBasePath(projectPath) .AddJsonFile("Complete.json") .Build(); var controller = new AccountController(_configuration) { ControllerContext = context }; string loginName = "userTest"; string password = "******"; bool rememberMe = false; // Act LocalRedirectResult result = await controller.Login(loginName, password, rememberMe) as LocalRedirectResult; // Assert var viewResult = Assert.IsType <LocalRedirectResult>(result); Assert.NotNull(viewResult); Assert.Equal("/Home/Index", viewResult.Url); }
public static LinkGenerationTestContext FromLocalRedirectResult(LocalRedirectResult localRedirectResult) { return(new LinkGenerationTestContext { Location = localRedirectResult.Url, UrlHelper = localRedirectResult.UrlHelper }); }
public void WithLocalUrl_GivenUnexpectedLocalUrl_ShouldFail() { const string actualLocalUrl = TestLocalUrl; const string expectedLocalUrl = "otherUrl"; ActionResult result = new LocalRedirectResult(TestLocalUrl); var failureMessage = FailureMessageHelper.ExpectedContextToBeXButY("LocalRedirectResult.LocalUrl", expectedLocalUrl, actualLocalUrl); Action a = () => result.Should().BeLocalRedirectResult().WithLocalUrl(expectedLocalUrl, Reason, ReasonArgs); a.Should().Throw <Exception>().WithMessage(failureMessage); }
public void Constructor_WithParameterUrlAndPermanent_SetsResultUrlPermanentAndPreserveMethod() { // Arrange var url = "/test/url"; // Act var result = new LocalRedirectResult(url, permanent: true, preserveMethod: true); // Assert Assert.True(result.PreserveMethod); Assert.True(result.Permanent); Assert.Same(url, result.Url); }
public void Constructor_WithParameterUrl_SetsResultUrlAndNotPermanentOrPreserveMethod() { // Arrange var url = "/test/url"; // Act var result = new LocalRedirectResult(url); // Assert Assert.False(result.PreserveMethod); Assert.False(result.Permanent); Assert.Same(url, result.Url); }
public void WithPreserveMethod_GivenUnexpectedPreserveMethod_ShouldFail() { var actualPreserveMethod = true; var expectedPreserveMethod = false; ActionResult result = new LocalRedirectResult(TestLocalUrl) { PreserveMethod = actualPreserveMethod }; var failureMessage = FailureMessageHelper.ExpectedContextToBeXButY("LocalRedirectResult.PreserveMethod", expectedPreserveMethod, actualPreserveMethod); Action a = () => result.Should().BeLocalRedirectResult().WithPreserveMethod(expectedPreserveMethod, Reason, ReasonArgs); a.Should().Throw <Exception>().WithMessage(failureMessage); }
public void WithPermanent_GivenUnexpectedPermanent_ShouldFail() { var actualPermanent = true; var expectedPermanent = false; ActionResult result = new LocalRedirectResult(TestLocalUrl) { Permanent = actualPermanent }; var failureMessage = FailureMessageHelper.ExpectedContextToBeXButY("LocalRedirectResult.Permanent", expectedPermanent, actualPermanent); Action a = () => result.Should().BeLocalRedirectResult().WithPermanent(expectedPermanent, Reason, ReasonArgs); a.Should().Throw <Exception>().WithMessage(failureMessage); }
public async void Account_LogOut_ReturnsAView_Success() { // Arrange var controller = GetAccountControllerSignOut(); // Act LocalRedirectResult result = await controller.Logout() as LocalRedirectResult; // Assert var viewResult = Assert.IsType <LocalRedirectResult>(result); Assert.NotNull(viewResult); Assert.Equal("/Home/Index", viewResult.Url); }
public async Task Execute_Throws_ForNonLocalUrl( string appRoot, string contentPath) { // Arrange var httpContext = GetHttpContext(appRoot); var result = new LocalRedirectResult(contentPath); // Act & Assert var exception = await Assert.ThrowsAsync <InvalidOperationException>(() => result.ExecuteAsync(httpContext)); Assert.Equal( "The supplied URL is not local. A URL with an absolute path is considered local if it does not " + "have a host/authority part. URLs using virtual paths ('~/') are also local.", exception.Message); }
public void Execute(ActionContext context, LocalRedirectResult result) { var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context); // IsLocalUrl is called to handle Urls starting with '~/'. var destinationUrl = result.Url; if (!urlHelper.IsLocalUrl(result.Url)) { throw new InvalidOperationException(Resources.UrlNotLocal); } destinationUrl = urlHelper.Content(result.Url); _logger.LocalRedirectResultExecuting(destinationUrl); context.HttpContext.Response.Redirect(destinationUrl, result.Permanent); }
public async Task Execute_ReturnsExpectedValues() { // Arrange var appRoot = "/"; var contentPath = "~/Home/About"; var expectedPath = "/Home/About"; var httpContext = GetHttpContext(appRoot); var result = new LocalRedirectResult(contentPath); // Act await result.ExecuteAsync(httpContext); // Assert Assert.Equal(expectedPath, httpContext.Response.Headers.Location.ToString()); Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode); }
public async Task <IActionResult> Logon(string username, string userpwd, string language, string returnUrl) { string errorMsg = string.Empty; string currLanguage = language.IsMissing() ? "ZhCn" : language; //管理员账号 var developer = FapPlatformConstants.Administrator; //获取用户 FapUser loginUser = _loginService.Login(username); Employee emp = null; LocalRedirectResult errorResult = CheckUser(); if (errorResult != null) { return(errorResult); } LoginLogging(); var claimsPrincipal = CreateClaimsPrincipal(); var authenticationProperties = CreateAuthenticationProperties(); //设置当前角色为普通员工 //_applicationContext.CurrentRoleUid =FapPlatformConstants.CommonUserRoleFid; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authenticationProperties).ConfigureAwait(false); return(Redirect()); LocalRedirectResult CheckUser() { PasswordHasher passwordHasher = new PasswordHasher(); if (loginUser == null) { errorMsg = GetOrAddPageMultiLanguageContent("login_page_no_exist_user", "不存在此用户"); } else if (loginUser.EnableState == 0) { errorMsg = GetOrAddPageMultiLanguageContent("login_page_forbidden_user", "该账户已被禁用"); } else if (loginUser.IsLocked == 1) { errorMsg = GetOrAddPageMultiLanguageContent("login_page_lock_user", "该账户暂被锁定"); } else if (!passwordHasher.VerifyHashedPassword(loginUser.UserPassword, userpwd)) { errorMsg = GetOrAddPageMultiLanguageContent("login_page_password_error", "密码不正确"); //增加尝试次数,超过5次冻结 _loginService.AddTryTimes(loginUser); } else if (loginUser.UserIdentity.IsMissing() && loginUser.UserName != developer) { errorMsg = GetOrAddPageMultiLanguageContent("login_page_no_mapping_employee", "此用户没有关联人员信息"); } else { if (loginUser.UserIdentity.IsMissing()) { if (loginUser.UserName.EqualsWithIgnoreCase(developer)) { emp = new Employee { Fid = "00000000000000000000", EmpCode = "Administrator", EmpName = "Administrator" }; } else { errorMsg = GetOrAddPageMultiLanguageContent("login_page_no_find_mapping_employee", "用户关联的人员不存在"); } } else { emp = _dbContext.QueryFirstOrDefault <Employee>("select Fid,EmpCode,EmpName,DeptUid,DeptCode,EmpPhoto,GroupUid,OrgUid from Employee where Fid=@Fid", new Dapper.DynamicParameters(new { Fid = loginUser.UserIdentity }), true); if (emp == null) { errorMsg = GetOrAddPageMultiLanguageContent("login_page_no_find_mapping_employee", "用户关联的人员不存在");; } } } if (errorMsg.IsPresent()) { string loginUrl = _configService.GetSysParamValue(LoginUrl);// FapPlatformConfig.PlatformLoginUrl; if (loginUrl.IsMissing()) { loginUrl = "~/"; } return(LocalRedirect(loginUrl + "?msg=" + System.Net.WebUtility.UrlEncode(errorMsg))); } return(null); } void LoginLogging() { //更新最近登录时间 loginUser.LastLoginTime = DateTimeUtils.CurrentDateTimeStr; loginUser.PasswordTryTimes = 0; _loginService.UpdateLastLoginTime(loginUser); } ClaimsPrincipal CreateClaimsPrincipal() { //初始化身份卡片 var claims = new List <Claim> { new Claim(ClaimTypes.Name, loginUser.UserName), //用户名 new Claim(ClaimTypes.UserData, loginUser.Fid), //用户Fid new Claim(ClaimTypes.NameIdentifier, loginUser.UserIdentity), //员工Fid new Claim(ClaimTypes.Surname, emp.EmpName), //员工姓名 new Claim(ClaimTypes.PrimarySid, emp.DeptUid ?? "-"), //员工部门 new Claim(ClaimTypes.PrimaryGroupSid, emp.DeptCode ?? ""), //部门编码 new Claim(ClaimTypes.System, emp.DeptUidMC ?? ""), //部门名称 new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, emp.GroupUid ?? ""), //集团 new Claim(ClaimTypes.DenyOnlyPrimarySid, emp.OrgUid ?? ""), //组织 new Claim(ClaimTypes.Sid, currLanguage), //语言 new Claim(ClaimTypes.Actor, emp.EmpPhoto), //用户图像 new Claim(ClaimTypes.Role, loginUser.UserRole) //角色普通用户 }; //组装身份 var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); return(new ClaimsPrincipal(claimsIdentity)); } AuthenticationProperties CreateAuthenticationProperties() { return(new AuthenticationProperties { //AllowRefresh = <bool>, // Refreshing the authentication session should be allowed. //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(1), // The time at which the authentication ticket expires. A // value set here overrides the ExpireTimeSpan option of // CookieAuthenticationOptions set with AddCookie. IsPersistent = true, // Whether the authentication session is persisted across // multiple requests. Required when setting the // ExpireTimeSpan option of CookieAuthenticationOptions // set with AddCookie. Also required when setting // ExpiresUtc. //IssuedUtc = <DateTimeOffset>, // The time at which the authentication ticket was issued. //RedirectUri = <string> // The full path or absolute URI to be used as an http // redirect response value. }); } LocalRedirectResult Redirect() { if (returnUrl.IsMissing()) { if (userpwd == _configService.GetSysParamValue("employee.user.password")) { //等于默认密码需要跳转到修改密码页 return(LocalRedirect("~/Home/MainFrame#Home/ResetPassword/1")); } else { if (_rbacService.IsCEO(emp.Fid)) { return(LocalRedirect("~/Home/MainFrame#System/Report/CEOChart")); } else { return(LocalRedirect(_configService.GetSysParamValue(HomeUrl))); } } } else { return(LocalRedirect(HttpUtility.UrlDecode(returnUrl))); } } }
public ActionResult cwbb_main() { LocalRedirectResult lrr = LocalRedirect("/sbzs-cjpt-web/biz/setting/cwbbydy?gos=true&gdslxDm=1&skssqQ=2019-08-01&biz=null&kjzdzzDm=102&ywbm=CWBBYDY&isCwbabz=Y&tjNd=2019&sssqZ=2019-08-31&bbbsqDm=4&bzz=dzswj&skssqZ=2019-08-31&sssqQ=2019-08-01&zlbsxlDm=&tjYf=09&gsdq=152"); return(lrr); }
/// <summary> /// Initializes a new instance of the <see cref="LocalRedirectResultAssertions" /> class. /// </summary> /// <param name="subject">The object to test assertion on</param> public LocalRedirectResultAssertions(LocalRedirectResult subject) : base(subject) { }
public LocalRedirectResultAssertions(LocalRedirectResult localRedirectResult) { _localRedirectResult = localRedirectResult; }