Пример #1
0
        /// <summary>
        /// 编辑权限时,获取指定角色的所有菜单权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task <WebResponseContent> GetUserTreePermission(int roleId)
        {
            WebResponseContent webResponse = new WebResponseContent();

            if (roleId != 1)
            {
                if (!(await GetAllChildren(UserContext.Current.RoleId)).Exists(x => x.Id == roleId))
                {
                    return(webResponse.Error("没有权限获取此角色的权限信息"));
                }
            }
            //获取用户权限
            List <Permissions> permissions = UserContext.Current.GetPermissions(roleId);
            //权限用户权限查询所有的菜单信息
            List <Sys_Menu> menus = await Task.Run(() => Sys_MenuService.Instance.GetUserMenuList(roleId));

            //获取当前用户权限如:(Add,Search)对应的显示文本信息如:Add:添加,Search:查询
            var data = menus.Select(x => new UserPermissions
            {
                Id      = x.Menu_Id,
                Pid     = x.ParentId,
                Text    = x.MenuName,
                Actions = GetActions(x.Menu_Id, x.Actions, permissions, roleId)
            });

            return(webResponse.OK(null, data));
        }
Пример #2
0
        /// <summary>
        /// 修改用户拦截过滤
        ///
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveModel)
        {
            WebResponseContent responseContent = new WebResponseContent();
            UserInfo           userInfo        = UserContext.Current.UserInfo;

            //禁止修改用户名
            base.UpdateOnExecute = (SaveModel saveInfo) =>
            {
                int    roleId   = saveModel.MainData["Role_Id"].GetInt();
                string roleName = GetChildrenName(roleId);
                if (UserContext.IsRoleIdSuperAdmin(userInfo.Role_Id))
                {
                    saveInfo.MainData.Add("RoleName", roleName);
                    return(responseContent.OK());
                }
                saveInfo.MainData.TryAdd("RoleName", roleName);

                if (string.IsNullOrEmpty(roleName))
                {
                    return(responseContent.Error("不能选择此角色"));
                }

                return(responseContent.OK());
            };
            base.UpdateOnExecuting = (Sys_User user, object obj1, object obj2, List <object> list) =>
            {
                if (user.User_Id == userInfo.User_Id && user.Role_Id != userInfo.Role_Id)
                {
                    return(responseContent.Error("不能修改自己的角色"));
                }

                var _user = repository.Find(x => x.User_Id == user.User_Id,
                                            s => new { s.UserName, s.UserPwd })
                            .FirstOrDefault();
                user.UserName = _user.UserName;
                //Sys_User实体的UserPwd用户密码字段的属性不是编辑,此处不会修改密码。但防止代码生成器将密码字段的修改成了可编辑造成密码被修改
                user.UserPwd = _user.UserPwd;
                return(responseContent.OK());
            };
            //用户信息被修改后,将用户的缓存信息清除
            base.UpdateOnExecuted = (Sys_User user, object obj1, object obj2, List <object> List) =>
            {
                base.CacheContext.Remove(user.User_Id.GetUserIdKey());
                return(new WebResponseContent(true));
            };
            return(base.Update(saveModel));
        }
Пример #3
0
        /// <summary>
        /// WebApi登陆
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public async Task <WebResponseContent> Login(LoginInfo loginInfo, bool verificationCode = true)
        {
            string             msg             = string.Empty;
            WebResponseContent responseContent = new WebResponseContent();

            try
            {
                responseContent = loginInfo.ValidationEntity(x => new { x.UserName, x.PassWord });
                if (!responseContent.Status)
                {
                    return(responseContent);
                }

                Sys_User user = await repository.FindAsIQueryable(x => x.UserName == loginInfo.UserName)
                                .FirstOrDefaultAsync();

                if (user == null || loginInfo.PassWord.Trim() != (user.UserPwd ?? "").DecryptDES(AppSetting.Secret.User))
                {
                    return(responseContent.Error(ResponseType.LoginError));
                }

                string token = JwtHelper.IssueJwt(new UserInfo()
                {
                    User_Id  = user.User_Id,
                    UserName = user.UserName,
                    Role_Id  = user.Role_Id
                });
                user.Token           = token;
                responseContent.Data = new { token, userName = user.UserTrueName, img = user.HeadImageUrl };
                repository.Update(user, x => x.Token, true);
                UserContext.Current.LogOut(user.User_Id);

                loginInfo.PassWord = string.Empty;

                return(responseContent.OK(ResponseType.LoginSuccess));
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                return(responseContent.Error(ResponseType.ServerError));
            }
            finally
            {
                Logger.Info(LoggerType.Login, loginInfo.Serialize(), responseContent.Message, msg);
            }
        }
Пример #4
0
        public async Task <WebResponseContent> RegisterUser(string openid, string nickName, string avatarUrl, int gender)
        {
            string             msg             = string.Empty;
            WebResponseContent responseContent = new WebResponseContent();

            try
            {
                var user = await repository.FindAsIQueryable(x => x.OpenId == openid)
                           .FirstOrDefaultAsync();

                if (user != null)
                {
                    return(responseContent.Error("用户名已经被注册"));
                }

                user = new Sys_User()
                {
                    OpenId       = openid,
                    UserName     = openid,
                    UserTrueName = nickName,
                    HeadImageUrl = avatarUrl,
                    Gender       = gender,
                    Role_Id      = 1001,
                    RoleName     = GetChildrenName(1001),
                    Enable       = 1
                };



                base.AddOnExecuted = (Sys_User sys_User, object list) =>
                {
                    return(responseContent.OK($"用户新建成功.帐号{user.UserName}"));
                };

                return(Add <Sys_User>(user));
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                return(responseContent.Error(ResponseType.ServerError));
            }
            finally
            {
                Logger.Info(LoggerType.ApiRegister, nickName, responseContent.Message, msg);
            }
        }
        public async Task <WebResponseContent> CreatePage(App_News news)
        {
            WebResponseContent webResponseContent = WebResponseContent.Instance;

            if (news == null)
            {
                return(webResponseContent.Error("未获取到数据"));
            }
            if (!await repository.ExistsAsync(x => x.Id == news.Id))
            {
                return(webResponseContent.Error("请求的数据已发生变化,请刷新页面重新提交"));
            }
            string template = FileHelper.ReadFile(@"Template\\AppHtml\\news.html");

            if (string.IsNullOrEmpty(template))
            {
                return(webResponseContent.Error("未获取到页面的模板,请确认模板是否存在"));
            }
            string filePath;
            string fileName;
            string urlPath;

            if (!string.IsNullOrEmpty(news.DetailUrl) && news.DetailUrl.IndexOf("/") != -1 && news.DetailUrl.Split(".").Length == 2)
            {
                var file = news.DetailUrl.Split("/");
                fileName = file[file.Length - 1];
                filePath = news.DetailUrl.Replace(fileName, "");
                urlPath  = filePath;
            }
            else
            {
                string day = DateTime.Now.ToString("yyyyMMdd");
                fileName = DateTime.Now.ToString("HHmmsss") + new Random().Next(1000, 9999) + ".html";
                urlPath  = $"static/news/{day}/";
                filePath = urlPath.MapPath(true);
            }
            string content = template.Replace("{title}", news.Title).Replace("{date}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{content}", news.Content);

            FileHelper.WriteFile((filePath.IndexOf("wwwroot") == -1 ? "wwwroot/" : "") + filePath, fileName, content);
            //更新数据库的url
            news.DetailUrl = $"{urlPath}{fileName}";
            repository.Update(news, x => new { news.DetailUrl, news.Content }, true);
            return(webResponseContent.OK("面发布成功,可预览看效果", new { url = news.DetailUrl }));
        }
