public void Follow_Request() { var userManager = new UserManager <ApplicationUser>(new TestUserStore()); MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = getApplicationUser(); var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); principal.SetupGet(x => x.Identity.Name).Returns("adarsh"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new SocialGoalUser(ticket); string[] userRoles = { goalsetterUser.RoleName }; principal.Setup(x => x.Identity).Returns(goalsetterUser); userRepository.Setup(x => x.Get(It.IsAny <Expression <Func <ApplicationUser, bool> > >())).Returns(applicationUser); Mapper.CreateMap <FollowRequestFormModel, FollowRequest>(); var result = controller.FollowRequest("402bd590-fdc7-49ad-9728-40efbfe512ec") as RedirectToRouteResult; Assert.AreEqual("UserProfile", result.RouteValues["action"]); }
public void Edit_Personal_Info() { var userManager = new UserManager <ApplicationUser>(new TestUserStore()); MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = getApplicationUser(); var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); principal.SetupGet(x => x.Identity.Name).Returns("adarsh"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new SocialGoalUser(ticket); string[] userRoles = { goalsetterUser.RoleName }; principal.Setup(x => x.Identity).Returns(goalsetterUser); UserProfile grpuser = new UserProfile() { UserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", Address = "t", City = "t", State = "*****@*****.**", }; userProfileRepository.Setup(x => x.Get(It.IsAny <Expression <Func <UserProfile, bool> > >())).Returns(grpuser); Mapper.CreateMap <UserProfile, UserProfileFormModel>(); PartialViewResult result = controller.EditPersonalInfo() as PartialViewResult; Assert.IsNotNull(result); Assert.IsInstanceOfType(typeof(UserProfileFormModel), result.ViewData.Model, "WrongType"); var data = result.ViewData.Model as UserProfileFormModel; Assert.AreEqual("t", data.Address); }
public void Image_Upload_GetView() { var userManager = new UserManager <ApplicationUser>(new TestUserStore()); MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = new ApplicationUser() { Activated = true, Email = "*****@*****.**", FirstName = "Adarsh", LastName = "Vikraman", RoleId = 0 }; var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); principal.SetupGet(x => x.Identity.Name).Returns("adarsh"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new SocialGoalUser(ticket); string[] userRoles = { goalsetterUser.RoleName }; principal.Setup(x => x.Identity).Returns(goalsetterUser); userRepository.Setup(x => x.Get(It.IsAny <Expression <Func <ApplicationUser, bool> > >())).Returns(applicationUser); PartialViewResult result = controller.ImageUpload() as PartialViewResult; Assert.IsNotNull(result); Assert.IsInstanceOfType(typeof(UploadImageViewModel), result.ViewData.Model, "Wrong model"); var data = result.ViewData.Model as UploadImageViewModel; Assert.AreEqual(null, data.LocalPath, "not matching"); }
public void WhenSettingAuthenticationCookieFromTicket_ThenAddsToResponseCookie() { var cookies = new HttpCookieCollection(); var formsAuth = new DefaultFormsAuthentication(); var context = MvcMockHelpers.FakeHttpContext(); var responseMock = Mock.Get(context.Response); responseMock.Setup(r => r.Cookies).Returns(cookies); formsAuth.SetAuthCookie(context, new FormsAuthenticationTicket("TestName", false, 55)); Assert.NotNull(cookies[FormsAuthentication.FormsCookieName]); Assert.Equal("TestName", FormsAuthentication.Decrypt(cookies[FormsAuthentication.FormsCookieName].Value).Name); }
public void WhenSettingAuthenticationCookieFromTicket_ThenSetsExpiryFromFormsAuthenticationTimeoutValue() { var cookies = new HttpCookieCollection(); var formsAuth = new DefaultFormsAuthentication(); var context = MvcMockHelpers.FakeHttpContext(); var responseMock = Mock.Get(context.Response); responseMock.Setup(r => r.Cookies).Returns(cookies); formsAuth.SetAuthCookie(context, new FormsAuthenticationTicket("TestName", false, 55)); var cookie = cookies[FormsAuthentication.FormsCookieName]; var now = DateTime.Now; var formsTimeout = FormsAuthentication.Timeout; // assumes test can run +/- 1 minute Assert.True(cookie.Expires >= now.AddMinutes(formsTimeout.Minutes - 1)); Assert.True(cookie.Expires <= now.AddMinutes(formsTimeout.Minutes + 1)); }
private void PostAuthenticateRequestHandler(object sender, EventArgs e) { HttpCookie authCookie = this.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value)) { //var formsAuthentication = DependencyResolver.Current.GetService<IFormsAuthentication>(); IFormsAuthentication formsAuthentication = new DefaultFormsAuthentication(); var ticket = formsAuthentication.Decrypt(authCookie.Value); try { var mvcUser = new MVCUser(ticket); this.Context.User = new GenericPrincipal(mvcUser, null); formsAuthentication.SetAuthCookie(this.Context, ticket); } catch { //清掉Session重登 formsAuthentication.Signout(); HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null); } } }
public void Followings_list() { var userManager = new UserManager <ApplicationUser>(new TestUserStore()); MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = getApplicationUser(); var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new SocialGoalUser(ticket); principal.Setup(x => x.Identity).Returns(goalsetterUser); IEnumerable <FollowUser> fakeuser = new List <FollowUser> { new FollowUser { FollowUserId = 1, Accepted = false, FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed", }, new FollowUser { FollowUserId = 2, Accepted = false, FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ee" }, }; followUserRepository.Setup(x => x.GetMany(It.IsAny <Expression <Func <FollowUser, bool> > >())).Returns(fakeuser); Mapper.CreateMap <ApplicationUser, FollowersViewModel>(); ViewResult result = controller.Followings() as ViewResult; Assert.IsNotNull(result); Assert.IsInstanceOfType(typeof(IEnumerable <FollowingViewModel>), result.ViewData.Model, "WrongType"); var data = result.ViewData.Model as IEnumerable <FollowingViewModel>; Assert.AreEqual(2, data.Count()); }
public void UserProfile() { var userManager = new UserManager <ApplicationUser>(new TestUserStore()); MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = getApplicationUser(); var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); userRepository.Setup(x => x.Get(It.IsAny <Expression <Func <ApplicationUser, bool> > >())).Returns(applicationUser); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); principal.SetupGet(x => x.Identity.Name).Returns("adarsh"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new SocialGoalUser(ticket); string[] userRoles = { goalsetterUser.RoleName }; principal.Setup(x => x.Identity).Returns(goalsetterUser); UserProfile prfil = new UserProfile() { FirstName = "Adarsh", LastName = "Vikraman", DateOfBirth = DateTime.Now, Gender = true, Address = "a", City = "a", State = "a", Country = "a", ZipCode = 2344545, ContactNo = 1223344556, UserId = "402bd590-fdc7-49ad-9728-40efbfe512ec" }; userProfileRepository.Setup(x => x.Get(It.IsAny <Expression <Func <UserProfile, bool> > >())).Returns(prfil); IEnumerable <FollowRequest> fake = new List <FollowRequest> { new FollowRequest { FollowRequestId = 1, FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed" }, new FollowRequest { FollowRequestId = 2, FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ee" }, }; followRequestRepository.Setup(x => x.GetMany(It.IsAny <Expression <Func <FollowRequest, bool> > >())).Returns(fake); IEnumerable <FollowUser> fakeuser = new List <FollowUser> { new FollowUser { FollowUserId = 1, Accepted = false, FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed" }, new FollowUser { FollowUserId = 2, Accepted = false, FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ee" }, }; followUserRepository.Setup(x => x.GetMany(It.IsAny <Expression <Func <FollowUser, bool> > >())).Returns(fakeuser); ViewResult result = controller.UserProfile("402bd590-fdc7-49ad-9728-40efbfe512ec") as ViewResult; Assert.IsNotNull(result); Assert.IsInstanceOfType(typeof(UserProfileViewModel), result.ViewData.Model, "WrongType"); var data = result.ViewData.Model as UserProfileViewModel; Assert.AreEqual("adarsh", data.UserName); }
public void Add_GroupUser() { Guid guidToken = Guid.NewGuid(); SecurityToken token = new SecurityToken() { SecurityTokenId = 1, Token = guidToken, ActualID = 1 }; securityTokenRepository.Setup(x => x.Get(It.IsAny <Expression <Func <SecurityToken, bool> > >())).Returns(token); MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = getApplicationUser(); var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); EmailRequestController controller = new EmailRequestController(securityTokenService, groupUserService, supportService, groupInvitationService); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new SocialGoalUser(ticket); principal.Setup(x => x.Identity).Returns(goalsetterUser); var httprequest = new HttpRequest("", "http://yoursite/", ""); var stringWriter = new StringWriter(); var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httprequest, httpResponce); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; //HttpContext.Current.Request.Session["somevalue"]; controller.TempData = tempData.Object; controller.TempData["grToken"] = guidToken; var result = controller.AddGroupUser() as RedirectToRouteResult; Assert.AreEqual("Index", result.RouteValues["action"]); }
public void Index_If_AjaxRequest_IsNull() { MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = getApplicationUser(); var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); userRepository.Setup(x => x.Get(It.IsAny <Expression <Func <ApplicationUser, bool> > >())).Returns(applicationUser); NotificationController controller = new NotificationController(goalService, updateService, commentService, groupInvitationService, supportInvitationService, followRequestService, userService); principal.SetupGet(x => x.Identity.Name).Returns("adarsh"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new MuhendislerBuradaUser(ticket); string[] userRoles = { goalsetterUser.RoleName }; principal.Setup(x => x.Identity).Returns(goalsetterUser); IEnumerable <GroupInvitation> groupInvitation = new List <GroupInvitation> { new GroupInvitation { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec" }, new GroupInvitation { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed", }, new GroupInvitation { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ee" }, }.AsEnumerable(); groupInvitationRepository.Setup(x => x.GetAll()).Returns(groupInvitation); IEnumerable <SupportInvitation> supportInvitation = new List <SupportInvitation> { new SupportInvitation { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec" }, new SupportInvitation { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed" }, new SupportInvitation { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ee" }, }.AsEnumerable(); supportInvitationRepository.Setup(x => x.GetAll()).Returns(supportInvitation); IEnumerable <FollowRequest> followInvitation = new List <FollowRequest> { new FollowRequest { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec" }, new FollowRequest { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ed" }, new FollowRequest { Accepted = false, ToUserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", FromUserId = "402bd590-fdc7-49ad-9728-40efbfe512ee" }, }.AsEnumerable(); followRequestRepository.Setup(x => x.GetMany(It.IsAny <Expression <Func <FollowRequest, bool> > >())).Returns(followInvitation); Mapper.CreateMap <GroupInvitation, NotificationViewModel>(); Mapper.CreateMap <SupportInvitation, NotificationViewModel>(); Mapper.CreateMap <FollowRequest, NotificationViewModel>(); ViewResult result = controller.Index(1) as ViewResult; Assert.IsNotNull(result); }
public JsonResult Index(LoginViewModel model, string requestUrl) { try { if (ModelState.IsValid) { using (TestEntities db = new TestEntities()) { LogOnStatus status = LogOnStatus.Failure; var currentDate = DateTime.Now; var user = db.Users.Where(x => x.Account == model.Account).SingleOrDefault(); if (user != null) { if (user.PasswordHash == model.Password) { //成功的流程 寫入登入時間 status = LogOnStatus.Successful; user.DateLastLogin = currentDate; db.Entry <Users>(user).State = EntityState.Modified; db.SaveChanges(); } else { status = LogOnStatus.FailPassword; } } else { status = LogOnStatus.NotExist; } switch (status) { case LogOnStatus.Successful: //note: AuthenticationTicketUserData userInfo = new AuthenticationTicketUserData { UserId = user.Account, Name = user.Name }; //當都沒有權限 則會用GUEST List <string> roles = new List <string>(); if (user.Roles.Count == 0) { roles.Add("Guest"); } else { roles = user.Roles.Select(x => x.RoleID).ToList(); } userInfo.Roles = roles; IFormsAuthentication _formAuthentication = new DefaultFormsAuthentication(); //IFormsAuthentication _formAuthentication = DependencyResolver.Current.GetService<IFormsAuthentication>(); _formAuthentication.SetAuthCookie(this.HttpContext, new FormsAuthenticationTicket(1, userInfo.UserId, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userInfo.ToString())); var cookies = HttpContext.Request.Cookies.AllKeys; if (cookies.Contains(SiteConst.RememberCookie)) { string rem_cookie = HttpContext.Request.Cookies[SiteConst.RememberCookie].Values["account"]; //記住帳號實做 if (model.RememberMe) { if (string.IsNullOrEmpty(rem_cookie)) { HttpCookie cookie = new HttpCookie(SiteConst.RememberCookie); cookie["account"] = model.Account; cookie.Expires = DateTime.Now.AddYears(100); Response.Cookies.Add(cookie); } else { if (rem_cookie != model.Account) { this.Request.Cookies[SiteConst.RememberCookie].Expires = DateTime.Now.AddHours(-1); Response.Cookies.Add(Request.Cookies[SiteConst.RememberCookie]); HttpCookie cookie = new HttpCookie(SiteConst.RememberCookie); cookie["account"] = model.Account; cookie.Expires = DateTime.Now.AddYears(100); Response.Cookies.Add(cookie); } } } else { if (!string.IsNullOrEmpty(rem_cookie)) { this.Request.Cookies[SiteConst.RememberCookie].Expires = DateTime.Now.AddHours(-1); Response.Cookies.Add(Request.Cookies[SiteConst.RememberCookie]); } } } else { HttpCookie cookie = new HttpCookie(SiteConst.RememberCookie); cookie["account"] = model.Account; cookie.Expires = DateTime.Now.AddYears(100); Response.Cookies.Add(cookie); } var returnUrlBack = requestUrl; if (!Url.IsLocalUrl(requestUrl)) { returnUrlBack = Url.Action("Index", "Home"); } return(Json(new { success = true, returnUrl = returnUrlBack })); case LogOnStatus.Disabled: ModelState.AddModelError("", "該帳號已被停權"); break; case LogOnStatus.Failure: ModelState.AddModelError("", "帳號或密碼錯誤"); break; case LogOnStatus.UnActived: ModelState.AddModelError("", "帳號尚未啟用"); break; default: ModelState.AddModelError("", "帳號或密碼錯誤"); break; } } } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); _logger.Info("Index - Error{0}", ex.Message); } finally { _logger.Info("Index - end"); } // If we got this far, something failed return(Json(new { errors = ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage)) })); }