示例#1
0
        public string NowTaskList()
        {
            ManageUserModel uM   = (ManageUserModel)Session["logUser"];
            var             list = DailyCheck.GetNowTaskList(uM.UserID);

            return(CommonLib.Helper.JsonSerializeObject(list, "yyyy-MM-dd HH:mm:ss"));
        }
        public string AddAgent(string agentId, string agentPwd, string agentPhone, string agentName, string agentAddress, int agentGrade, string agentIdCard,
                               string agentNumber, string agentEmail, string agentQq, string remark, int serviceType)
        {
            AgentModel model = new AgentModel();

            model.AgentId       = agentId;
            model.AgentPassword = CommonLib.Helper.Md5Hash(agentPwd);
            model.AgentPhone    = agentPhone;
            model.AgentName     = agentName;
            model.AgentAddress  = agentAddress;
            model.AgentGrade    = agentGrade;
            model.AgentIdCard   = agentIdCard;
            model.AgentNumber   = agentNumber;
            model.AgentEmail    = agentEmail;
            model.AgentQQ       = agentQq;
            model.Remark        = remark;
            model.ServiceType   = serviceType;

            ManageUserModel uM = (ManageUserModel)Session["logUser"];

            if (uM != null)
            {
                model.Creater = uM.Name;
            }

            model.AgentLink = "http://app.i200.cn/LoginReg/Registration.aspx?ag=";
            //舍弃加密方式的代理商编码
            //model.AgentLink += (new Class_Password()).EnCode(agentId);
            model.AgentLink += agentId;

            return(AgentCtrl.AddAgent(model));
        }
        /// <summary>
        /// 优化规则的筛选器方法
        /// </summary>
        /// <param name="postJson"></param>
        /// <returns></returns>
        public string GetFilterDataSet(string postJson)
        {
            ManageUserModel uM   = (ManageUserModel)Session["logUser"];
            var             list = Controls.Filtrate.Filtrate.GetFilterData(postJson, uM.UserID, uM.Name);

            return(CommonLib.Helper.JsonSerializeObject(list, "yyyy-MM-dd HH:mm:ss"));
        }
示例#4
0
        public ActionResult Users(int?page, int?sortColumnIndex, int?sortDirection, string searchText)
        {
            ManageUserModel  model       = new ManageUserModel();
            SearchAttributes searchParam = new SearchAttributes();

            searchParam.CurrentPageNumber = (page.HasValue && page.Value > 0) ? page.Value : 1;
            searchParam.RecordsPerPage    = AppSettingsUtility.GetInt(AppSettingsKeys.RecordsPerPage);
            searchParam.SortColumnIndex   = (sortColumnIndex.HasValue && sortColumnIndex.Value > 0) ? sortColumnIndex.Value : 1;
            searchParam.SortDirection     = (sortDirection.HasValue && sortDirection.Value == 1) ? Entity.SortDirection.Descending : Entity.SortDirection.Ascending;

            if (!string.IsNullOrEmpty(searchText))
            {
                searchParam.SearchText = searchText;
            }

            model.Populate(searchParam);

            //for Ajax Specific Request


            if (Request.IsAjaxRequest())
            {
                return(View("~/Views/Shared/PartialViews/Admin/User/_UserList.cshtml", model));
            }
            else
            {
                return(View("~/Views/Admin/User/UserList.cshtml", model));
            }
        }
        public IEnumerable <ManageUserModel> GetAllUsers()
        {
            List <ManageUserModel>        userDetails = new List <ManageUserModel>();
            IEnumerable <ApplicationUser> users       = UserManager.Users.ToList();

            foreach (var user in users)
            {
                if (!User.Identity.GetUserId().Equals(user.Id))
                {
                    ManageUserModel model = new ManageUserModel
                    {
                        Id          = user.Id,
                        FirstName   = user.UserInfo.FirstName,
                        LastName    = user.UserInfo.LastName,
                        Email       = user.Email,
                        PhoneNumber = user.PhoneNumber,
                        DateOfBirth = user.UserInfo.DateOfBirth,
                        Street      = user.UserInfo.Street,
                        Suburb      = user.UserInfo.Suburb,
                        State       = user.UserInfo.State,
                        PostCode    = user.UserInfo.PostCode,
                        FileName    = user.UserInfo.FileName,
                        UserRoles   = generateMyRolesArr(UserManager.GetRoles(user.Id))
                    };
                    userDetails.Add(model);
                }
            }
            return(userDetails);
        }