Пример #6
0
        /// <summary>
        /// 新建用户,根据实际情况自行处理
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveModel)
        {
            WebResponseContent responseData = new WebResponseContent();

            base.AddOnExecute = (SaveModel userModel) =>
            {
                int roleId = userModel?.MainData?["Role_Id"].GetInt() ?? 0;
                if (roleId > 0)
                {
                    string roleName = GetChildrenName(roleId);
                    if (string.IsNullOrEmpty(roleName))
                    {
                        return(responseData.Error("不能选择此角色"));
                    }
                    //选择新建的角色ID,手动添加角色ID的名称
                    userModel.MainData["RoleName"] = roleName;
                }
                return(responseData.OK());
            };


            ///生成6位数随机密码
            string pwd = 6.GenerateRandomNumber();

            //在AddOnExecuting之前已经对提交的数据做过验证是否为空
            base.AddOnExecuting = (Sys_User user, object obj) =>
            {
                user.UserName = user.UserName.Trim();
                if (repository.Exists(x => x.UserName == user.UserName))
                {
                    return(responseData.Error("用户名已经被注册"));
                }
                user.UserPwd = pwd.EncryptDES(AppSetting.Secret.User);
                //设置默认头像
                user.HeadImageUrl = "https://imgs-1256993465.cos.ap-chengdu.myqcloud.com/h5pic/x1.jpg";
                return(responseData.OK());
            };

            base.AddOnExecuted = (Sys_User user, object list) =>
            {
                return(responseData.OK($"用户新建成功.帐号{user.UserName}密码{pwd}"));
            };
            return(base.Add(saveModel));;
        }
Пример #7
0
        /// <summary>
        /// 新建用户,根据实际情况自行处理
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveModel)
        {
            WebResponseContent responseData = new WebResponseContent();

            base.AddOnExecute = (SaveModel userModel) =>
            {
                int roleId = userModel?.MainData?["Role_Id"].GetInt() ?? 0;
                if (roleId > 0)
                {
                    string roleName = GetChildrenName(roleId);
                    if ((!UserContext.Current.IsSuperAdmin && roleId == 1) || string.IsNullOrEmpty(roleName))
                    {
                        return(responseData.Error("不能选择此角色"));
                    }
                    //选择新建的角色ID,手动添加角色ID的名称
                    userModel.MainData["RoleName"] = roleName;
                }
                return(responseData.OK());
            };


            ///生成6位数随机密码
            string pwd = 6.GenerateRandomNumber();

            //在AddOnExecuting之前已经对提交的数据做过验证是否为空
            base.AddOnExecuting = (Sys_User user, object obj) =>
            {
                user.UserName = user.UserName.Trim();
                if (repository.Exists(x => x.UserName == user.UserName))
                {
                    return(responseData.Error("用户名已经被注册"));
                }
                user.UserPwd = pwd.EncryptDES(AppSetting.Secret.User);
                //设置默认头像
                return(responseData.OK());
            };

            base.AddOnExecuted = (Sys_User user, object list) =>
            {
                return(responseData.OK($"用户新建成功.帐号{user.UserName}密码{pwd}"));
            };
            return(base.Add(saveModel));;
        }
Пример #8
0
        private WebResponseContent ValidateRoleName(Sys_Role role, Expression <Func <Sys_Role, bool> > predicate)
        {
            WebResponseContent responseContent = new WebResponseContent(true);

            if (repository.Exists(predicate))
            {
                return(responseContent.Error($"角色名【{role.RoleName}】已存在,请设置其他角色名"));
            }
            return(responseContent);
        }
Пример #9
0
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据,可对数据进修改过滤
            AddOnExecute = (SaveModel saveModel) =>
            {
                //如果返回false,后面代码不会再执行
                return(webResponse.OK());
            };
            // 在保存数据库前的操作,所有数据都验证通过了,这一步执行完就执行数据库保存
            AddOnExecuting = (SellOrder order, object list) =>
            {
                //如果设置code=-1会强制返回,不再继续后面的操作,2021.07.04更新LambdaExtensions文件后才可以使用此属性
                //webResponse.Code = "-1";
                // webResponse.Message = "测试强制返回";
                //return webResponse.OK();

                List <SellOrderList> orderLists = list as List <SellOrderList>;
                if (orderLists == null || orderLists.Count == 0)
                {//如果没有界面上没有填写明细,则中断执行
                    return(webResponse.Error("必须填写明细数据"));
                }
                if (orderLists.Exists(x => x.Qty <= 20))
                {
                    return(webResponse.Error("明细数量必须大于20"));
                }

                return(webResponse.OK());
            };

            //此方法中已开启了事务,如果在此方法中做其他数据库操作,请不要再开启事务
            // 在保存数据库后的操作,此时已进行数据提交,但未提交事务,如果返回false,则会回滚提交
            AddOnExecuted = (SellOrder order, object list) =>
            {
                if (order.Qty < 10)
                {  //如果输入的销售数量<10,会回滚数据库
                    return(webResponse.Error("销售数量必须大于1000"));
                }
                return(webResponse.OK("已新建成功,台AddOnExecuted方法返回的消息"));
            };

            return(base.Add(saveDataModel));
        }
Пример #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public WebResponseContent Login(string userName, string password)
        {
            WebResponseContent responseContent = new WebResponseContent();

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                return(responseContent.Error("登录错误"));
            }
            // var encryptPwd = AESEncrypt.Encrypt(password, AESEncrypt.pwdKey);

            var user = repository.Sys_User.Where(q => q.Enable == (byte)DataStatus.Enable)
                       .Where(q => q.UserName == userName && q.UserPwd == password).First();

            if (user == null)
            {
                return(responseContent.Error("账户或密码错误"));
            }
            var adminToken = new AdminUser
            {
                User_Id  = user.UID,
                Email    = user.Email,
                Role_Id  = user.Role_Id,
                UserName = user.UserName,
            };
            //获取token配置
            var tokenManagement = AutofacContainerModule.GetService <IOptions <TokenManagement> >().Value;

            var token = TokenHelper.CreateAdminToken(tokenManagement, adminToken);

            //HttpContext.Current.Response.Headers.Add("Authorization", new StringValues(token));

            return(responseContent.OK("登录成功", new M_AdminUserRP
            {
                id = user.UID,
                UserName = user.UserName,
                RoleId = user.Role_Id,
                HeadImageUrl = user.HeadImageUrl,
                Moblie = user.Mobile,
                Email = user.Email,
                Token = token,
            }));
        }
