Exemplo n.º 1
0
        //[HttpGet]
        //public IActionResult GenKey()
        //{
        //    var str = CommonTools.CreateRandomStr(16);
        //    str = "97AVsyHmvBJFGMXj";
        //    var data = EncryptTools.AESEncrypt(str + "|" + DateTime.Now.ToString("yyyyMMddHHmmss"), str);
        //    var result = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
        //    return Json(new { key = str, token = result });
        //}
        //[HttpGet]
        //public IActionResult Test()
        //{
        //    var order = new InterfaceOrderModel();
        //    order.PSerialNumber = "XX45513245556";//必填
        //    order.ShopId = 1;//后续给出(必填)
        //    order.PayType = 120;//后续给出(必填)
        //    order.PayMentType = 0;//填0即可(B2B订单需要)
        //    order.PayDate = "20200918112455";//付款日期,传递过来格式"yyyyMMddHHmmss"
        //    order.PayPrice = 200;//已付款金额(必填)

        //    //order.IsNeedPaperBag = true;//是否需要纸袋
        //    order.DeliveryTypeId = 11;//后续给出(必填)

        //    order.UserName = "";//商城购买者账号,需要关联的时候填写
        //    order.CustomerName = "任盈盈";
        //    order.CustomerPhone = "18776159649";
        //    order.CustomerAddressDetail = "广东省 深圳市 南山区 金融科技大厦12楼";
        //    order.CustomerMark = "尽快发货";
        //    order.AdminMark = "客服备注";

        //    order.ZMCoupon = 0;
        //    order.ZMWineCoupon = 0;
        //    order.WineWorldCoupon = 0;
        //    order.ProductCoupon = "";
        //    order.ZMIntegralValuePrice = 0;


        //    //发票信息
        //    InvoiceInfo invInfo = new InvoiceInfo();
        //    invInfo.CustomerEmail = "*****@*****.**";//客户用于发票接收邮箱
        //    invInfo.Title = "发票抬头";
        //    //发票中包含的增票部分
        //    invInfo.TaxpayerID = "45234234";
        //    invInfo.RegisterAddress = "广东省 深圳市 南山区 金融科技大厦12楼";
        //    invInfo.RegisterTel = "8588885";
        //    invInfo.BankOfDeposit = "广发 桃园支行";
        //    invInfo.BankAccount = "88888888888888";


        //    //商品
        //    List<InterFaceOrderProduct> proList = new List<InterFaceOrderProduct>();
        //    InterFaceOrderProduct pro = new InterFaceOrderProduct();
        //    pro.ProductCode = "Ferrari911";
        //    pro.ProductCode = "Ferrari911";
        //    pro.Quantity = 5;
        //    pro.SumPrice = 200;
        //    pro.Price = 80;



        //    proList.Add(pro);
        //    order.Products = proList;
        //    order.InvoiceInfo = invInfo;
        //    var data = new List<InterfaceOrderModel>();
        //    data.Add(order);
        //    //order.InvoiceMode = item.InvoiceMode;//开票方式
        //    dynamic dd = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(GenKey()));

        //    using (var http = new HttpClient())
        //    {
        //        var data3 = new { orders = data, sign = dd, orderType = 1 };

        //        StringContent content = new StringContent(JsonConvert.SerializeObject(data3));
        //        var response = http.PostAsync("http://localhost:50444", content);


        //    }

        //    var cc = CreateOrderToOMS(data, (string)dd.Value["token"], 1);
        //    return Json(cc);
        //}
        #endregion


        #region 验证部分
        /// <summary>
        /// AES验证部分
        /// </summary>
        /// <param name="sign"></param>
        /// <param name="key"></param>
        bool VerifySignature(string sign, string key)
        {
            /* *****************************************************************
            *
            * sign字符串  Base64[AES(key|dateTime)]
            * dateTime  接口获取时间 误差3分钟  格式"yyyyMMddHHmmss"
            * key       双方约定密钥字符串    97AVsyHmvBJFGMXj
            *
            * *****************************************************************/
            try
            {
                //反base64
                var req = Convert.FromBase64String(sign);
                var str = Encoding.GetEncoding("utf-8").GetString(req);
                //解密
                var res = EncryptTools.AESDecrypt(str, key);
                //判断
                var result = res.Split("|");
                var time   = DateTime.ParseExact(result[1], "yyyyMMddHHmmss", null);
                if (result[0] == key && time.AddMinutes(3) >= DateTime.Now)
                {
                    return(true);
                }
                return(false);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Exemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string mobile = "13761138329";
            string s1     = EncryptTools.AESEncrypt(mobile);

            Response.Write("加密结果:" + s1);
            Response.Write("<br/>解密结果:");
            Response.Write(EncryptTools.AESDecrypt(s1));
        }
Exemplo n.º 3
0
        public IActionResult Login(string username, string password, string verify, string returnUrl)
        {
            if (string.IsNullOrEmpty(username))
            {
                return(Error("用户名为空"));
            }
            if (string.IsNullOrEmpty(password))
            {
                return(Error("密码为空"));
            }
            if (string.IsNullOrEmpty(verify))
            {
                return(Error("验证码为空"));
            }
            var code = HttpContext.Session.GetString("VerifyCode");

            if (code == null)
            {
                return(Error());
            }
            if (verify.ToLower() != code.ToLower())
            {
                return(Error("验证码错误"));
            }
            var account = _userService.GetByUserName(username);

            if (account == null)
            {
                return(Error("账号或密码错误"));
            }
            if (!account.Isvalid)
            {
                return(Error("账号已被删除"));
            }
            if (account.State == UserState.Disabled)
            {
                return(Error("账号已被禁用"));
            }
            if (EncryptTools.AESEncrypt(password, account.Salt) == account.UserPwd)
            {
                account.LastLoginTime = DateTime.Now;
                account.LastLoginIp   = HttpContext.Connection.RemoteIpAddress.ToString();
                _userService.Update(account);

                _authenticationService.SignIn(username);

                return(Success(new { returnUrl = RedirectToLocal(returnUrl) }));
            }
            else
            {
                return(Error("账号或密码错误"));
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// 获取 RSA 加密之后的Key
 /// </summary>
 /// <returns></returns>
 private static string GetRSAPwdKey()
 {
     try
     {
         return(EncryptTools.RSADecryption(LoginPassWord));
     }
     catch (Exception ex)
     {
         //ServerLogger.Error(ex.Message);
     }
     return("");
 }
Exemplo n.º 5
0
 public static void SaveManagerCookie(Manager manager, bool remember)
 {
     if (remember)
     {
         CookieManager.SetCookie(CookieConst.COOKIE_MANAMGER,
                                 EncryptTools.EncryptDES(manager.GetManagerCookieString(), EncryptKey), DateTime.Now.AddDays(14));
     }
     else
     {
         CookieManager.SetCookie(CookieConst.COOKIE_MANAMGER,
                                 EncryptTools.EncryptDES(manager.GetManagerCookieString(), EncryptKey));
     }
 }
Exemplo n.º 6
0
        public IActionResult RequestToken([FromBody] TokenRequest request)
        {
            if (request != null)
            {
                var account = _userService.GetByUserName(request.UserName);
                if (account == null)
                {
                    return(Ok(new TokenResult {
                        res_state = false
                    }));
                }

                if (EncryptTools.AESEncrypt(request.Password, account.Salt) == account.UserPwd)
                {
                    var claims = new[] {
                        //加入用户的名称
                        new Claim(ClaimTypes.Name, request.UserName)
                    };

                    var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var authTime  = DateTime.UtcNow;
                    var expiresAt = authTime.AddDays(1);

                    var token = new JwtSecurityToken(
                        issuer: "wine-world.com",
                        audience: "wine-world.com",
                        claims: claims,
                        expires: expiresAt, // 过期时间
                        signingCredentials: creds);

                    return(Ok(new TokenResult
                    {
                        res_state = true,
                        access_token = new JwtSecurityTokenHandler().WriteToken(token),
                        token_type = "Bearer",
                        profile = new Profile
                        {
                            name = request.UserName,
                            auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                            expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                        }
                    }));
                }
            }

            return(Ok(new TokenResult {
                res_state = false
            }));
        }
Exemplo n.º 7
0
        public IActionResult AddUser(Dictionary <int, UserViewModel> data)
        {
            var role = from s in (_roleService.GetRolesByUserId(_workContext.CurrentUser.Id).ToList()) select s.Name;

            if (role.Contains("超级管理员") || _permissionService.Authorize("AddUser"))
            {
                var ob         = "";
                var errStr     = "";
                var model      = data.Where(x => true).FirstOrDefault().Value;
                var isValidate = ValidateUser("create", data, out ob, out errStr);
                if (isValidate)
                {
                    try
                    {
                        var salt = CommonTools.CreateRandomStr(16);
                        var user = new User
                        {
                            Name        = model.Name,
                            Salt        = salt,
                            State       = (UserState)model.State,
                            Email       = model.Email,
                            Isvalid     = true,
                            UserPwd     = EncryptTools.AESEncrypt(model.UserPwd, salt),
                            UserName    = model.UserName,
                            PhoneNumber = model.PhoneNumber,
                            CreatedBy   = WorkContext.CurrentUser.Id,
                            CreatedTime = DateTime.Now
                        };
                        var resUser = _userService.CreateUser(user);
                        resUser.UserPwd = "";
                        var result = new List <UserViewModel> {
                            resUser.ToViewModel()
                        };
                        return(Success(result));
                    }
                    catch (Exception e)
                    {
                        return(ErrReturn("* 出现错误!"));
                    }
                }
                else
                {
                    return(ErrReturn(ob, errStr));
                }
            }
            else
            {
                return(Error("无操作权限!"));
            }
        }
Exemplo n.º 8
0
 public static Manager GetManagerFromCookie()
 {
     try
     {
         //加密串 进行一次DES 加密,RSA串作为密Key,保存到cookie\
         var encryptCookie = CookieManager.GetCookie(CookieConst.COOKIE_MANAMGER);
         var cookieString  = EncryptTools.DecryptDES(encryptCookie, EncryptKey);
         return(Manager.GetFromCookieString(cookieString));
     }
     catch
     {
         return(null);
     }
 }
Exemplo n.º 9
0
 public IActionResult UpdateCurrentUser(UserModel userModel)
 {
     try
     {
         var user = _userService.GetById(userModel.Id);
         var salt = CommonTools.CreateRandomStr(16);
         user.Salt    = salt;
         user.UserPwd = EncryptTools.AESEncrypt(userModel.UserPwd.ToString().Trim(), salt);
         _userService.UpdateUser(user);
         return(Success());
     }catch (Exception e)
     {
         return(Error("修改失败!"));
     }
 }
Exemplo n.º 10
0
        public IActionResult UpdateUser(Dictionary <int, UserViewModel> data)
        {
            var role = from s in (_roleService.GetRolesByUserId(_workContext.CurrentUser.Id).ToList()) select s.Name;

            if (role.Contains("超级管理员") || _permissionService.Authorize("UpdateUser"))
            {
                var ob         = "";
                var errStr     = "";
                var dic        = data.Where(x => true).FirstOrDefault();
                var model      = dic.Value;
                var isValidate = ValidateUser("update", data, out ob, out errStr);
                if (isValidate)
                {
                    try
                    {
                        var user = _userService.GetById(dic.Key);
                        user.Name         = model.Name;
                        user.UserName     = model.UserName;
                        user.Email        = model.Email;
                        user.PhoneNumber  = model.PhoneNumber;
                        user.ModifiedBy   = WorkContext.CurrentUser.Id;
                        user.ModifiedTime = DateTime.Now;
                        user.State        = (UserState)model.State;
                        if (model.UserPwd != null)
                        {
                            user.Salt    = CommonTools.CreateRandomStr(16);
                            user.UserPwd = EncryptTools.AESEncrypt(model.UserPwd, user.Salt);
                        }
                        var resUser = _userService.UpdateUser(user);
                        resUser.UserPwd = "";
                        var result = new List <UserViewModel> {
                            resUser.ToViewModel()
                        };
                        return(Success(result));
                    }
                    catch (Exception e)
                    {
                        return(ErrReturn("出现错误,更新失败!"));
                    }
                }

                return(ErrReturn(ob, errStr));
            }
            else
            {
                return(Error("无操作权限!"));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        public IActionResult ResetPassword(int userId)
        {
            var user = _userService.GetById(userId);

            if (user == null)
            {
                return(Error("数据错误,未找到该用户"));
            }
            var passWord = user.UserName.Trim() + "2020801";
            var salt     = CommonTools.CreateRandomStr(16);

            user.Salt         = salt;
            user.UserPwd      = EncryptTools.AESEncrypt(passWord, salt);
            user.ModifiedBy   = _workContext.CurrentUser.Id;
            user.ModifiedTime = DateTime.Now;
            _userService.UpdateUser(user);
            return(Success("重置密码成功,重置密码为" + passWord));
        }
Exemplo n.º 12
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="managerLogin"></param>
        /// <returns></returns>
        public dynamic GetManager(ManagerLogin managerLogin)
        {
            ManagerLogin login = new ManagerLogin
            {
                Account  = managerLogin.Account,
                Password = EncryptTools.EncryptToSHA256(managerLogin.Password)
            };
            var result = Context.ServiceContext.Current.ManagerService.GetManager(login);

            if (result != null)
            {
                return(new JsonResult(true, StatusCodeEnum.OK, StatusCodeEnum.OK.GetDescription(), result, null));
            }
            else
            {
                return(new JsonResult(true, StatusCodeEnum.BadRequest, ResponseDescriptionEnum.AccountOrPasswordError.GetDescription()));
            }
        }
Exemplo n.º 13
0
        public IActionResult UpdateUser(Dictionary <int, UserViewModel> data)
        {
            var ob         = "";
            var errStr     = "";
            var dic        = data.Where(x => true).FirstOrDefault();
            var model      = dic.Value;
            var isValidate = ValidateUser("update", data, out ob, out errStr);

            if (isValidate)
            {
                try
                {
                    var user = _userService.GetById(dic.Key);
                    user.Name         = model.Name;
                    user.UserName     = model.UserName;
                    user.Email        = model.Email;
                    user.PhoneNumber  = model.PhoneNumber;
                    user.ModifiedBy   = WorkContext.CurrentUser.Id;
                    user.ModifiedTime = DateTime.Now;
                    user.State        = (UserState)model.State;
                    if (model.UserPwd != null)
                    {
                        user.UserPwd = EncryptTools.AESEncrypt(model.UserPwd, CommonTools.CreateRandomStr(16));
                    }
                    var resUser = _userService.UpdateUser(user);
                    resUser.UserPwd = "";
                    var result = new List <UserViewModel> {
                        resUser.ToViewModel()
                    };
                    return(Success(result));
                }
                catch (Exception e)
                {
                    return(ErrReturn("出现错误,更新失败!"));
                }
            }

            return(ErrReturn(ob, errStr));
        }
Exemplo n.º 14
0
 /// <summary>
 /// 重置所有用户密码
 /// </summary>
 /// <returns></returns>
 public IActionResult ResetAllPassword()
 {
     try
     {
         var users = _userService.GetAllUserList().ToList();
         foreach (var user in users)
         {
             var passWord = user.UserName.Trim() + "2020801";
             var salt     = CommonTools.CreateRandomStr(16);
             user.Salt         = salt;
             user.UserPwd      = EncryptTools.AESEncrypt(passWord, salt);
             user.ModifiedBy   = _workContext.CurrentUser.Id;
             user.ModifiedTime = DateTime.Now;
             _omsAccessor.Update(user);
         }
         _omsAccessor.SaveChanges();
         return(Success("重置所有用户密码成功!"));
     }
     catch (Exception ex)
     {
         _logService.Error("重置所有用户密码错误:" + ex.Message);
         return(Error("重置所有用户密码失败!"));
     }
 }
Exemplo n.º 15
0
        public IActionResult UpdateUserPassword(string oldPassword, string newPassword, int id)
        {
            var user = _userService.GetById(id);

            if (user == null)
            {
                return(Error("数据错误,未找到该用户"));
            }

            var password = EncryptTools.AESDecrypt(user.UserPwd, user.Salt);

            if (oldPassword != password)
            {
                return(Error("旧密码输入错误"));
            }
            var salt = CommonTools.CreateRandomStr(16);

            user.Salt         = salt;
            user.UserPwd      = EncryptTools.AESEncrypt(newPassword, salt);
            user.ModifiedBy   = _workContext.CurrentUser.Id;
            user.ModifiedTime = DateTime.Now;
            _userService.UpdateUser(user);
            return(Success());
        }
Exemplo n.º 16
0
        /// <summary>
        /// 获取加密后的值
        /// </summary>
        /// <returns></returns>
        private string getAuthorization()
        {
            string authorizationStr = RequestHelper.UserName + RequestHelper.Password + DateTime.Now.ToString("yyyy-MM-dd");

            return(EncryptTools.EncryptMD5(authorizationStr));
        }
Exemplo n.º 17
0
        }                                            //绑定客户邮箱

        public virtual void  EncryptPassword()
        {
            Password = EncryptTools.GetMD5_32(Password);
        }
Exemplo n.º 18
0
 public virtual bool MatchPassword(string plainPassword)
 {
     return(this.Password == EncryptTools.GetMD5_32(plainPassword));
 }
Exemplo n.º 19
0
            public async Task <CommandActionResult> Handle(CreateCommercialUserCommand request, CancellationToken cancellationToken)
            {
                var Result = new CommandActionResult();


                string username = request.CellPhone;

                if (_context.Users.Any(x => x.Username == username))
                {
                    throw new CustomException("Username: \"" + username + "\" is already taken");
                }


                byte[] passwordHash, passwordSalt;
                EncryptTools.CreatePasswordHash(request.Password, out passwordHash, out passwordSalt);

                var user = new User()
                {
                    Username     = username,
                    PasswordHash = passwordHash,
                    PasswordSalt = passwordSalt,
                    DisplayName  = request.ContactName,
                    //Default User Active
                    IsActive = true
                };

                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        user.UserRoles.Add(new UserRole()
                        {
                            RoleId = 5
                        });

                        await _context.Users.AddAsync(user);

                        await _context.SaveChangesAsync(cancellationToken);

                        var customer = new Customer()
                        {
                            CustomerId        = request.CellPhone,
                            UserId            = user.Id
                            , CellPhone       = request.CellPhone
                            , ContactTitle    = request.ContactTitle
                            , ContactName     = request.ContactName
                            , Email           = request.Email
                            , Address         = request.Address
                            , AreaId          = request.AreaId
                            , ActivityFieldId = request.ActivityFieldId
                            , CreatedDate     = DateTime.Now
                        };

                        await _context.Customers.AddAsync(customer);

                        await _context.SaveChangesAsync(cancellationToken);

                        // List<CustomerTrashTypes> NewCustomerTrashTypes = new List<CustomerTrashTypes>();
                        //  var TrashTypesTobeUpdate = _context.CustomerTrashTypes.Include(p => p.CustomerId).Where(p => p.CustomerId == customer.CustomerId);

                        foreach (var item in request.TrashTypes)
                        {
                            _context.CustomerTrashTypes.Add(new CustomerTrashTypes()
                            {
                                CustomerId = customer.CustomerId, TrashTypeId = item.TrashTypeId
                            });
                        }
                        await _context.SaveChangesAsync(cancellationToken);

                        transaction.Commit();

                        Result.IsSuccess = true;
                    }
                    catch (Exception ex)
                    {
                        Result.IsSuccess = false;
                        Result.Message   = ex.Message;
                    }
                }

                Result.Unit = Unit.Value;
                return(Result);
            }