示例#6
0
        public ActionResult ManageUser(string id)
        {
            ManageUserModel UserModel = new ManageUserModel();
            Guid            guid;

            if (!string.IsNullOrEmpty(id))
            {
                guid = new Guid(id);

                UserModel.GetUser(guid);
            }


            if (TempData["savesuccess"] != null)
            {
                if (TempData["savesuccess"].ToString() == "savesuccess")
                {
                    ViewBag.success = "success";
                }
                else
                {
                    ViewBag.success = "unsuccess";
                }
            }

            return(View("~/Views/Admin/User/manage-user.cshtml", UserModel));
        }
        /// <summary>
        /// 退款操作
        /// </summary>
        /// <param name="oid"></param>
        /// <param name="accid"></param>
        /// <param name="dDesc"></param>
        /// <returns></returns>
        public string Drawback(int oid, int accid, string dDesc)
        {
            ManageUserModel uM  = (ManageUserModel)Session["logUser"];
            int             uid = uM.UserID;

            return(T_OrderInfoBLL.DrawbackProcess(accid, oid, uid, dDesc) ? "1" : "0");
        }
        /// <summary>
        /// 后台话费补充
        /// </summary>
        /// <param name="accid"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string RechargeMobile(int accid, int orderId)
        {
            ManageUserModel uM  = (ManageUserModel)Session["logUser"];
            int             uid = uM.UserID;

            return(OrderInfoList.RechargeProc(accid, orderId, uid));
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Handles GET requests for the User View </summary>
        /// <remarks>   Andre Beging, 29.04.2018. </remarks>
        /// <param name="id">   The identifier. </param>
        /// <param name="successMessages"></param>
        /// <returns>   An IActionResult. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public new IActionResult User(Guid id, List <string> successMessages = null)
        {
            if (id == Guid.Empty)
            {
                return(RedirectToAction("Users"));
            }

            var model = new ManageUserModel();

            using (var context = ContextHelper.OpenContext())
            {
                var contextUser = context.User
                                  .Include(e => e.DrinkEntries)
                                  .Include(e => e.UserEvents)
                                  .FirstOrDefault(e => e.UserId == id);

                if (contextUser == null)
                {
                    return(RedirectToAction("Users"));
                }

                model.UserId = contextUser.UserId;
                model.Mail   = contextUser.Mail;
                model.Type   = contextUser.Type;
                model.Name   = contextUser.Username;
                model.Origin = contextUser.Origin;
            }

            successMessages             = successMessages ?? new List <string>();
            ViewData["SuccessMessages"] = successMessages;

            return(View(model));
        }
        public string SaveMenu(int uid, string idList)
        {
            ManageUserModel muM = (ManageUserModel)Session["logUser"];
            UserMenu        um  = new UserMenu();

            if (muM.PowerSession == 0 && muM.MenuPermission.IndexOf("501") > -1)
            {
                if (uid < 1)
                {
                    return("uid");
                }
                if (idList.Length < 1)
                {
                    return("list");
                }
                if (Controls.SysAccount.Account.UpdateUserMenu(uid, idList))
                {
                    return("1");
                }
                else
                {
                    return("0");
                }
            }
            else
            {
                return("log");
            }
        }
        public async Task <Result <bool> > CreateUser([FromBody] ManageUserModel userModel)
        {
            if (!Validate(userModel))
            {
                return(false);
            }

            var appUser = new ApplicationUser()
            {
                FirstName           = userModel.FirstName,
                LastName            = userModel.LastName,
                Email               = userModel.Email,
                TokenExpirationDate = DateTime.Now.AddDays(appOptions.Value.ActivationTokenExpirationTermDays),
                IsConfirmed         = false,
                ConfirmationToken   = Guid.NewGuid(),
                Profile             = new AdminProfile()
                {
                    AgentId     = userModel.AgentId,
                    IdAdminTeam = userModel.IdAdminTeam
                },
                IdUserType = UserType.Admin,
                Status     = UserStatus.NotActive,
            };

            await userService.CreateAsync(appUser, userModel.RoleIds);

            return(true);
        }
        public string GetForumFeedBack(string url, string remark)
        {
            ManageUserModel uM    = (ManageUserModel)Session["logUser"];
            string          uName = uM.Name;

            return(VisitInfo.GetForumFeedBack(url, uName, remark));
        }
        /// <summary>
        /// 关闭回访
        /// </summary>
        /// <param name="visitId"></param>
        /// <returns></returns>
        public string CloseVisit(int visitId, string reason, int accid)
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];

            //return "0";
            return(Controls.PlatformVisit.VisitInfo.AddVisitInfo(accid, 1, 505, 553, 759, 5, reason, 1, uM.Name, "", "", visitId, 0).ToString());
        }