Пример #11
0
        /// <summary>
        /// 获取所有菜单
        /// </summary>
        /// <returns></returns>
        public async Task <WebResponseContent> Save(Sys_Menu menu)
        {
            WebResponseContent webResponse = new WebResponseContent();

            if (menu == null)
            {
                return(webResponse.Error("没有获取到提交的参数"));
            }
            if (menu.Menu_Id > 0 && menu.Menu_Id == menu.ParentId)
            {
                return(webResponse.Error("父级ID不能是当前菜单的ID"));
            }
            var isSave = false;

            if (menu.Menu_Id <= 0)
            {
                menu.CreateDate = DateTime.Now;
                menu.Creator    = UserContext.Current.UserName;
                isSave          = await repository.Sys_Menu.AddAsync(menu);
            }
            else
            {
                //2020.05.07新增禁止选择上级角色为自己
                if (menu.Menu_Id == menu.ParentId)
                {
                    return(WebResponseContent.Instance.Error($"父级id不能为自己"));
                }
                if (repository.Sys_Menu.IsExists(x => x.ParentId == menu.Menu_Id && menu.ParentId == x.Menu_Id))
                {
                    return(WebResponseContent.Instance.Error($"不能选择此父级id,选择的父级id与当前菜单形成依赖关系"));
                }
                menu.ModifyDate = DateTime.Now;
                menu.Modifier   = UserContext.Current.UserName;
                menu.Enable     = (byte)EnumDataStatus.Enable;
                isSave          = await repository.Sys_Menu.UpdateAsync(menu);
            }
            if (isSave)
            {
                webResponse.OK("保存成功", menu);
            }
            return(webResponse);
        }
Пример #12
0
        private WebResponseContent CheckKeyValue(List <Sys_DictionaryList> dictionaryLists)
        {
            WebResponseContent webResponse = new WebResponseContent();

            if (dictionaryLists == null || dictionaryLists.Count == 0)
            {
                return(webResponse.OK());
            }

            if (dictionaryLists.GroupBy(g => g.DicName).Any(x => x.Count() > 1))
            {
                return(webResponse.Error("【字典项名称】不能有重复的值"));
            }

            if (dictionaryLists.GroupBy(g => g.DicValue).Any(x => x.Count() > 1))
            {
                return(webResponse.Error("【字典项Key】不能有重复的值"));
            }

            return(webResponse.OK());
        }
Пример #13
0
 /// <summary>
 /// 验证提交的从表参数
 /// saveModel.Extra在App_ReportPrice.js中addBefore/updateBefore新建与编辑时提交到的后台
 /// </summary>
 /// <param name="saveModel"></param>
 /// <returns></returns>
 private WebResponseContent ValidateExtra(SaveModel saveModel)
 {
     if (saveModel == null || saveModel.Extra == null)
     {
         return(_webResponse.Error("请提交参数"));
     }
     try
     {
         TableExtra tableExtra = saveModel.Extra.ToString().DeserializeObject <TableExtra>();
         if (tableExtra == null ||
             tableExtra.Table1List == null ||
             tableExtra.Table1List.Count == 0 ||
             tableExtra.Table1List == null ||
             tableExtra.Table2List.Count == 0)
         {
             return(_webResponse.Error("请提交从表1与从表2的参数"));
         }
         //校验 从表1字段:Title,CreateDate必填
         _webResponse = tableExtra.Table1List.ValidationEntityList(x => new { x.Title, x.CreateDate });
         if (!_webResponse.Status)
         {
             _webResponse.Message = "从表1:" + _webResponse.Message;
             return(_webResponse);
         }
         //校验 从表2字段:Describe, Name,PhoneNo 必填
         _webResponse = tableExtra.Table2List.ValidationEntityList(x => new { x.Describe, x.Name, x.PhoneNo });
         if (!_webResponse.Status)
         {
             _webResponse.Message = "从表2:" + _webResponse.Message;
             return(_webResponse);
         }
         //校验成功返回
         return(_webResponse.OK(null, tableExtra));
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(_webResponse.Error("参数不正确"));
     }
 }
Пример #14
0
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            WebResponseContent responseContent = WebResponseContent.Instance;

            //此处saveModel是从前台提交的原生数据,可对数据进修改过滤
            AddOnExecute = (SaveModel saveModel) =>
            {
                //如果返回false,后面代码不会再执行
                return(responseContent.OK());
            };
            // 在保存数据库前的操作,所有数据都验证通过了,这一步执行完就执行数据库保存
            AddOnExecuting = (SellOrder order, object list) =>
            {
                List <SellOrderList> orderLists = list as List <SellOrderList>;
                if (orderLists == null || orderLists.Count == 0)
                {//如果没有界面上没有填写明细,则中断执行
                    return(responseContent.Error("必须填写明细数据"));
                }
                if (orderLists.Exists(x => x.Qty <= 20))
                {
                    return(responseContent.Error("明细数量必须大于20"));
                }

                return(responseContent.OK());
            };

            //此方法中已开启了事务,如果在此方法中做其他数据库操作,请不要再开启事务
            // 在保存数据库后的操作,此时已进行数据提交,但未提交事务,如果返回false,则会回滚提交
            AddOnExecuted = (SellOrder order, object list) =>
            {
                if (order.Qty < 10)
                {  //如果输入的销售数量<10,会回滚数据库
                    return(responseContent.Error("销售数量必须大于1000"));
                }
                return(responseContent.OK("已新建成功,台AddOnExecuted方法返回的消息"));
            };

            return(base.Add(saveDataModel));
        }
Пример #15
0
        public async Task <WebResponseContent> LoginOpenId(string openid)
        {
            string             msg             = string.Empty;
            WebResponseContent responseContent = new WebResponseContent();

            try
            {
                var user = await repository.FindAsIQueryable(x => x.OpenId == openid)
                           .FirstOrDefaultAsync();

                if (user == null)
                {
                    return(responseContent.Error(ResponseType.UserNotFound));
                }

                string token = JwtHelper.IssueJwt(new UserInfo()
                {
                    User_Id  = user.User_Id,
                    UserName = user.UserName
                });
                user.Token           = token;
                responseContent.Data = new { token, userName = user.UserTrueName, img = user.HeadImageUrl };
                repository.Update(user, x => x.Token, true);
                UserContext.Current.LogOut(user.User_Id);

                //loginInfo.PassWord = string.Empty;
                return(responseContent.OK(ResponseType.LoginSuccess));
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                return(responseContent.Error(ResponseType.ServerError));
            }
            finally
            {
                Logger.Info(LoggerType.Login, openid, responseContent.Message, msg);
            }
        }
