public void GetProfileDataAsync_UserFound_NoClaimsRequested_NoIssuedClaims()
        {
            // Arrange
            var userId = Guid.NewGuid();

            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var user = new MembershipUser();

            A.CallTo(() => membershipService.GetUserAsync(userId)).Returns(Task.FromResult(user));

            var context = new ProfileDataRequestContext
            {
                Subject = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>
                {
                    new Claim(Constants.ClaimTypes.Subject, userId.ToString("N"))
                })),
                AllClaimsRequested  = false,
                RequestedClaimTypes = new List <string>()
            };

            var service = new MembershipUserService(options, membershipService, roleService);

            // Act
            service.GetProfileDataAsync(context).Wait();

            // Assert
            context.IssuedClaims.Should().BeNullOrEmpty();

            A.CallTo(() => membershipService.GetUserAsync(userId));
        }
        public void AuthenticateLocalAsync_UserValidationFails_AuthenticateResultIsNull()
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new LocalAuthenticationContext {
                UserName = "******", Password = "******"
            };

            A.CallTo(() => membershipService.GetUserAsync("*****@*****.**"))
            .Returns(Task.FromResult(new MembershipUser {
                IsLockedOut = false
            }));

            A.CallTo(() => membershipService.ValidateUser("*****@*****.**", "password123"))
            .Returns(Task.FromResult(false));

            var service = new MembershipUserService(options, membershipService, roleService);

            // Act
            service.AuthenticateLocalAsync(context).Wait();

            // Assert
            context.AuthenticateResult.Should().BeNull();

            A.CallTo(() => membershipService.GetUserAsync("*****@*****.**")).MustHaveHappened();
            A.CallTo(() => membershipService.ValidateUser("*****@*****.**", "password123")).MustHaveHappened();
        }
        public void GetProfileDataAsync_UserNotFound_ThrowsArgumentException()
        {
            // Arrange
            var userId = Guid.NewGuid();

            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            A.CallTo(() => membershipService.GetUserAsync(userId)).Returns(Task.FromResult((MembershipUser)null));

            var context = new ProfileDataRequestContext
            {
                Subject = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>
                {
                    new Claim(Constants.ClaimTypes.Subject, userId.ToString("N"))
                }))
            };

            var service = new MembershipUserService(options, membershipService, roleService);

            Action getProfileDataAsync = () => service.GetProfileDataAsync(context).Wait();

            // Act
            getProfileDataAsync.Should().Throw <ArgumentException>().WithMessage("Invalid subject identifier");

            // Assert
            A.CallTo(() => membershipService.GetUserAsync(userId)).MustHaveHappened();
        }
        public void GetProfileDataAsync_UserFound_AllClaimsRequested_RolesIncluded_NoIssuedClaims()
        {
            // Arrange
            var userId = Guid.NewGuid();

            var options = new MembershipOptions
            {
                UseRoleProviderSource = true,
                IdentityProvider      = "idsvr"
            };
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var user = new MembershipUser
            {
                UserId      = userId,
                UserName    = "******",
                Email       = "*****@*****.**",
                IsLockedOut = false
            };

            A.CallTo(() => membershipService.GetUserAsync(userId))
            .Returns(Task.FromResult(user));
            A.CallTo(() => roleService.GetRolesForUser("*****@*****.**"))
            .Returns(Task.FromResult(new[] { "role1", "role2", "role3" }));

            var context = new ProfileDataRequestContext
            {
                Subject = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>
                {
                    new Claim(Constants.ClaimTypes.Subject, userId.ToString("N"))
                })),
                AllClaimsRequested  = true,
                RequestedClaimTypes = new List <string>()
            };

            var service = new MembershipUserService(options, membershipService, roleService);

            // Act
            service.GetProfileDataAsync(context).Wait();

            // Assert
            var issuedClaims = context.IssuedClaims.ToList();

            issuedClaims.Should().HaveCount(11);

            issuedClaims.ShouldContain(JwtClaimTypes.Subject, userId.ToString("N"));
            issuedClaims.ShouldContain(JwtClaimTypes.PreferredUserName, "*****@*****.**");
            issuedClaims.ShouldContain(JwtClaimTypes.Email, "*****@*****.**");
            issuedClaims.ShouldContain(JwtClaimTypes.IdentityProvider, "idsvr");

            issuedClaims.ShouldContain(JwtClaimTypes.Role, "role1");
            issuedClaims.ShouldContain(JwtClaimTypes.Role, "role2");
            issuedClaims.ShouldContain(JwtClaimTypes.Role, "role3");

            A.CallTo(() => membershipService.GetUserAsync(userId));
        }
        public void AuthenticateLocalAsync_UserValid_RolesNotIncluded_AuthenticateResultSet()
        {
            // Arrange
            var userId = Guid.NewGuid();

            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new LocalAuthenticationContext {
                UserName = "******", Password = "******"
            };

            A.CallTo(() => membershipService.GetUserAsync("*****@*****.**"))
            .Returns(Task.FromResult(new MembershipUser
            {
                UserId      = userId,
                UserName    = "******",
                Email       = "*****@*****.**",
                IsLockedOut = false
            }));

            A.CallTo(() => membershipService.ValidateUser("*****@*****.**", "password123"))
            .Returns(Task.FromResult(true));

            var service = new MembershipUserService(options, membershipService, roleService);

            // Act
            service.AuthenticateLocalAsync(context).Wait();

            // Assert
            context.AuthenticateResult.Should().NotBeNull();
            context.AuthenticateResult.HasSubject.Should().BeTrue();

            var issuedClaims = context.AuthenticateResult.User.Claims.ToList();

            issuedClaims.Should().HaveCount(10);

            issuedClaims.ShouldContain(Constants.ClaimTypes.Subject, userId.ToString("N"));
            issuedClaims.ShouldContain(Constants.ClaimTypes.Name, "*****@*****.**");
            issuedClaims.ShouldContain(Constants.ClaimTypes.AuthenticationMethod, "password");
            issuedClaims.ShouldContain(Constants.ClaimTypes.IdentityProvider, "idsrv");
            issuedClaims.ShouldContain(Constants.ClaimTypes.AuthenticationTime);
            issuedClaims.ShouldContain(Constants.ClaimTypes.PreferredUserName, "*****@*****.**");
            issuedClaims.ShouldContain(Constants.ClaimTypes.Email, "*****@*****.**");

            A.CallTo(() => membershipService.GetUserAsync("*****@*****.**")).MustHaveHappened();
            A.CallTo(() => membershipService.ValidateUser("*****@*****.**", "password123")).MustHaveHappened();
        }
        public void IsActiveAsync_SubjectNull_ContextIsNotActive()
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new IsActiveContext(new ClaimsPrincipal(new ClaimsIdentity()), new Client());

            var service = new MembershipUserService(options, membershipService, roleService);

            Action isActiveAsync = () => service.IsActiveAsync(context).Wait();

            // Act + Assert
            isActiveAsync.Should().Throw <InvalidOperationException>().And.Message.Should().Be("sub claim is missing");
        }
        public void GetProfileDataAsync_SubjectClaimMissing_ThrowsInvalidOperationException()
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new ProfileDataRequestContext
            {
                Subject = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>()))
            };

            var service = new MembershipUserService(options, membershipService, roleService);

            Action getProfileDataAsync = () => service.GetProfileDataAsync(context).Wait();

            // Act + Assert
            getProfileDataAsync.Should().Throw <InvalidOperationException>();
        }
        public void GetProfileDataAsync_SubjectNull_ThrowsArgumentNullException()
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new ProfileDataRequestContext {
                Subject = null
            };

            var service = new MembershipUserService(options, membershipService, roleService);

            Action getProfileDataAsync = () => service.GetProfileDataAsync(context).Wait();

            // Act + Assert
            getProfileDataAsync.Should().Throw <ArgumentNullException>()
            .And.ParamName.Should().Be("subject");
        }
        public void AuthenticateLocalAsync_UsernameNullOrEmpty_AuthenticateResultIsNull(string username)
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new LocalAuthenticationContext {
                UserName = username
            };

            var service = new MembershipUserService(options, membershipService, roleService);

            // Act
            service.AuthenticateLocalAsync(context).Wait();

            // Assert
            context.AuthenticateResult.Should().BeNull();
        }
        public void GetProfileDataAsync_SubjectClaimInvalid_ThrowsArgumentException(string subjectId)
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new ProfileDataRequestContext
            {
                Subject = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>
                {
                    new Claim(Constants.ClaimTypes.Subject, subjectId)
                }))
            };

            var service = new MembershipUserService(options, membershipService, roleService);

            Action getProfileDataAsync = () => service.GetProfileDataAsync(context).Wait();

            // Act + Assert
            getProfileDataAsync.Should().Throw <ArgumentException>().WithMessage("Invalid subject identifier");
        }
        public void IsActiveAsync_SubjectClaimInvalid_ContextIsNotActive(string subjectId)
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new IsActiveContext(
                new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                new Claim(Constants.ClaimTypes.Subject, subjectId)
            })),
                new Client()
                );

            var service = new MembershipUserService(options, membershipService, roleService);

            // Act
            service.IsActiveAsync(context).Wait();

            // Assert
            context.IsActive.Should().BeFalse();
        }
        public void AuthenticateLocalAsync_UserNotFound_AuthenticateResultIsNull()
        {
            // Arrange
            var options           = new MembershipOptions();
            var membershipService = A.Fake <IMembershipService>();
            var roleService       = A.Fake <IRoleService>();

            var context = new LocalAuthenticationContext {
                UserName = "******"
            };

            A.CallTo(() => membershipService.GetUserAsync("*****@*****.**"))
            .Returns(Task.FromResult((MembershipUser)null));

            var service = new MembershipUserService(options, membershipService, roleService);

            // Act
            service.AuthenticateLocalAsync(context).Wait();

            // Assert
            context.AuthenticateResult.Should().BeNull();

            A.CallTo(() => membershipService.GetUserAsync("*****@*****.**")).MustHaveHappened();
        }