示例#14
0
        public ActionResult NewPwd()
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];

            ViewBag.UsrName = uM.UserName;
            return(View());
        }
        public string SetAlipay(int accId, string alipayAccount, string alipayPid, string alipayKey)
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];
            int             r  = ShopDetails.AddAccountAlipay(accId, alipayAccount, alipayPid, alipayKey);

            return(r.ToString());
        }
示例#16
0
        public string SendMessage(string batchId, int channelId)
        {
            ManageUserModel uM    = (ManageUserModel)Session["logUser"];
            int             uid   = uM.UserID;
            string          uName = uM.Name;

            MessageSysControl.UpdateOperator(uid, batchId, channelId);

            switch (channelId)
            {
            case 1:
                return(MessageSysControl.SendingSms(batchId));

            case 2:
                return(MessageSysControl.SendingWebNotify(batchId, uid, uName));

                break;

            case 3:
                return(MessageSysControl.SendingAppNotify(batchId, uid, uName));

                break;

            case 4:
                //Logger.Debug("发送");
                return(MessageSysControl.SendingEmail(batchId));

            default:
                return("1");
            }

            return("1");
        }
示例#17
0
        /// <summary>
        /// 导出发票信息
        /// </summary>
        /// <param name="stDate"></param>
        /// <param name="edDate"></param>
        /// <returns></returns>
        public ActionResult ExportOrder(DateTime stDate, DateTime edDate)
        {
            ManageUserModel uM  = (ManageUserModel)Session["logUser"];
            int             uid = uM.UserID;

            List <dynamic> ds = T_Order_InvoiceBLL.GetExportInvoice(stDate, edDate);

            Dictionary <string, string> colName = new Dictionary <string, string>();

            colName["ID"]              = "店铺ID";
            colName["CompanyName"]     = "店铺名称";
            colName["invoiceMoney"]    = "发票金额";
            colName["transactionDate"] = "订单日期";
            colName["invoiceName"]     = "发票抬头";
            colName["invoicePhone"]    = "手机号码";
            colName["invoiceAddress"]  = "发票地址";
            colName["UserRealName"]    = "收件人姓名";
            colName["invoice_zip"]     = "邮政编码";

            HelperEx.ExportExcel export = new HelperEx.ExportExcel("发票信息", "invoice", colName);
            string webPath     = System.Web.HttpContext.Current.Server.MapPath("/");
            string strFileName = export.ExportFile(uM.UserName, ds, webPath);

            ViewBag.NavigateUrl = strFileName;

            Response.Redirect(strFileName);
            return(View());
        }
        public string SetAppActive(int accid, int appkey)
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];
            int             r  = ShopDetails.AddAccountApp(accid, appkey, uM.UserID);

            return(r.ToString());
        }
        /// <summary>
        /// 用户登录判断
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userPwd">密码(MD5)</param>
        /// <param name="sIP">浏览器IP</param>
        /// <param name="sBrowser">浏览器类型</param>
        /// <returns></returns>
        public ManageUserModel Login(string userName, string userPwd, string sIP, string sBrowser)
        {
            Sys_Manage_User manageUser = new Sys_Manage_User();
            ManageUserModel AccModel   = new ManageUserModel();

            AccModel.LoginStatus = false;
            string sPassWord = "";

            StringBuilder strSql = new StringBuilder();

            strSql.Append("select top(1) Id,UserName,P_session,LoginCounter,phone,name,PassWord,MenuPermission from Sys_Manage_User where [state]=1 and UserName=@userName;");

            manageUser = DapperHelper.GetModel <Sys_Manage_User>(strSql.ToString(), new { userName = userName });

            if (manageUser != null)
            {
                AccModel.UserID         = manageUser.Id;
                AccModel.UserName       = manageUser.UserName;
                AccModel.PowerSession   = Convert.ToInt32(manageUser.P_session);
                AccModel.LoginCnt       = Convert.ToInt32(manageUser.LoginCounter);
                AccModel.Phone          = manageUser.phone;
                AccModel.Name           = manageUser.name;
                AccModel.MenuPermission = manageUser.MenuPermission;
                sPassWord = manageUser.PassWord;
                //判断是否一致
                if (sPassWord == userPwd)
                {
                    //登录成功
                    AccModel.LoginStatus = true;
                    Sys_ManageLogDAL logDal = new Sys_ManageLogDAL();
                    logDal.LoginLog(AccModel.UserID, sIP, sBrowser);
                }
            }
            return(AccModel);
        }
        public string AddCoupon(int couponType, int bindType, int bindValue, string bindName, int ruleType, int ruleValue, int couponValue, string couponDesc,
                                int maxLimitNum, DateTime endDate, string remark, string prefix)
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];

            T_Order_CouponInfo model = new T_Order_CouponInfo();

            model.couponType   = couponType;
            model.bindType     = bindType;
            model.bindValue    = bindValue;
            model.bindName     = bindName;
            model.ruleType     = ruleType;
            model.ruleValue    = ruleValue;
            model.couponValue  = couponValue;
            model.couponStatus = 0;
            model.couponDesc   = couponDesc;
            model.maxLimitNum  = maxLimitNum;
            model.createDate   = DateTime.Now;
            model.endDate      = endDate.AddHours(23).AddMinutes(59).AddSeconds(59);
            model.remark       = remark;
            model.operatorId   = uM.UserID;
            model.operarorIp   = Request.UserHostAddress;
            model.operatorTime = DateTime.Now;
            model.prefixAgent  = (prefix == null ? 0 : Convert.ToInt32(prefix));

            model.id = T_Order_CouponInfoBLL.Add(model);
            if (model.id > 0)
            {
                return("0");
            }
            else
            {
                return("-1");
            }
        }