Пример #16
0
        /// <summary>
        /// 添加资讯
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveModel)
        {
            WebResponseContent responseContent = WebResponseContent.Instance;

            AddOnExecuted = (News news, object list) =>
            {
                if (news.Tags.IsNullOrEmpty())
                {
                    return(responseContent.OK());
                }
                string[] tags = news.Tags?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (tags.Length > 5)
                {
                    return(responseContent.Error("标签不能超过5个"));
                }
                if (tags.Length > 0)
                {
                    for (int i = 0; i < tags.Length; i++)
                    {
                        var tagModel = repository.DbContext.Set <NewsTag>().Where(m => m.Tag == tags[i]).FirstOrDefault();
                        if (tagModel == null)
                        {
                            tagModel = new NewsTag()
                            {
                                Tag = tags[i], UseCount = 1
                            };
                            tagModel.SetCreateDefaultVal();
                            repository.DbContext.Set <NewsTag>().Add(tagModel);
                        }
                        else
                        {
                            tagModel.UseCount += 1;
                            repository.DbContext.Set <NewsTag>().Update(tagModel);
                        }
                    }
                    if (repository.DbContext.SaveChanges() > 0)
                    {
                        return(responseContent.OK("创建成功."));
                    }
                }
                news.SetModifyDefaultVal();
                return(responseContent.OK());
            };
            return(base.Add(saveModel).OK("已提交,正在审核中.."));
        }
Пример #17
0
        public override WebResponseContent Export(PageDataOptions pageData)
        {
            string             path        = null;
            string             fileName    = null;
            WebResponseContent webResponse = new WebResponseContent();

            ExportOnExecuting = (List <FormCollectionObject> list, List <string> columns) =>
            {
                var formId = list[0].FormId;
                var data   = _designOptionsRepository.FindAsIQueryable(x => x.FormId == formId)
                             .Select(s => new { s.Title, s.FormConfig }).FirstOrDefault();
                try
                {
                    List <FormOptions> formObj = data.FormConfig.DeserializeObject <List <FormOptions> >();
                    List <Dictionary <string, object> > listDic = new List <Dictionary <string, object> >();
                    foreach (var item in list)
                    {
                        Dictionary <string, object> dic = new Dictionary <string, object>();
                        var formData = item.FormData.DeserializeObject <Dictionary <string, string> >();
                        dic.Add("标题", data.Title);

                        dic.Add("提交人", item.Creator);
                        dic.Add("提交时间", item.CreateDate.ToString("yyyy-MM-dd HH:mm:sss"));
                        foreach (var obj in formObj)
                        {
                            dic.Add(obj.Title, formData.Where(x => x.Key == obj.Field).Select(s => s.Value).FirstOrDefault());
                        }
                        listDic.Add(dic);
                    }
                    fileName = data.Title + ".xlsx";
                    path     = EPPlusHelper.ExportGeneralExcel(listDic, fileName);
                }
                catch (Exception ex)
                {
                    Logger.Error($"解析表单出错:{data.Title},表单配置:{data.FormConfig},{ex.Message}");
                    return(webResponse.Error("获取表单出错"));
                }
                webResponse.Code = "-1";
                return(webResponse.OK(null, path.EncryptDES(AppSetting.Secret.ExportFile)));
            };
            return(base.Export(pageData));
        }
Пример #18
0
        public async Task <WebResponseContent> CardsGenerate(CardsSet cardsSet)
        {
            WebResponseContent responseContent = new WebResponseContent();
            var shop = ShopsRepository.Instance.FindFirst(x => x.User_Id == UserContext.Current.UserId);

            if (shop.IsNullOrEmpty())
            {
                return(responseContent.Error("商家信息未设定"));
            }
            var startnumber = (shop.Prefix.ToLong() * 10000 + shop.Middle.ToLong()) * 10000;

            var cardslist = new List <Cards>();

            for (int i = 0; i < cardsSet.Qty; i++)
            {
                var   cardno = startnumber + i;
                Cards card   = new Cards();
                card.Card_Name = cardsSet.Card_Name;
                card.Card_No   = cardno.ToString();
                Random ran = new Random();
                card.Card_Pwd         = ran.Next(100000, 999999).ToString();
                card.Card_Status      = 0;
                card.Card_Ship_Status = 0;
                card.CateGory_Id      = cardsSet.CateGory_Id;
                card.CreateDate       = DateTime.Now;
                card.Customer_Id      = cardsSet.Customer_Id;
                card.Expiry_Time      = cardsSet.Expiry_Time;
                card.Price            = cardsSet.Price;
                card.Strategy_Id      = cardsSet.Strategy_Id;
                card.Remark           = cardsSet.Remark;
                card.Sku_Id           = cardsSet.Sku_Id;
                card.CreateDate       = DateTime.Now;
                card.CreateID         = UserContext.Current.UserId;
                card.Creator          = UserContext.Current.UserName;
                cardslist.Add(card);
            }
            _repository.AddRange(cardslist, true);
            shop.Middle += 1;
            ShopsRepository.Instance.Update(shop);
            return(responseContent.OK("生成成功"));
        }
Пример #19
0
        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <param name="code">验证码</param>
        /// <param name="sessionKey">提交表单验证码</param>
        /// <param name="newPassWord">新密码</param>
        /// <param name="againPassWord">重复密码</param>
        /// <returns></returns>
        public WebResponseContent FindPassword(string phone, string code, string sessionKey, string newPassWord, string againPassWord)
        {
            WebResponseContent webResponseContent = new WebResponseContent();

            if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(code) || string.IsNullOrEmpty(newPassWord) || string.IsNullOrEmpty(againPassWord))
            {
                return(webResponseContent.Error("请输入完整信息"));
            }
            if (!phone.IsPhoneNo())
            {
                return(webResponseContent.Error("请输入正确的手机号码"));
            }
            if (string.IsNullOrEmpty(CacheContext.Get(sessionKey)))
            {
                return(webResponseContent.Error("请先获取验证码"));
            }
            if (CacheContext.Get(sessionKey) != code)
            {
                return(webResponseContent.Error("请输入正确的验证码"));
            }
            if (!newPassWord.Equals(againPassWord))
            {
                return(webResponseContent.Error("两次输入的密码不一致"));
            }
            var seller = DbContext.Set <Hiiops_Cart_SellerUser>().Where(x => x.Phone == phone).FirstOrDefault();

            if (seller == null)
            {
                return(webResponseContent.Error("手机号未注册"));
            }

            string token = JwtHelper.IssueJwt(seller.Id.ToString());

            seller.Token    = token;
            seller.Password = newPassWord.EncryptDES(AppSetting.Secret.User);
            DbContext.Update(seller);
            if (DbContext.SaveChanges() > 0)
            {
                return(webResponseContent.OK("密码修改成功", data: new { token = seller.Token }));
            }
            return(webResponseContent.Error("密码修改失败"));
        }