Example #13
0
        /// <summary>
        /// 在一个action被执行前调用
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            int productid = 1;
            BaseController control = filterContext.Controller as BaseController;

            //跳过对/Base/的任何检查
            if (control != null && control.GetType() == typeof(BaseController))
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            string LoginIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] as string;
            //用户权限较验
            CRMService crm = new CRMService();

            //获得当前用户的登陆信息
            CookieUserInfo cui = MembershipService.GetUserCookie();
            //CookieUserInfo cui = new CookieUserInfo() { UserID = "1", UserName = "******", LoginGuid = Guid.NewGuid().ToString() };
            Int32? userid = null;
            if (cui != null)
            {
                userid = Convert.ToInt32(cui.UserID);
                Hashtable counthtparm = new Hashtable();
                counthtparm["UserID"] = userid.Value;
                counthtparm["LoginIP"] = LoginIP;
                int countIP = CRMMapper.Get().QueryForObject<int>("BlackIP.MyFind", counthtparm);
                if (countIP != 0)
                {
                    filterContext.Result = new RedirectResult("/Base/IPError.mvc");
                }
            }
            else
            {
                userid = -1;
                Hashtable counthtparm = new Hashtable();
                counthtparm["UserID"] = userid.Value;
                counthtparm["LoginIP"] = LoginIP;
                int countIP = CRMMapper.Get().QueryForObject<int>("BlackIP.MyFind", counthtparm);
                if (countIP != 0)
                {
                    filterContext.Result = new RedirectResult("/Base/IPError.mvc");
                }
            }

            //用户ip使用次数校验
            int count = 0;
            int times = 30;
            Hashtable htparm = new Hashtable();
            if (userid != null)
                htparm["UserID"] = userid.Value;
            else
                htparm["UserID"] = -1;
            htparm["LoginIP"] = LoginIP;
            htparm["Now"] = DateTime.Now;
            htparm["Last"] = DateTime.Now.AddMinutes(-1);
            count = CRMMapper.Get().QueryForObject<Int32>("UserLogin.Total", htparm);
            if (count < times)
            {
                UserLogin userlogin = new UserLogin();
                if (userid != null)
                    userlogin.UserID = userid.Value;
                else
                    userlogin.UserID = -1;
                userlogin.LoginIP = LoginIP;
                userlogin.LoginTime = DateTime.Now;
                userlogin.FuntionCode = control.functionCode();
                userlogin.URL = HttpContext.Current.Request.Url.PathAndQuery;
                new UserLoginDao().Insert(userlogin);

            }
            else
            {
                BlackIP bIP = new BlackIP();
                bIP.LogIP = LoginIP;
                bIP.UserID = userid.Value;
                bIP.BlackTime = DateTime.Now;
                new BlackIPDao().Insert(bIP);
                filterContext.Result = new RedirectResult("/Base/IPError.mvc");
            }
            //检验是否是重复登录
            if (userid != null)
            {
                string url = HttpContext.Current.Request.Url.PathAndQuery;
                UserLoginGuidService ulgs = new UserLoginGuidService();
                UserLoginGuid ulg = ulgs.selectbyuserid(userid.Value);
                if (ulg != null)
                {
                    if (ulg.LoginGuid != cui.LoginGuid)
                    {
                        UserModel olduser = new MembershipUserService().GetUserName(Int32.Parse(cui.UserID));
                        DateTime oldtime = olduser.LastLoginDate;
                        string oldip = olduser.LastLoginIp;
                        if (oldtime.AddMinutes(30) < DateTime.Now || oldip == LoginIP)
                            filterContext.Result = new RedirectResult("/Base/MutiLogin.mvc?Url=" + url);
                        else
                        {
                            int t = 30 - (DateTime.Now - oldtime).Minutes;
                            filterContext.Result = new RedirectResult("/Base/LessTime.mvc?t=" + t);
                        }
                    }
                }
            }
            int helptopic = 0;
            EnumPrivilegeCheckResult checkresult = crm.UserPrivilegeCheck(control.ProductID, control.functionCode(), userid, out helptopic);

            //处理验证结果
            switch (checkresult)
            {
                case EnumPrivilegeCheckResult.未登陆失败:
                    filterContext.Result = new RedirectResult("/Base/NotLogin.mvc");
                    return;

                case EnumPrivilegeCheckResult.非会员失败:
                    filterContext.Result = new RedirectResult("/Base/NotMember.mvc/" + helptopic);
                    return;

                case EnumPrivilegeCheckResult.会员等级不足失败:
                    filterContext.Result = new RedirectResult("/Base/MemberLevelError.mvc/" + helptopic);
                    return;

                case EnumPrivilegeCheckResult.未购买产品失败:
                    filterContext.Result = new RedirectResult("/Base/NotBuyer.mvc/" + helptopic);
                    return;
                case EnumPrivilegeCheckResult.试用账号超过次数上限:
                    filterContext.Result = new RedirectResult("/Base/TryError.mvc");
                    return;

            }
            //如果是子账户,检查是否有相应权限
            if (userid != null && new MemberUserInfoDao().Find((int)userid) != null)
            {
                int uid = (int)userid;
                bool IsAdmin = new MemberUserInfoDao().IsAdmin(uid);
                if (!IsAdmin)//如果是子账户
                {
                    //找到子账户的functionlist
                    string functionlist = FindFunctionlist(uid, productid);
                    List<string> codelist = new List<string>();
                    if (functionlist != null)
                    {
                        string[] list = functionlist.Split(',');
                        //再找到相应的functioncode

                        foreach (string str in list)
                        {
                            if (str.Trim().ToLower() != "on")
                            {
                                codelist.Add(new ProductFunctionDao().Find(Int32.Parse(str)).FunctionCode);
                            }
                        }
                    }
                    codelist.Add("IndexPage");//首页都有
                    //如果当前code不在列表中则失败
                    if (!codelist.Contains(control.functionCode()))
                    {
                        filterContext.Result = new RedirectResult("/Base/NotAdmin.mvc");
                    }
                }
            }
            //通过检杳,允许访问
            base.OnActionExecuting(filterContext);
        }
        public ActionResult BasicInfo(FormCollection collection)
        {
            Dictionary<string, string> sitemaster = GetSiteMaster();
            ViewData["SiteMaster"] = sitemaster;
            int userid=Int32.Parse(CurrentUserInfo.UserID);
            //int companyID = new MemberUserInfoDao().GetMemberID(userid);
            string username=CurrentUserInfo.UserName;
            IDictionary dict = QueryBasicInfo(userid);
            if (dict != null)
            {
                string mail = MembershipService.GetUserMail(username);
                if (CurrentUserInfo != null)
                {
                    if (collection.Count == 0)
                    {
                        //ViewData["CompanyID"] = dict["MemberID"];
                        ViewData["Name"] = username;
                        dict["Email"] = mail;
                        ViewData["BasicInfo"] = dict;

                    }
                    else
                    {
                        //Dictionary<string, string> dict = new Dictionary<string, string>();
                        //dict["OldPassword"] = collection["OldPassword"];
                        //dict["NewPassword"] = collection["NewPassword"];
                        dict["ContractName"] = collection["ContractName"];
                        dict["Address"] = collection["Address"];
                        dict["Email"] = collection["Email"];
                        dict["ContractMobile"] = collection["ContractMobile"];
                        dict["Name"] = collection["Name"];
                        dict["Mobile"] = collection["Mobile"];
                        if (!MembershipService.CheckValidateCode(collection["ValidateCode"]))
                        {
                            //ViewData["CompanyID"] = companyID;
                            ViewData["Name"] = username;
                            ViewData["BasicInfo"] = dict;
                            ViewData["Validatecode"] = "False";
                            return View();
                        }
                        bool isSuccess = true;
                        EnterpriseMemberInfo upadtedEMI = new EnterpriseMemberInfo();
                        upadtedEMI = new EnterpriseMemberInfoDao().Find(Int32.Parse(dict["MemberID"].ToString()));
                        upadtedEMI.Address = collection["Address"];
                        upadtedEMI.ContractName = collection["ContractName"];
                        upadtedEMI.ContractMobile = collection["ContractMobile"];
                        MemberUserInfo mui = new MemberUserInfo();
                        Hashtable ht = new Hashtable();
                        ht["Mobile"] = collection["Mobile"];
                        ht["Name"] = collection["Name"];
                        ht["Userid"] = userid;
                        try
                        {
                            new EnterpriseMemberInfoDao().Update(upadtedEMI);
                            MembershipService.UpdateMail(userid, collection["Email"]);
                            CRMMapper.Get().Update("MemberUserInfo.myupdate", ht);
                        }
                        catch (Exception)
                        {
                            isSuccess = false;
                        }
                        //ViewData["CompanyID"] = companyID;
                        ViewData["Name"] = username;
                        ViewData["Basicinfo"] = dict;
                        ViewData["Success"] = isSuccess;
                    }
                }
            }
            else
            {
                UserModel um = new MembershipUserService().GetUserName(userid);
                IDictionary dictex = new Dictionary<string, string>();
                if (collection.Count == 0)
                {
                    dictex.Add("Address", um.Address);
                    dictex.Add("ContractMobile", um.Mobile);
                    dictex.Add("Mobile", um.Mobile);
                    dictex.Add("Email", um.Email);
                    ViewData["Name"] = username;
                    ViewData["BasicInfo"] = dictex;
                }
                else
                {
                    dictex.Add("Address", collection["Address"]);
                    dictex.Add("ContractMobile", collection["ContractMobile"]);
                    dictex.Add("Mobile", collection["Mobile"]);
                    dictex.Add("Email", collection["Email"]);
                    ViewData["Name"] = username;
                    ViewData["BasicInfo"] = dictex;
                    if (!MembershipService.CheckValidateCode(collection["ValidateCode"]))
                    {
                        //ViewData["CompanyID"] = companyID;
                        ViewData["Validatecode"] = "False";
                        return View();
                    }
                    bool isSuccess = true;
                    Hashtable ht = new Hashtable();
                    ht["Mobile"] = collection["Mobile"];
                    ht["Name"] = collection["Name"];
                    ht["Address"] = collection["Address"];
                    ht["Email"] = collection["Email"];
                    ht["Userid"] = userid;
                    try
                    {
                        MembershipService.UpdateBaseInfo(ht);
                    }
                    catch (Exception)
                    {
                        isSuccess = false;
                    }
                    //ViewData["CompanyID"] = companyID;
                    ViewData["Success"] = isSuccess;
                }
            }
            ViewData["titlename"] = "基本资料修改";
            return View();
        }