示例#21
0
 public JsonResult GetUsersList(DataTablesParam param, string sortDir, string sortCol, int clientId = -1, int active = -1, string name = "")
 {
     try
     {
         ManageUserModel model  = new ManageUserModel();
         int             pageNo = 1;
         if (param.iDisplayStart >= param.iDisplayLength)
         {
             pageNo = (param.iDisplayStart / param.iDisplayLength) + 1;
         }
         model = _userService.GetUsers(clientId, active, name, param, pageNo, sortDir, sortCol);
         return(Json(new
         {
             aaData = model.users,
             param.sEcho,
             iTotalDisplayRecords = model.totalUsersCount,
             iTotalRecords = model.totalUsersCount,
             Success = true
         }, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         _errorLogService.Add(new ErrorLogModel()
         {
             Page = "UserController/GetUsersList", CreatedBy = Convert.ToInt32(Session["UserId"]), CreateDate = DateTime.Now, ErrorText = ex.ToMessageAndCompleteStacktrace()
         });
         return(Json(new { Message = "Sorry, An error occurred!", Success = false }));
     }
 }
示例#22
0
        public ActionResult NewPwd(NewPwdModels viewData)
        {
            ManageUserModel uM     = (ManageUserModel)Session["logUser"];
            string          id     = uM.UserID.ToString();
            string          newPwd = viewData.NewPwd;
            string          oldPwd = viewData.OldPwd;

            ViewBag.js = Account.ChangePwd(newPwd, oldPwd, id);
            return(View());
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="accid">店铺ID</param>
        /// <param name="recordType">记录类别</param>
        /// <param name="vmanner">回访方式</param>
        /// <param name="content">内容</param>
        /// <param name="stat">状态</param>
        /// <param name="insertName">回访人</param>
        /// <param name="tags">标签</param>
        /// <param name="contact">回访方式值</param>
        /// <param name="taskid">任务ID</param>
        /// <returns></returns>
        public string addVisit(int accid, int recordType, int vrOne, int vrTwo, int vrThree, int vmanner, string content, int stat, string tags = "", string contact = "", int taskid = 0, int feedBack = 0)
        {
            //登录人名

            ManageUserModel uM = (ManageUserModel)Session["logUser"];


            content = Server.UrlDecode(content);
            return(Controls.PlatformVisit.VisitInfo.AddVisitInfo(accid, recordType, vrOne, vrTwo, vrThree, vmanner, content, stat, uM.Name, tags, contact, taskid, feedBack).ToString());
        }
示例#24
0
        public string PostMessage(string accids, string title, string content, DateTime?timing = null)
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];

            content = Server.UrlDecode(content);

            int    operatorId   = uM.UserID;
            string operstorName = uM.UserName;

            return(MessageCenterControls.PostMessage(accids, title, content, operatorId, operstorName, timing));
        }
        public string AddVisitReply(int vi_id, int accid, string vr_Content, int vr_Stat)
        {
            vr_Content = Server.UrlDecode(vr_Content);

            ManageUserModel uM         = (ManageUserModel)Session["logUser"];
            string          insertName = uM.Name;

            int l = Controls.PlatformVisit.VisitInfo.AddVisitReply(vi_id, accid, vr_Content, vr_Stat, insertName);

            return(l.ToString());
        }
示例#26
0
        public string MobileGlobal(string title, string content, DateTime?expire, DateTime?timing = null)
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];

            content = Server.UrlDecode(content);

            int    operatorId   = uM.UserID;
            string operstorName = uM.UserName;

            return(MessageCenterControls.PostMobileGlobal(uM.PowerSession, title, content, operatorId, operstorName, timing));
        }
        public new IActionResult User(ManageUserModel model)
        {
            var successMessages = new List <string>();

            var changePassword = ModelState.GetValidationState("Password") == ModelValidationState.Valid &&
                                 ModelState.GetValidationState("PasswordConfirmation") == ModelValidationState.Valid;

            ModelState.Remove("Password");
            ModelState.Remove("PasswordConfirmation");

            if (ModelState.IsValid || changePassword)
            {
                using (var context = ContextHelper.OpenContext())
                {
                    var contextUser = context.User.FirstOrDefault(u => u.UserId == model.UserId);
                    if (contextUser == null)
                    {
                        return(RedirectToAction("Users"));
                    }

                    if (ModelState.IsValid)
                    {
                        contextUser.Username = model.Name;
                        contextUser.Origin   = model.Origin;
                        contextUser.Type     = model.Type;

                        successMessages.Add("Der User wurde gespeichert.");
                    }

                    if (changePassword)
                    {
                        var salt = AuthenticationHelper.GenerateSalt();
                        var hash = AuthenticationHelper.CalculatePasswordHash(salt, model.Password);

                        contextUser.Salt = salt;
                        contextUser.Hash = hash;

                        successMessages.Add("Das Passwort wurde geändert.");
                    }

                    contextUser.Modified = DateTime.Now;
                    context.SaveChanges();
                }

                SharedProperties.OutdatedObjects.Add(model.UserId);
            }
            else
            {
                return(View(model));
            }


            return(RedirectToAction("User", new { id = model.UserId, successMessages }));
        }
        public string GetFunnelDataEx(string verif)
        {
            string          verification = verif;
            ManageUserModel uM           = (ManageUserModel)Session["logUser"];
            int             uid          = uM.UserID;
            string          UidList      = Controls.Filtrate.Filtrate.GetAccountList(uid, verification);

            string activeList = UidList.Substring(UidList.IndexOf(',') + 1);//去除首个0

            return(PanelShow.GetFunnelDataEx(activeList));
        }