Пример #20
0
        public WebResponseContent MovieWebsiteTypePost(MovieWebsiteType type)
        {
            WebResponseContent Response = type.ValidationEntity();

            if (!Response.Status)
            {
                return(Response);
            }
            if (type.Id > 0)
            {
                repository.DbContext.Set <MovieWebsiteType>().Update(type);
            }
            else
            {
                repository.DbContext.Set <MovieWebsiteType>().Add(type);
            }
            if (repository.DbContext.SaveChanges() > 0)
            {
                return(Response.OK(ResponseType.SaveSuccess));
            }
            return(Response.Error("绑定失败."));
        }
Пример #21
0
        /// <summary>
        /// 获取短信验证码
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public WebResponseContent ValidateSMSCode(string sessionKey, string code, string phone)
        {
            WebResponseContent webResponseContent = new WebResponseContent();
            //取出短信配置参数
            string regionId, accessKeyId, secret;
            string signName, templateCode, templateParam;
            var    config    = DbContext.Set <Hiiops_Cart_System_Config>();
            var    _regionId = CacheContext.Get <string>(Constant.REGIONID);

            if (_regionId == null)
            {
                regionId = config.Where(x => x.KEYNAME == Constant.REGIONID).FirstOrDefault().VAL;
                if (regionId == null || regionId == "")
                {
                    return(webResponseContent.Error("阿里云短信节点配置有误"));
                }
                CacheContext.Add(Constant.REGIONID, regionId);
            }
            else
            {
                regionId = _regionId;
            }
            var _accessKeyId = CacheContext.Get <string>(Constant.ACCESSKEYID);

            if (_accessKeyId == null)
            {
                accessKeyId = config.Where(x => x.KEYNAME == Constant.ACCESSKEYID).FirstOrDefault().VAL;
                if (accessKeyId == null || accessKeyId == "")
                {
                    return(webResponseContent.Error("阿里云短信配置有误"));
                }
                CacheContext.Add(Constant.ACCESSKEYID, accessKeyId);
            }
            else
            {
                accessKeyId = _accessKeyId;
            }

            var _secret = CacheContext.Get <string>(Constant.SECRET);

            if (_secret == null)
            {
                secret = config.Where(x => x.KEYNAME == Constant.SECRET).FirstOrDefault().VAL;
                if (secret == null || secret == "")
                {
                    return(webResponseContent.Error("阿里云短信配置有误"));
                }
                CacheContext.Add(Constant.SECRET, secret);
            }
            else
            {
                secret = _secret;
            }
            var _signName = CacheContext.Get <string>(Constant.SIGNNAME);

            if (_signName == null)
            {
                signName = config.Where(x => x.KEYNAME == Constant.SIGNNAME).FirstOrDefault().VAL;
                if (signName == null || signName == "")
                {
                    return(webResponseContent.Error("阿里云短信配置有误"));
                }
                CacheContext.Add(Constant.SIGNNAME, signName);
            }
            else
            {
                signName = _signName;
            }

            templateCode = config.Where(x => x.KEYNAME == Constant.TEMPLATECODE && x.Remark.Contains("登录验证码")).FirstOrDefault().VAL;
            if (templateCode == null || templateCode == "")
            {
                return(webResponseContent.Error("阿里云短信配置有误"));
            }


            templateParam = config.Where(x => x.KEYNAME == Constant.TEMPLATEPARAM && x.Remark.Contains("登录验证码模板")).FirstOrDefault().VAL;
            if (templateParam == null || templateParam == "")
            {
                return(webResponseContent.Error("阿里云短信配置有误"));
            }

            string _code = CacheContext.Get <string>(sessionKey);

            if (_code == null)
            {
                return(webResponseContent.Error("请先获取验证码"));
            }
            if (_code != code)
            {
                return(webResponseContent.Error("输入的验证码有误!"));
            }

            //组装一下数据
            Random rnd  = new Random();
            int    rand = rnd.Next(1000, 9999);

            CacheContext.Add(phone + "ValidateSMSCode", rand + "", DateTime.Now.AddMinutes(10).GetTimeSpan());
            return(_smsservice.SendTemplateSms(regionId, accessKeyId, secret, phone, signName, templateCode, templateParam));

            //return new WebResponseContent().OK(message: "获取成功", data: new { img = $"data:image/jpeg;base64,{Convert.ToBase64String(data.ToArray())}", sessionKey = guid });
        }
Пример #22
0
        /// <summary>
        /// 小程序-通过OpenId快捷登录
        /// </summary>
        /// <param name="code">微信临时code</param>
        /// <returns></returns>
        public async Task <WebResponseContent> Login(string code)
        {
            WebResponseContent responseContent = new WebResponseContent();
            WxUtils            _wxUtils        = new WxUtils();
            //取出appid和secret
            var config = DbContext.Set <Hiiops_Cart_System_Config>().Where(x => x.KEYNAME == Constant.WECHATAPPID || x.KEYNAME == Constant.WECHATAPPSECRET).ToList();

            if (config.Count < 2)
            {
                return(responseContent.Error("请先配置小程序参数"));
            }

            var    appid         = CacheContext.Get <string>(Constant.WECHATAPPID);
            string applet_appid  = "";
            string applet_secret = "";

            if (appid == null)
            {
                applet_appid = config.Where(x => x.KEYNAME == Constant.WECHATAPPID).FirstOrDefault().VAL;
                CacheContext.Add(Constant.WECHATAPPID, applet_appid);
            }
            else
            {
                applet_appid = appid;
            }
            var secret = CacheContext.Get <string>(Constant.WECHATAPPSECRET);

            if (secret == null)
            {
                applet_secret = config.Where(x => x.KEYNAME == Constant.WECHATAPPSECRET).FirstOrDefault().VAL;
                CacheContext.Add(Constant.WECHATAPPSECRET, applet_secret);
            }
            else
            {
                applet_secret = secret;
            }

            //通过code取openid
            string  jsonStr = _wxUtils.GetXcxKey(code, applet_appid, applet_secret);
            JObject json    = JObject.Parse(jsonStr);
            string  openid  = json["openid"].ToString();

            if (string.IsNullOrWhiteSpace(openid))
            {
                return(responseContent.Error("服务繁忙,请重试!"));
            }
            //通过openid判断系统是否存在当前微信用户
            var user = await DbContext.Set <Hiiops_Cart_SellerUser>().Where(x => x.OpenId == openid).FirstOrDefaultAsync();

            if (user == null)
            {
                return(responseContent.Error("第一次使用请先注册!"));
            }
            string token = JwtHelper.IssueJwt(user.Id.ToString());

            user.Token           = token;
            responseContent.Data = new { token, user.NickName, user.Phone, user.Account, user.Country, user.HeadImgUrl, user.Id, user.Name, user.Privilege, user.Province, user.Remark, user.SearchKey, user.Sex, user.Status };
            DbContext.Update(user);
            SellerContent.Current.LogOut(user.Id);
            return(responseContent.OK(ResponseType.LoginSuccess));
        }
Пример #23
0
        /// <summary>
        /// 新建或编辑菜单
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        public async Task <WebResponseContent> Save(Sys_Menu menu)
        {
            WebResponseContent webResponse = new WebResponseContent();

            if (menu == null)
            {
                return(webResponse.Error("没有获取到提交的参数"));
            }
            if (menu.Menu_Id > 0 && menu.Menu_Id == menu.ParentId)
            {
                return(webResponse.Error("父级ID不能是当前菜单的ID"));
            }
            try
            {
                webResponse = menu.ValidationEntity(x => new { x.MenuName, x.TableName });
                if (!webResponse.Status)
                {
                    return(webResponse);
                }
                if (menu.TableName != "/" && menu.TableName != ".")
                {
                    Sys_Menu sysMenu = await repository.FindAsyncFirst(x => x.TableName == menu.TableName);

                    if (sysMenu != null)
                    {
                        if ((menu.Menu_Id > 0 && sysMenu.Menu_Id != menu.Menu_Id) ||
                            menu.Menu_Id <= 0)
                        {
                            return(webResponse.Error($"视图/表名【{menu.TableName}】已被其他菜单使用"));
                        }
                    }
                }

                if (menu.Menu_Id <= 0)
                {
                    repository.Add(menu.SetCreateDefaultVal());
                }
                else
                {
                    //2020.05.07新增禁止选择上级角色为自己
                    if (menu.Menu_Id == menu.ParentId)
                    {
                        return(WebResponseContent.Instance.Error($"父级id不能为自己"));
                    }
                    if (repository.Exists(x => x.ParentId == menu.Menu_Id && menu.ParentId == x.Menu_Id))
                    {
                        return(WebResponseContent.Instance.Error($"不能选择此父级id,选择的父级id与当前菜单形成依赖关系"));
                    }
                    repository.Update(menu.SetModifyDefaultVal(), p => new
                    {
                        p.ParentId,
                        p.MenuName,
                        p.Url,
                        p.Auth,
                        p.OrderNo,
                        p.Icon,
                        p.Enable,
                        p.TableName,
                        p.ModifyDate,
                        p.Modifier
                    });
                }
                await repository.SaveChangesAsync();

                _menuVersionn = DateTime.Now.ToString("yyyyMMddHHMMssfff");
                _menus        = null;
                webResponse.OK("保存成功", menu);
            }
            catch (Exception ex)
            {
                webResponse.Error(ex.Message);
            }
            finally
            {
                Logger.Info($"表:{menu.TableName},菜单:{menu.MenuName},权限{menu.Auth},{(webResponse.Status ? "成功" : "失败")}{webResponse.Message}");
            }
            return(webResponse);
        }
Пример #24
0
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="verificationCode">验证码</param>
        /// <param name="code">短信验证码</param>
        /// <param name="sessionKey">获取图片验证码的ID</param>
        /// <returns></returns>
        public async Task <WebResponseContent> ModifyPwd(string phone, string newPwd, string verificationCode, string code, string sessionKey)
        {
            newPwd = newPwd?.Trim();
            string             message     = "";
            WebResponseContent webResponse = new WebResponseContent();

            try
            {
                if (string.IsNullOrEmpty(phone))
                {
                    return(webResponse.Error("手机号不能为空"));
                }
                if (string.IsNullOrEmpty(newPwd))
                {
                    return(webResponse.Error("新密码不能为空"));
                }
                if (string.IsNullOrEmpty(verificationCode))
                {
                    return(webResponse.Error("验证码不能为空"));
                }
                if (string.IsNullOrEmpty(code))
                {
                    return(webResponse.Error("短信验证码有误"));
                }
                if (string.IsNullOrEmpty(sessionKey))
                {
                    return(webResponse.Error("参数有误"));
                }

                if (newPwd.Length < 6)
                {
                    return(webResponse.Error("密码不能少于6位"));
                }


                string imgCode = CacheContext.Get <string>(sessionKey);
                if (imgCode == null || imgCode != verificationCode)
                {
                    if (string.IsNullOrEmpty(verificationCode))
                    {
                        return(webResponse.Error("请输入正确验证码"));
                    }
                }


                string phoneCode = CacheContext.Get <string>(phone + "ValidateSMSCode");
                if (phoneCode == null || phoneCode != code)
                {
                    return(webResponse.Error("短信验证码有误"));
                }

                var a = await DbContext.Set <Hiiops_Cart_SellerUser>().Where(x => x.Phone == phone).FirstOrDefaultAsync();

                string userCurrentPwd = a.Password;


                string _newPwd = newPwd.EncryptDES(AppSetting.Secret.User);
                if (userCurrentPwd == _newPwd)
                {
                    return(webResponse.Error("新密码不能与旧密码相同"));
                }

                await Task.Run(() =>
                {
                    DbContext.Database.ExecuteSqlRaw($"UPDATA Hiiops_Cart_SellerUser SET Password = '******' , ModifyDate = '{DateTime.Now}'");
                });

                webResponse.OK("密码修改成功");
            }
            catch (Exception ex)
            {
                message = ex.Message;
                webResponse.Error("服务器了点问题,请稍后再试");
            }
            finally
            {
                if (message == "")
                {
                    Logger.OK(LoggerType.ApiModifyPwd, "密码修改成功");
                }
                else
                {
                    Logger.Error(LoggerType.ApiModifyPwd, message);
                }
            }
            return(webResponse);
        }
Пример #25
0
        /// <summary>
        /// 新建或编辑菜单
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        public async Task <WebResponseContent> Save(Sys_Menu menu)
        {
            bool result = true;;
            WebResponseContent webResponse = new WebResponseContent();

            if (menu == null)
            {
                return(webResponse.Error("没有获取到提交的参数"));
            }
            if (menu.Menu_Id > 0 && menu.Menu_Id == menu.ParentId)
            {
                return(webResponse.Error("父级ID不能是当前菜单的ID"));
            }
            try
            {
                webResponse = menu.ValidationEntity(x => new { x.MenuName, x.TableName });
                if (!webResponse.Status)
                {
                    return(webResponse);
                }

                if (menu.Menu_Id <= 0)
                {
                    menu.SetCreateDefaultVal();
                    repository.Add(menu);
                }
                else
                {
                    menu.SetModifyDefaultVal();
                    repository.Update(menu, p => new
                    {
                        p.ParentId,
                        p.MenuName,
                        p.Url,
                        p.Auth,
                        p.OrderNo,
                        p.Icon,
                        p.Enable,
                        p.TableName,
                        p.ModifyDate,
                        p.Modifier
                    });
                }
                await repository.SaverChangesAsync();

                if (result)
                {
                    _menuVersionn = DateTime.Now.ToString("yyyyMMddHHMMssfff");
                    _menus        = null;
                }
                webResponse.OK("保存成功", menu);
            }
            catch (Exception ex)
            {
                webResponse.Error(ex.Message);
            }
            finally
            {
                Logger.Info($"表:{menu.TableName},菜单:{menu.MenuName},权限{menu.Auth},{(webResponse.Status ? "成功" : "失败")}{webResponse.Message}");
            }
            return(webResponse);
        }