示例#29
0
        public string updateAlphaApplyRecord(int id, int status)
        {
            string ip   = HttpContext.Request.UserHostAddress;
            int    opid = 0;

            if (Session["logUser"] != null)
            {
                ManageUserModel uM = (ManageUserModel)Session["logUser"];
                opid = uM.UserID;
            }
            return(AlphaApply.UpdateWithdrawalStatus(id, status, ip, opid));
        }
        public ActionResult SetPermission(int id)
        {
            ManageUserModel muM = (ManageUserModel)Session["logUser"];
            UserMenu        um  = new UserMenu();

            if (muM.PowerSession == 0 && muM.MenuPermission.IndexOf("501") > -1)
            {
                um = Controls.SysAccount.Account.GetAllMenu();
            }
            ViewBag.AccId = id;
            return(View(um));
        }
        public async Task<ActionResult> Manage(ManageUserModel model)
        {
            bool hasPassword = await this.HasPassword();
            ViewBag.HasLocalPassword = hasPassword;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasPassword)
            {
                if (ModelState.IsValid)
                {
                    var result = await this.userService.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        this.AddErrors(result);
                    }
                }
            }
            else
            {
                // User does not have a password so remove any validation errors caused by a missing OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    var result = await this.userService.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    else
                    {
                        this.AddErrors(result);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
示例#32
0
        // ReSharper disable once InconsistentNaming
        public void Middleware_can_sucessfully_update_a_users_password_upon_request()
        {
            #region - Unsuccessful tests/code via Moq for UserManager. Defer ?
                //var userMgrMock = new Mock<UserManager<ApplicationUser>>(
                //                  new UserStore<ApplicationUser>(NHibernateConfiguration.CreateSessionFactory(ConnString).OpenSession()));
                //userMgrMock.Setup(x => x.ChangePasswordAsync(loggedInUser.Id, _login.Password, "pwrd0827b"))
                //                        .ReturnsAsync(new IdentityResult());

                //var userStoreMock = new Mock<UserStore<ApplicationUser>>(NHibernateConfiguration.CreateSessionFactory(ConnString).OpenSession());
                //var userMgr2Mock = new Mock<UserManager<ApplicationUser>>(userStoreMock.Object);
                //userMgr2Mock.Setup(x => x.ChangePasswordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
                //                        .ReturnsAsync(new IdentityResult()); 

                // returns: IdentityResult.Succeeded = false - 8/27/14; 8/28 - definitely a Moq setup issue!
                //userMgrMock.Setup(x => x.ChangePasswordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
                //                        .ReturnsAsync(new IdentityResult()); 
                //var acctCtrl = new AccountController(userMgrMock.Object); //no
                //var acctCtrl = new AccountController(userMgr2Mock.Object); 

                //var identity = new GenericIdentity(loggedInUser.UserName);
                //var claimsIdentity = new ClaimsIdentity();
                //identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", loggedInUser.Id));
                //identity.AddClaims(claimsCollection);
                //var principal = new GenericPrincipal(identity, new[] {"user"});
                //requestCtx.SetupGet(s => s.Principal).Returns(principal);
                //requestMsg.SetRequestContext(requestCtx.Object);
                //var descriptor = new HttpControllerDescriptor();
                //var controller = new Mock<IHttpController>();
                //acctCtrl.ControllerContext.RequestContext.Principal = principal;
                //acctCtrl.ControllerContext = new HttpControllerContext(requestCtx.Object, requestMsg, descriptor, controller.Object );    
                //var testCall = client.PostAsJsonAsync("http://localhost/Pims.Web.Api/api/Account/ManageAsync", editedPassword).Result;
                // Mimic user login.
                // Validate currently logged in User and their existence in ASP.NET Identity.
                //var loggedInUser2 = _userMgr.FindAsync(_login.UserName, _login.Password).Result;

                // mimic SignInAsync()
                //var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                //authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                //var claimsIdentity = await _userMgr.CreateIdentityAsync(loggedInUser, DefaultAuthenticationTypes.ApplicationCookie);
                //authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity);



                //// Identity created with added claim.
                //var identity = new GenericIdentity(loggedInUser.UserName);
                //identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", loggedUserId));

                //// Principal created with associated Identity.
                //var principal = new GenericPrincipal(identity, new[] {"user"});

                //var urlHelper = new Mock<UrlHelper>();
                //urlHelper.Setup(s => s.Link(It.IsAny<string>(), It.IsAny<object>()))
                //    .Returns("http://localhost/PIMS.Web.Api/api/Account");

                //// HttpRequestContext created
                //var requestCtx = new Mock<HttpRequestContext>();
                //requestCtx.Setup(s => s.Url).Returns(urlHelper.Object);
                //requestCtx.SetupGet(s => s.Principal).Returns(principal);

                //// Set HttpRequestMessage on HttpRequestContext via HttpConfiguration object.
                //var config = new HttpConfiguration();
                //config.Routes.MapHttpRoute(
                //                            name: "ManageRoute",
                //                            routeTemplate: "api/Account/ManageAsync" 
                //                           );

                //var requestMsg = TestHelpers.GetHttpRequestMessage(
                //                                HttpMethod.Post,
                //                                UrlBase + "/ManageAsync",
                //                                new AccountController(_userMgr),
                //                                "ManageRoute",
                //                                "api/Account/ManageAsync",
                //                                new { }
                //                                );

                //// Set required objects for HttpControllerContext.
                //requestMsg.SetRequestContext(requestCtx.Object);
                //var descriptor = new HttpControllerDescriptor();
                //var controller = new Mock<IHttpController>();
                //var accountCtrl = new AccountController(_userMgr)
                //           {
                //               ControllerContext = new HttpControllerContext
                //                                            (
                //                                               requestCtx.Object,
                //                                               requestMsg, 
                //                                               descriptor, 
                //                                               controller.Object
                //                                            )
                //           };

                //client.DefaultRequestHeaders.Add("UserId", loggedInUser.Id);
                //client.BaseAddress = new Uri(UrlBase);
                //client.DefaultRequestHeaders.Accept.Clear();
                //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //var settings = new JsonSerializerSettings();
                //var serializer = JsonSerializer.Create(settings);
                //var editedPassword = new ManageUserModel
                //                            {
                //                                OldPassword = _login.Password,
                //                                NewPassword = "******",
                //                                ConfirmPassword = "******"
                //                                //UserId = loggedUserId
                //                            };

                //var j = JObject.FromObject(editedData, serializer);
                //HttpContent content = new StringContent(j.ToString());
                //content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                //var contentData = content.ReadAsStringAsync();

                // Act
                //var claimsIdentityFactory = new PimsClaimsIdentityFactory();
                //var claimsIdentity = claimsIdentityFactory.CreateClaimsIdentity(_login);
                //IList<Claim> claimsCollection = new List<Claim>
                //                                {
                //                                    new Claim(ClaimTypes.Name, "Richard"),
                //                                    new Claim(ClaimTypes.PostalCode, "94065"),
                //                                    new Claim(ClaimTypes.MobilePhone, "650.465.3609"),
                //                                    new Claim(ClaimTypes.Locality, "Redwood Shores")
                //                                };
                //NHibernate.AspNet.Identity.IdentityUserClaim nhClaim = new IdentityUserClaim();

                //var claimsIdentity = new ClaimsIdentity(claimsCollection, "PIMS test authType");
                //claimsIdentity.AddClaims(claimsCollection);
                //var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            #endregion

            using (new HttpClient())
            {
                // Arrange 
                var loggedInUser = _userMgr.FindAsync(_login.UserName, _login.Password).Result;
                var acctCtrl = new AccountController(_userMgr);
                
                // Assumes valid loggedInUser.
                IList<Claim> claimsCollection = new List<Claim>
                                                {
                                                    new Claim(ClaimTypes.Name, loggedInUser.UserName),
                                                    new Claim(ClaimTypes.NameIdentifier, loggedInUser.Id),
                                                    new Claim(ClaimTypes.PostalCode, "94065"),
                                                    new Claim(ClaimTypes.StateOrProvince, "California")
                                                };

                // Associate claims with Identity 
                var claimsIdentity = new ClaimsIdentity(claimsCollection, "PIMS web site");

                // Associate Identity with Principal
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                Thread.CurrentPrincipal = claimsPrincipal;                             
     
                // Setup: RequestContext-RequestMessage-HttpConfiguration
                var requestCtx = new Mock<HttpRequestContext>();
                requestCtx.SetupGet(s => s.Principal).Returns(claimsPrincipal);
                var config = new HttpConfiguration();
                var route = config.Routes.MapHttpRoute(
                    name: "ManageRoute",
                    routeTemplate: "api/{controller}/ManageAsync",
                    defaults: new {}
                    );

                var routeData = new HttpRouteData(route, new HttpRouteValueDictionary {{"controller", "Account"}});
                var requestMsg = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Pims.Web.Api/api/Account/ManageAsync");
                requestMsg.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
                requestMsg.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute());
           
                acctCtrl.ControllerContext = new HttpControllerContext(config, routeData, requestMsg);
                acctCtrl.Request = requestMsg;
                acctCtrl.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
             
                acctCtrl.ControllerContext.RequestContext.Principal = claimsPrincipal;
              
               
                var userEdits = new ManageUserModel {
                                                        OldPassword = _login.Password,
                                                        NewPassword = "******",
                                                        ConfirmPassword = "******"
                                                    };

                
                // Act
                // Confirm userEdits & _login passwords are configured correctly.
                var actionResult = acctCtrl.ManageAsync(userEdits).Result;
                var loggedInUserModified = _userMgr.FindAsync(_login.UserName, userEdits.NewPassword).Result;
                // Create response message.
                var responseMsg = actionResult.ExecuteAsync(new CancellationToken(false));

                
                // Assert
                
                Assert.AreEqual(responseMsg.Result.StatusCode, HttpStatusCode.OK);
                Assert.IsNotNullOrEmpty(loggedInUserModified.UserName);

            }
        }
示例#33
0
        // ReSharper disable once InconsistentNaming
        public void Middleware_can_not_sucessfully_update_a_users_account_based_on_invalid_password_confirmations()
        {
            using (new HttpClient())
            {
                // Arrange 
                var loggedInUserValid = _userMgr.FindAsync(_login.UserName, _login.Password).Result;
                var acctCtrl = new AccountController(_userMgr);

                // Assumes valid loggedInUser.
                IList<Claim> claimsCollection = new List<Claim>
                                                {
                                                    new Claim(ClaimTypes.Name, loggedInUserValid.UserName),
                                                    new Claim(ClaimTypes.NameIdentifier, loggedInUserValid.Id),
                                                    new Claim(ClaimTypes.PostalCode, "94065"),
                                                    new Claim(ClaimTypes.StateOrProvince, "California")
                                                };

                // Associate claims with Identity 
                var claimsIdentity = new ClaimsIdentity(claimsCollection, "PIMS web site");

                // Associate Identity with Principal
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                Thread.CurrentPrincipal = claimsPrincipal;

                // Setup: RequestContext-RequestMessage-HttpConfiguration
                var requestCtx = new Mock<HttpRequestContext>();
                requestCtx.SetupGet(s => s.Principal).Returns(claimsPrincipal);
                var config = new HttpConfiguration();
                var route = config.Routes.MapHttpRoute(
                    name: "ManageRoute",
                    routeTemplate: "api/{controller}/ManageAsync",
                    defaults: new { }
                    );

                var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "Account" } });
                var requestMsg = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Pims.Web.Api/api/Account/ManageAsync");
                requestMsg.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
                requestMsg.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute());

                acctCtrl.ControllerContext = new HttpControllerContext(config, routeData, requestMsg);
                acctCtrl.Request = requestMsg;
                acctCtrl.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

                acctCtrl.ControllerContext.RequestContext.Principal = claimsPrincipal;

                // Change to invalid confirmation passwords.
                var userEdits = new ManageUserModel
                                {
                                    OldPassword = _login.Password,
                                    NewPassword = "******",
                                    ConfirmPassword = "******"
                                };


                // Act
                var actionResult = acctCtrl.ManageAsync(userEdits).Result;
                var loggedInUserUnModified = _userMgr.FindAsync(_login.UserName, userEdits.OldPassword).Result;
                // Create response message.
                var responseMsg = actionResult.ExecuteAsync(new CancellationToken(false));


                // Assert
                Assert.IsTrue(responseMsg.Result.StatusCode == HttpStatusCode.BadRequest);
                Assert.IsNotNullOrEmpty(loggedInUserUnModified.Id);

            }
        }