Пример #26
0
        public async Task <WebResponseContent> GetOrderList(bool hasRefund, int status)
        {
            string             msg             = string.Empty;
            WebResponseContent responseContent = new WebResponseContent();

            try
            {
                //var orderList = repository.FindAllIncluding(o => o.SellOrderItem).Where(o => o.CustomerId == UserContext.Current.UserId).ToList();

                //var ordersIncludeItems = await repository.FindAsync(o => o.CustomerId == UserContext.Current.UserId, o => new { Order = o, OrderItems = o.SellOrderItem });

                //var data = new
                //{
                //    OrderList = ordersIncludeItems.Select(o => o.Order),

                //};

                var orders = await repository.FindAsync(o => o.CustomerId == UserContext.Current.UserId);

                List <SellOrderItem> list = new List <SellOrderItem>();

                foreach (var item in orders)
                {
                    var items = await SellOrderItemRepository.Instance.FindAsync(orderItem => orderItem.SellOrderId == item.SellOrderId);

                    list.AddRange(items);
                }

                List <object> bla = new List <object>();
                foreach (var item in list)
                {
                    var productName = ProductRepository.Instance.Find(p => p.ProductId == item.ProductId, p => p.Name).FirstOrDefault();

                    var pictureList = new List <string>();
                    var pictureIds  = await Product_Picture_MappingRepository.Instance.FindAsync(mapping => mapping.ProductId == item.ProductId, mapping => mapping.PictureId);

                    foreach (var pictureId in pictureIds)
                    {
                        var pictureBit = PictureRepository.Instance.Find(p => p.Id == pictureId, p => p.PictureBinary);
                        pictureList.AddRange(pictureBit);
                    }
                    bla.Add(
                        new
                    {
                        OrderId     = item.SellOrderId,
                        ProductName = productName,
                        Pictures    = pictureList
                    });
                }

                responseContent.Data = new
                {
                    OrderList = orders,
                    Products  = bla
                };
                return(responseContent.OK(ResponseType.OperSuccess));// throw new System.NotImplementedException();
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                return(responseContent.Error(ResponseType.ServerError));
            }
            finally
            {
                Logger.Info(msg);
            }
        }
Пример #27
0
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public async Task <WebResponseContent> ModifyPwd(string oldPwd, string newPwd)
        {
            oldPwd = oldPwd?.Trim();
            newPwd = newPwd?.Trim();
            string             message     = "";
            WebResponseContent webResponse = new WebResponseContent();

            try
            {
                if (string.IsNullOrEmpty(oldPwd))
                {
                    return(webResponse.Error("旧密码不能为空"));
                }
                if (string.IsNullOrEmpty(newPwd))
                {
                    return(webResponse.Error("新密码不能为空"));
                }
                if (newPwd.Length < 6)
                {
                    return(webResponse.Error("密码不能少于6位"));
                }

                int    userId         = UserContext.Current.UserId;
                string userCurrentPwd = await base.repository.FindFirstAsync(x => x.User_Id == userId, s => s.UserPwd);

                string _oldPwd = oldPwd.EncryptDES(AppSetting.Secret.User);
                if (_oldPwd != userCurrentPwd)
                {
                    return(webResponse.Error("旧密码不正确"));
                }

                string _newPwd = newPwd.EncryptDES(AppSetting.Secret.User);
                if (userCurrentPwd == _newPwd)
                {
                    return(webResponse.Error("新密码不能与旧密码相同"));
                }


                repository.Update(new Sys_User
                {
                    User_Id           = userId,
                    UserPwd           = _newPwd,
                    LastModifyPwdDate = DateTime.Now
                }, x => new { x.UserPwd, x.LastModifyPwdDate }, true);

                webResponse.OK("密码修改成功");
            }
            catch (Exception ex)
            {
                message = ex.Message;
                webResponse.Error("服务器了点问题,请稍后再试");
            }
            finally
            {
                if (message == "")
                {
                    Logger.OK(LoggerType.ApiModifyPwd, "密码修改成功");
                }
                else
                {
                    Logger.Error(LoggerType.ApiModifyPwd, message);
                }
            }
            return(webResponse);
        }
Пример #28
0
        public IActionResult ReplaceToken()
        {
            WebResponseContent responseContent = new WebResponseContent();
            string             error           = "";
            string             key             = $"rp:Token:{UserContext.Current.UserId}";
            UserInfo           userInfo        = null;

            try
            {
                //如果5秒内替换过token,直接使用最新的token(防止一个页面多个并发请求同时替换token导致token错位)
                if (_cache.Exists(key))
                {
                    return(Json(responseContent.OK(null, _cache.Get(key))));
                }
                var _obj = _lockCurrent.GetOrAdd(UserContext.Current.UserId, new object()
                {
                });
                lock (_obj)
                {
                    if (_cache.Exists(key))
                    {
                        return(Json(responseContent.OK(null, _cache.Get(key))));
                    }
                    string requestToken = HttpContext.Request.Headers[AppSetting.TokenHeaderName];
                    requestToken = requestToken?.Replace("Bearer ", "");

                    if (JwtHelper.IsExp(requestToken))
                    {
                        return(Json(responseContent.Error("Token已过期!")));
                    }

                    int userId = UserContext.Current.UserId;

                    userInfo = _userRepository.FindAsIQueryable(x => x.User_Id == userId).Select(
                        s => new UserInfo()
                    {
                        User_Id      = userId,
                        UserName     = s.UserName,
                        UserTrueName = s.UserTrueName,
                        Role_Id      = s.Role_Id,
                        RoleName     = s.RoleName
                    }).FirstOrDefault();

                    if (userInfo == null)
                    {
                        return(Json(responseContent.Error("未查到用户信息!")));
                    }

                    string token = JwtHelper.IssueJwt(userInfo);
                    //移除当前缓存
                    _cache.Remove(userId.GetUserIdKey());
                    //只更新的token字段
                    _userRepository.Update(new Sys_User()
                    {
                        User_Id = userId, Token = token
                    }, x => x.Token, true);
                    //添加一个5秒缓存
                    _cache.Add(key, token, 5);
                    responseContent.OK(null, token);
                }
            }
            catch (Exception ex)
            {
                error = ex.Message + ex.StackTrace;
                responseContent.Error("token替换异常");
            }
            finally
            {
                _lockCurrent.TryRemove(UserContext.Current.UserId, out object val);
                string _message = $"用户{userInfo?.User_Id}_{userInfo?.UserTrueName},({(responseContent.Status ? "token替换成功": "token替换失败")})";
                Logger.Info(LoggerType.ReplaceToeken, _message, null, error);
            }
            return(Json(responseContent));
        }
Пример #29
0
        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <param name="userPermissions"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task <WebResponseContent> SavePermission(List <UserPermissions> userPermissions, int roleId)
        {
            WebResponseContent webResponse = new WebResponseContent();
            string             message     = "";

            try
            {
                UserInfo user = UserContext.Current.UserInfo;
                if (!(await GetAllChildren(user.Role_Id)).Exists(x => x.Id == roleId))
                {
                    return(webResponse.Error("没有权限修改此角色的权限信息"));
                }
                //当前用户的权限
                List <Permissions> permissions = UserContext.Current.Permissions;

                List <int> originalMeunIds = new List <int>();
                //被分配角色的权限
                List <Sys_RoleAuth> roleAuths = await repository.FindAsync <Sys_RoleAuth>(x => x.Role_Id == roleId);

                List <Sys_RoleAuth> updateAuths = new List <Sys_RoleAuth>();
                foreach (UserPermissions x in userPermissions)
                {
                    Permissions per = permissions.Where(p => p.Menu_Id == x.Id).FirstOrDefault();
                    //不能分配超过当前用户的权限
                    if (per == null)
                    {
                        continue;
                    }
                    //per.UserAuthArr.Contains(a.Value)校验权限范围
                    string[] arr = x.Actions == null || x.Actions.Count == 0
                      ? new string[0]
                      : x.Actions.Where(a => per.UserAuthArr.Contains(a.Value))
                                   .Select(s => s.Value).ToArray();

                    //如果当前权限没有分配过,设置Auth_Id默认为0,表示新增的权限
                    var    auth         = roleAuths.Where(r => r.Menu_Id == x.Id).Select(s => new { s.Auth_Id, s.AuthValue, s.Menu_Id }).FirstOrDefault();
                    string newAuthValue = string.Join(",", arr);
                    //权限没有发生变化则不处理
                    if (auth == null || auth.AuthValue != newAuthValue)
                    {
                        updateAuths.Add(new Sys_RoleAuth()
                        {
                            Role_Id    = roleId,
                            Menu_Id    = x.Id,
                            AuthValue  = string.Join(",", arr),
                            Auth_Id    = auth == null ? 0 : auth.Auth_Id,
                            ModifyDate = DateTime.Now,
                            Modifier   = user.UserTrueName,
                            CreateDate = DateTime.Now,
                            Creator    = user.UserTrueName
                        });
                    }
                    else
                    {
                        originalMeunIds.Add(auth.Menu_Id);
                    }
                }
                //更新权限
                repository.UpdateRange(updateAuths.Where(x => x.Auth_Id > 0), x => new
                {
                    x.Menu_Id,
                    x.AuthValue,
                    x.Modifier,
                    x.ModifyDate
                });
                //新增的权限
                repository.AddRange(updateAuths.Where(x => x.Auth_Id <= 0));

                //获取权限取消的权限
                int[] authIds = roleAuths.Where(x => userPermissions.Select(u => u.Id)
                                                .ToList().Contains(x.Menu_Id) || originalMeunIds.Contains(x.Menu_Id))
                                .Select(s => s.Auth_Id)
                                .ToArray();
                List <Sys_RoleAuth> delAuths = roleAuths.Where(x => x.AuthValue != "" && !authIds.Contains(x.Auth_Id)).ToList();
                delAuths.ForEach(x =>
                {
                    x.AuthValue = "";
                });
                //将取消的权限设置为""
                repository.UpdateRange(delAuths, x => new
                {
                    x.Menu_Id,
                    x.AuthValue,
                    x.Modifier,
                    x.ModifyDate
                });

                int addCount    = updateAuths.Where(x => x.Auth_Id <= 0).Count();
                int updateCount = updateAuths.Where(x => x.Auth_Id > 0).Count();
                await repository.SaveChangesAsync();

                string _version = DateTime.Now.ToString("yyyyMMddHHMMssfff");
                //标识缓存已更新
                base.CacheContext.Add(roleId.GetRoleIdKey(), _version);

                webResponse.OK($"保存成功:新增加配菜单权限{addCount}条,更新菜单{updateCount}条,删除权限{delAuths.Count()}条");
            }
            catch (Exception ex)
            {
                message = "异常信息:" + ex.Message + ex.StackTrace + ",";
            }
            finally
            {
                Logger.Info($"权限分配置:{message}{webResponse.Message}");
            }

            return(webResponse);
        }
Пример #30
0
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public async Task <WebResponseContent> ModifyPwd(string oldPwd, string newPwd, string verificationCode)
        {
            oldPwd = oldPwd?.Trim();
            newPwd = newPwd?.Trim();
            string             message     = "";
            WebResponseContent webResponse = new WebResponseContent();

            try
            {
                if (string.IsNullOrEmpty(oldPwd))
                {
                    return(webResponse.Error("旧密码不能为空"));
                }
                if (string.IsNullOrEmpty(newPwd))
                {
                    return(webResponse.Error("新密码不能为空"));
                }
                if (newPwd.Length < 6)
                {
                    return(webResponse.Error("密码不能少于6位"));
                }

                int userId = SellerContent.Current.Id;

                var a = await DbContext.Set <Hiiops_Cart_SellerUser>().Where(x => x.Id == userId).FirstOrDefaultAsync();

                string userCurrentPwd = a.Password;

                string _oldPwd = oldPwd.EncryptDES(AppSetting.Secret.User);
                if (_oldPwd != userCurrentPwd)
                {
                    return(webResponse.Error("旧密码不正确"));
                }

                string _newPwd = newPwd.EncryptDES(AppSetting.Secret.User);
                if (userCurrentPwd == _newPwd)
                {
                    return(webResponse.Error("新密码不能与旧密码相同"));
                }

                await Task.Run(() =>
                {
                    DbContext.Database.ExecuteSqlRaw($"UPDATA Hiiops_Cart_SellerUser SET Password = '******' , ModifyDate = '{DateTime.Now}'");
                });

                webResponse.OK("密码修改成功");
            }
            catch (Exception ex)
            {
                message = ex.Message;
                webResponse.Error("服务器了点问题,请稍后再试");
            }
            finally
            {
                if (message == "")
                {
                    Logger.OK(LoggerType.ApiModifyPwd, "密码修改成功");
                }
                else
                {
                    Logger.Error(LoggerType.ApiModifyPwd, message);
                }
            }
            return(webResponse);
        }