Exemplo n.º 1
0
        public ActionResultVM WriteDel(int id)
        {
            var vm = new ActionResultVM();

            int uid = new Application.UserAuthService(HttpContext).Get().UserId;

            using (var db = new Data.ContextBase())
            {
                var mo1 = db.UserWriting.Where(x => x.Uid == uid && x.UwId == id).FirstOrDefault();
                if (mo1.UwStatus == -1)
                {
                    vm.Set(ARTag.unauthorized);
                }
                else
                {
                    db.UserWriting.Remove(mo1);
                    var mo2 = db.UserWritingTags.Where(x => x.UwId == id).ToList();
                    db.UserWritingTags.RemoveRange(mo2);
                    var mo3 = db.UserReply.Where(x => x.UrTargetId == id.ToString()).ToList();
                    db.UserReply.RemoveRange(mo3);

                    vm.Set(db.SaveChanges() > 0);
                }
            }

            return(vm);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 公共注册
        /// </summary>
        /// <param name="mo">个人用户信息</param>
        /// <returns></returns>
        private ActionResultVM RegisterUser(Domain.UserInfo mo)
        {
            var vm = new ActionResultVM();

            using (var db = new Data.ContextBase())
            {
                var isok = true;

                //邮箱注册
                if (!string.IsNullOrWhiteSpace(mo.UserMail))
                {
                    isok = !db.UserInfo.Any(x => x.UserName == mo.UserName || x.UserMail == mo.UserMail);

                    vm.Set(ARTag.exist);
                    vm.Msg = "该邮箱已经注册";
                }
                else
                {
                    isok = !db.UserInfo.Any(x => x.UserName == mo.UserName);

                    vm.Set(ARTag.exist);
                    vm.Msg = "该账号已经注册";
                }

                if (isok)
                {
                    db.UserInfo.Add(mo);
                    int num = db.SaveChanges();
                    vm.Set(num > 0);
                }
            }

            return(vm);
        }
Exemplo n.º 3
0
        public ActionResultVM UpdatePassword(string oldpwd, string newpwd)
        {
            var vm = new ActionResultVM();

            int uid = new Application.UserAuthService(HttpContext).Get().UserId;

            using (var db = new Data.ContextBase())
            {
                var userinfo = db.UserInfo.Find(uid);
                if (userinfo.UserPwd == Core.CalcTo.MD5(oldpwd))
                {
                    userinfo.UserPwd = Core.CalcTo.MD5(newpwd);
                    db.UserInfo.Update(userinfo);
                    var num = db.SaveChanges();

                    vm.Set(num > 0);
                }
                else
                {
                    vm.Set(ARTag.unauthorized);
                }
            };

            return(vm);
        }
Exemplo n.º 4
0
        public ActionResultVM Delete(string id)
        {
            var vm = new ActionResultVM();

            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    vm.Set(ARTag.invalid);
                }
                else
                {
                    var uinfo = new Application.UserAuthService(HttpContext).Get();
                    if (uinfo.UserId != 0)
                    {
                        using var db = new Data.ContextBase();
                        var mo = db.GuffRecord.Find(id);

                        if (mo == null)
                        {
                            vm.Set(ARTag.invalid);
                        }
                        else
                        {
                            if (mo.Uid != uinfo.UserId)
                            {
                                vm.Set(ARTag.unauthorized);
                            }
                            else if (mo.GrStatus == -1)
                            {
                                vm.Set(ARTag.refuse);
                            }
                            else
                            {
                                db.Remove(mo);
                                int num = db.SaveChanges();

                                vm.Set(num > 0);
                            }
                        }
                    }
                    else
                    {
                        vm.Set(ARTag.unauthorized);
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                Filters.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemplo n.º 5
0
        public ActionResultVM WriteEditSave(Domain.UserWriting mo, int UwId, string TagIds)
        {
            var vm = new ActionResultVM();

            var lisTagId = new List <int>();

            TagIds.Split(',').ToList().ForEach(x => lisTagId.Add(Convert.ToInt32(x)));

            var lisTagName = Application.CommonService.TagsQuery().Where(x => lisTagId.Contains(x.TagId)).ToList();

            int uid = new Application.UserAuthService(HttpContext).Get().UserId;

            using (var db = new Data.ContextBase())
            {
                var oldmo = db.UserWriting.Where(x => x.Uid == uid && x.UwId == UwId).FirstOrDefault();

                if (oldmo.UwStatus == -1)
                {
                    vm.Set(ARTag.unauthorized);
                }
                else if (oldmo != null)
                {
                    oldmo.UwTitle      = mo.UwTitle;
                    oldmo.UwCategory   = mo.UwCategory;
                    oldmo.UwContentMd  = mo.UwContentMd;
                    oldmo.UwContent    = mo.UwContent;
                    oldmo.UwUpdateTime = DateTime.Now;

                    db.UserWriting.Update(oldmo);

                    var wt = db.UserWritingTags.Where(x => x.UwId == UwId).ToList();
                    db.UserWritingTags.RemoveRange(wt);

                    var listwt = new List <Domain.UserWritingTags>();
                    foreach (var tag in lisTagId)
                    {
                        var wtmo = new Domain.UserWritingTags
                        {
                            UwId    = mo.UwId,
                            TagId   = tag,
                            TagName = lisTagName.Where(x => x.TagId == tag).FirstOrDefault().TagName
                        };

                        listwt.Add(wtmo);
                    }
                    db.UserWritingTags.AddRange(listwt);

                    int num = db.SaveChanges();

                    vm.Set(num > 0);
                }
            }

            return(vm);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 处理用户消息回执
        /// </summary>
        /// <param name="cm">发送消息</param>
        /// <param name="hc">上下文</param>
        /// <param name="db">数据库</param>
        /// <returns></returns>
        public static ActionResultVM HandleUserMessageReceipt(ChatMessageVM cm, HttpContext hc, Data.ContextBase db)
        {
            var vm = new ActionResultVM();

            if (cm == null)
            {
                vm.Set(ARTag.lack);
                vm.Msg = "消息主体不能为空";
            }
            else if (string.IsNullOrWhiteSpace(cm.CmId))
            {
                vm.Set(ARTag.lack);
                vm.Msg = "消息ID不能为空";
            }
            else
            {
                vm.Set(ARTag.invalid);
                vm.Msg = "消息ID无效";

                //用户连接信息
                var cu = GetChatUserInfo(hc);

                //缓存消息
                if (UserMessage1.ContainsKey(cu.UserId))
                {
                    var mb = UserMessage1[cu.UserId].FirstOrDefault(x => x.CmuId == cm.CmId);
                    if (mb != null)
                    {
                        mb.CmuStatus = cm.CmStatus;

                        vm.Set(ARTag.success);
                    }
                }
                else
                {
                    var mb = db.NChatMessageToUser.Find(cm.CmId);
                    if (mb != null)
                    {
                        mb.CmuStatus = cm.CmStatus;
                        db.SaveChanges();

                        vm.Set(ARTag.success);
                    }
                }
            }

            return(vm);
        }
Exemplo n.º 7
0
            public override void OnResultExecuted(ResultExecutedContext context)
            {
                var hc = context.HttpContext;

                string controller = context.RouteData.Values["controller"].ToString().ToLower();
                string action     = context.RouteData.Values["action"].ToString().ToLower();
                string url        = hc.Request.Path.ToString() + hc.Request.QueryString.Value;

                try
                {
                    //客户端信息
                    var ct = new Core.ClientTo(hc);

                    //用户信息
                    var userinfo = Func.Common.GetLoginUserInfo(hc);

                    //日志保存
                    var mo = new Domain.SysLog()
                    {
                        LogId          = Guid.NewGuid().ToString(),
                        SuName         = userinfo.UserName,
                        SuNickname     = userinfo.Nickname,
                        LogAction      = controller + "/" + action,
                        LogUrl         = url,
                        LogIp          = ct.IPv4,
                        LogCreateTime  = DateTime.Now,
                        LogBrowserName = ct.BrowserName,
                        LogSystemName  = ct.SystemName,
                        LogGroup       = 1
                    };
                    mo.LogContent = DicDescription[mo.LogAction.ToLower()];

                    using (var db = new Data.ContextBase())
                    {
                        db.SysLog.Add(mo);
                        db.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    //throw new System.Exception("写入操作日志失败");
                }

                base.OnResultExecuted(context);
            }
Exemplo n.º 8
0
        /// <summary>
        /// 保存组消息
        /// </summary>
        /// <param name="db"></param>
        /// <param name="second">发送消息已超过分钟数,默认5分钟,0为全部写入</param>
        public static int SaveGroupMessage(Data.ContextBase db, int second = 5)
        {
            //待写入的消息
            var listMessage = new List <Domain.NChatMessageToGroup>();

            foreach (var key in GroupMessage1.Keys)
            {
                var msgs = GroupMessage1[key];

                //全部写入
                if (second <= 0)
                {
                    listMessage.AddRange(msgs);
                    GroupMessage1[key].Clear();
                }
                else
                {
                    //已超过分钟的消息
                    var mt = DateTime.Now.AddSeconds(second);

                    foreach (var m in msgs)
                    {
                        if (m.CmgCreateTime > mt)
                        {
                            listMessage.Add(m);
                            msgs.Remove(m);
                        }
                    }
                }
            }

            int batchRows = GlobalTo.GetValue <int>("NetnrChat:BatchSaveDataBase");
            int num       = 0;

            while (listMessage.Count > 0)
            {
                var listm = listMessage.Take(batchRows);
                db.NChatMessageToGroup.AddRange(listm);
                num += db.SaveChanges();
                listMessage.RemoveRange(0, batchRows);
            }

            return(num);
        }
Exemplo n.º 9
0
        public ActionResultVM UpdateUserSay(Domain.UserInfo mo)
        {
            var vm = new ActionResultVM();

            var uinfo = new Application.UserAuthService(HttpContext).Get();

            using (var db = new Data.ContextBase())
            {
                var currmo = db.UserInfo.Find(uinfo.UserId);
                currmo.UserSay = mo.UserSay;
                db.UserInfo.Update(currmo);

                int num = db.SaveChanges();

                vm.Set(num > 0);
            }

            return(vm);
        }
Exemplo n.º 10
0
        public IActionResult Del()
        {
            string code = RouteData.Values["id"]?.ToString();

            var uinfo = new Application.UserAuthService(HttpContext).Get();

            using (var db = new Data.ContextBase())
            {
                var mo = db.DocSet.Find(code);
                if (mo.Uid == uinfo.UserId)
                {
                    db.DocSet.Remove(mo);
                    var moDetail = db.DocSetDetail.Where(x => x.DsCode == code).ToList();
                    db.DocSetDetail.RemoveRange(moDetail);
                    db.SaveChanges();

                    return(Redirect("/doc/user/" + uinfo.UserId));
                }
            }
            return(Content("Bad"));
        }
Exemplo n.º 11
0
        public IActionResult RidOAuth()
        {
            if (Enum.TryParse(RouteData.Values["id"]?.ToString().ToLower(), out AccountController.ValidateloginType vtype))
            {
                int uid = new Application.UserAuthService(HttpContext).Get().UserId;
                using var db = new Data.ContextBase();
                var mo = db.UserInfo.Find(uid);

                switch (vtype)
                {
                case AccountController.ValidateloginType.qq:
                    mo.OpenId1 = "";
                    break;

                case AccountController.ValidateloginType.weibo:
                    mo.OpenId2 = "";
                    break;

                case AccountController.ValidateloginType.github:
                    mo.OpenId3 = "";
                    break;

                case AccountController.ValidateloginType.taobao:
                    mo.OpenId4 = "";
                    break;

                case AccountController.ValidateloginType.microsoft:
                    mo.OpenId5 = "";
                    break;

                case AccountController.ValidateloginType.dingtalk:
                    mo.OpenId6 = "";
                    break;
                }

                db.UserInfo.Update(mo);
                db.SaveChanges();
            }
            return(Redirect("/user/setting"));
        }
Exemplo n.º 12
0
        public ActionResultVM SaveDocSet(Domain.DocSet mo)
        {
            var vm = new ActionResultVM();

            var uinfo = new Application.UserAuthService(HttpContext).Get();

            using (var db = new Data.ContextBase())
            {
                if (string.IsNullOrWhiteSpace(mo.DsCode))
                {
                    mo.DsCode       = Core.UniqueTo.LongId().ToString();
                    mo.Uid          = uinfo.UserId;
                    mo.DsStatus     = 1;
                    mo.DsCreateTime = DateTime.Now;

                    db.DocSet.Add(mo);
                }
                else
                {
                    var currmo = db.DocSet.Find(mo.DsCode);
                    if (currmo.Uid != uinfo.UserId)
                    {
                        vm.Set(ARTag.unauthorized);
                    }

                    currmo.DsName   = mo.DsName;
                    currmo.DsRemark = mo.DsRemark;
                    currmo.DsOpen   = mo.DsOpen;
                    currmo.Spare1   = mo.Spare1;

                    db.DocSet.Update(currmo);
                }
                var num = db.SaveChanges();

                vm.Set(num > 0);
            }

            return(vm);
        }
Exemplo n.º 13
0
        public IActionResult Message(int page = 1)
        {
            int uid = new Application.UserAuthService(HttpContext).Get().UserId;

            var vm = Application.CommonService.MessageQuery(uid, Application.EnumService.MessageType.UserWriting, null, page);

            vm.Route = Request.Path;

            if (page == 1)
            {
                using var db = new Data.ContextBase();
                var listum = db.UserMessage.Where(x => x.UmType == Application.EnumService.MessageType.UserWriting.ToString() && x.UmAction == 2 && x.UmStatus == 1).ToList();
                if (listum.Count > 0)
                {
                    listum.ForEach(x => x.UmStatus = 2);
                    db.UserMessage.UpdateRange(listum);
                    db.SaveChanges();
                }
            }

            return(View(vm));
        }
Exemplo n.º 14
0
        public IActionResult DelMessage()
        {
            var vm = new ActionResultVM();

            var id = RouteData.Values["id"]?.ToString();

            if (!string.IsNullOrWhiteSpace(id))
            {
                var uinfo = new Application.UserAuthService(HttpContext).Get();

                using var db = new Data.ContextBase();
                var um = db.UserMessage.Find(id);
                if (um == null)
                {
                    vm.Set(ARTag.lack);
                }
                else if (um?.Uid != uinfo.UserId)
                {
                    vm.Set(ARTag.unauthorized);
                }
                else
                {
                    db.UserMessage.Remove(um);
                    int num = db.SaveChanges();

                    vm.Set(num > 0);
                }
            }

            if (vm.Code == 200)
            {
                return(Redirect("/user/message"));
            }
            else
            {
                return(Content(vm.ToJson()));
            }
        }
Exemplo n.º 15
0
        public ActionResultVM DelNote(int id)
        {
            var vm = new ActionResultVM();

            var uinfo = new Application.UserAuthService(HttpContext).Get();

            using (var db = new Data.ContextBase())
            {
                var mo = db.Notepad.Find(id);
                if (mo.Uid == uinfo.UserId)
                {
                    db.Notepad.Remove(mo);
                    int num = db.SaveChanges();

                    vm.Set(num > 0);
                }
                else
                {
                    vm.Set(ARTag.unauthorized);
                }
            }

            return(vm);
        }
Exemplo n.º 16
0
            public override void OnActionExecuting(ActionExecutingContext context)
            {
                var hc = context.HttpContext;

                //日志记录,设置“__nolog”参数可忽略日志记录,为压力测试等环境考虑(即一些不需要记录请求日志的需求)

                //如果需要记录更详细的日志,可提取请求的参数、表单信息写入日志
                //可能信息量较大,需要考虑分开存储,推荐方案:使用sqlite-net-pcl包按月或按天拆分写入SQLite数据库文件

                if (string.IsNullOrWhiteSpace(hc.Request.Query["__nolog"].ToString()))
                {
                    string controller = context.RouteData.Values["controller"].ToString().ToLower();
                    string action     = context.RouteData.Values["action"].ToString().ToLower();
                    string url        = hc.Request.Path.ToString() + hc.Request.QueryString.Value;

                    try
                    {
                        //客户端信息
                        var ct = new Core.ClientTo(hc);

                        //用户信息
                        var userinfo = Func.Common.GetLoginUserInfo(hc);

                        //日志保存
                        var mo = new Domain.SysLog()
                        {
                            LogId          = Guid.NewGuid().ToString(),
                            SuName         = userinfo.UserName,
                            SuNickname     = userinfo.Nickname,
                            LogAction      = controller + "/" + action,
                            LogUrl         = url,
                            LogIp          = ct.IPv4,
                            LogCreateTime  = DateTime.Now,
                            LogBrowserName = ct.BrowserName,
                            LogSystemName  = ct.SystemName,
                            LogGroup       = 1
                        };

                        try
                        {
                            //IP城市
                            var city = new ipdb.City(GlobalTo.GetValue("logs:ipdb").Replace("~", GlobalTo.ContentRootPath));

                            var ips = mo.LogIp.Split(',');
                            var ipc = string.Empty;
                            foreach (var ip in ips)
                            {
                                var listCity = city.find(ip.Trim().Replace("::1", "127.0.0.1"), "CN").Distinct();
                                ipc += string.Join(",", listCity).TrimEnd(',') + ";";
                            }
                            mo.LogCity = ipc.TrimEnd(';');
                        }
                        catch (Exception)
                        {
                            mo.LogCity = "fail";
                        }

                        mo.LogContent = DicDescription[mo.LogAction.ToLower()];

                        #region 分批写入日志

                        //分批写入满足的条件:缓存的日志数量
                        int cacheLogCount = GlobalTo.GetValue <int>("logs:batchwritecount");
                        //分批写入满足的条件:缓存的时长,单位秒
                        int cacheLogTime = GlobalTo.GetValue <int>("logs:batchwritetime");

                        //日志记录
                        var cacheLogsKey = "Global_Logs";
                        //上次写入的时间
                        var cacheLogWriteKey = "Global_Logs_Write";

                        if (!(Core.CacheTo.Get(cacheLogsKey) is List <Domain.SysLog> cacheLogs))
                        {
                            cacheLogs = new List <Domain.SysLog>();
                        }
                        cacheLogs.Add(mo);

                        var cacheLogWrite = Core.CacheTo.Get(cacheLogWriteKey) as DateTime?;
                        if (!cacheLogWrite.HasValue)
                        {
                            cacheLogWrite = DateTime.Now;
                        }

                        if (cacheLogs?.Count > cacheLogCount || DateTime.Now.ToTimestamp() - cacheLogWrite.Value.ToTimestamp() > cacheLogTime)
                        {
                            using (var db = new Data.ContextBase())
                            {
                                db.SysLog.AddRange(cacheLogs);
                                db.SaveChanges();
                            }

                            cacheLogs     = null;
                            cacheLogWrite = DateTime.Now;
                        }

                        Core.CacheTo.Set(cacheLogsKey, cacheLogs, 3600 * 24 * 30);
                        Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite, 3600 * 24 * 30);

                        #endregion
                    }
                    catch (Exception)
                    {
                        //throw new System.Exception("写入操作日志失败");
                    }
                }

                base.OnActionExecuting(context);
            }
Exemplo n.º 17
0
        public ActionResultVM Update(Domain.GuffRecord mo)
        {
            var vm = new ActionResultVM();

            try
            {
                var uinfo = new Application.UserAuthService(HttpContext).Get();

                if (string.IsNullOrWhiteSpace(mo.GrContent) && string.IsNullOrWhiteSpace(mo.GrImage) && string.IsNullOrWhiteSpace(mo.GrAudio) && string.IsNullOrWhiteSpace(mo.GrVideo))
                {
                    vm.Code = 1;
                    vm.Msg  = "内容不能为空(内容、图片、音频、视频 至少有一项有内容)";
                }
                else if (string.IsNullOrWhiteSpace(mo.GrTag))
                {
                    vm.Code = 2;
                    vm.Msg  = "标签不能为空";
                }
                else if (uinfo.UserId == 0)
                {
                    vm.Set(ARTag.unauthorized);
                }
                else
                {
                    using var db = new Data.ContextBase();
                    var currMo = db.GuffRecord.Find(mo.GrId);

                    if (currMo == null)
                    {
                        vm.Set(ARTag.invalid);
                    }
                    else
                    {
                        currMo.GrTypeName  = Fast.ParsingTo.JsSafeJoin(mo.GrTypeName);
                        currMo.GrTypeValue = Fast.ParsingTo.JsSafeJoin(mo.GrTypeValue);
                        currMo.GrObject    = Fast.ParsingTo.JsSafeJoin(mo.GrObject);

                        currMo.GrContent   = mo.GrContent;
                        currMo.GrContentMd = mo.GrContentMd;

                        currMo.GrImage  = Fast.ParsingTo.JsSafeJoin(mo.GrImage);
                        currMo.GrAudio  = Fast.ParsingTo.JsSafeJoin(mo.GrAudio);
                        currMo.GrVideo  = Fast.ParsingTo.JsSafeJoin(mo.GrVideo);
                        currMo.GrFile   = Fast.ParsingTo.JsSafeJoin(mo.GrFile);
                        currMo.GrRemark = mo.GrRemark;

                        currMo.GrTag        = mo.GrTag;
                        currMo.GrUpdateTime = DateTime.Now;
                        currMo.GrOpen       = mo.GrOpen ?? 1;

                        db.Update(currMo);

                        int num = db.SaveChanges();

                        vm.Data = mo.GrId;
                        vm.Set(num > 0);
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                Filters.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemplo n.º 18
0
        public Startup(IConfiguration configuration, IHostEnvironment env)
        {
            GlobalTo.Configuration   = configuration;
            GlobalTo.HostEnvironment = env;

            #region 第三方登录
            QQConfig.APPID        = GlobalTo.GetValue("OAuthLogin:QQ:APPID");
            QQConfig.APPKey       = GlobalTo.GetValue("OAuthLogin:QQ:APPKey");
            QQConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:QQ:Redirect_Uri");

            WeiboConfig.AppKey       = GlobalTo.GetValue("OAuthLogin:Weibo:AppKey");
            WeiboConfig.AppSecret    = GlobalTo.GetValue("OAuthLogin:Weibo:AppSecret");
            WeiboConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:Weibo:Redirect_Uri");

            GitHubConfig.ClientID        = GlobalTo.GetValue("OAuthLogin:GitHub:ClientID");
            GitHubConfig.ClientSecret    = GlobalTo.GetValue("OAuthLogin:GitHub:ClientSecret");
            GitHubConfig.Redirect_Uri    = GlobalTo.GetValue("OAuthLogin:GitHub:Redirect_Uri");
            GitHubConfig.ApplicationName = GlobalTo.GetValue("OAuthLogin:GitHub:ApplicationName");

            TaoBaoConfig.AppKey       = GlobalTo.GetValue("OAuthLogin:TaoBao:AppKey");
            TaoBaoConfig.AppSecret    = GlobalTo.GetValue("OAuthLogin:TaoBao:AppSecret");
            TaoBaoConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:TaoBao:Redirect_Uri");

            MicroSoftConfig.ClientID     = GlobalTo.GetValue("OAuthLogin:MicroSoft:ClientID");
            MicroSoftConfig.ClientSecret = GlobalTo.GetValue("OAuthLogin:MicroSoft:ClientSecret");
            MicroSoftConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:MicroSoft:Redirect_Uri");

            DingTalkConfig.appId        = GlobalTo.GetValue("OAuthLogin:DingTalk:AppId");
            DingTalkConfig.appSecret    = GlobalTo.GetValue("OAuthLogin:DingTalk:AppSecret");
            DingTalkConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:DingTalk:Redirect_Uri");
            #endregion

            //无创建,有忽略
            using var db = new Data.ContextBase();
            if (db.Database.EnsureCreated())
            {
                var jodb = Core.FileTo.ReadText(GlobalTo.WebRootPath + "/scripts/example/", "data.json").ToJObject();

                db.UserInfo.AddRange(jodb["UserInfo"].ToString().ToEntitys <Domain.UserInfo>());

                db.Tags.AddRange(jodb["Tags"].ToString().ToEntitys <Domain.Tags>());

                db.UserWriting.AddRange(jodb["UserWriting"].ToString().ToEntitys <Domain.UserWriting>());

                db.UserWritingTags.AddRange(jodb["UserWritingTags"].ToString().ToEntitys <Domain.UserWritingTags>());

                db.UserReply.AddRange(jodb["UserReply"].ToString().ToEntitys <Domain.UserReply>());

                db.Run.AddRange(jodb["Run"].ToString().ToEntitys <Domain.Run>());

                db.KeyValues.AddRange(jodb["KeyValues"].ToString().ToEntitys <Domain.KeyValues>());

                db.Gist.AddRange(jodb["Gist"].ToString().ToEntitys <Domain.Gist>());

                db.Draw.AddRange(jodb["Draw"].ToString().ToEntitys <Domain.Draw>());

                db.DocSet.AddRange(jodb["DocSet"].ToString().ToEntitys <Domain.DocSet>());

                db.DocSetDetail.AddRange(jodb["DocSetDetail"].ToString().ToEntitys <Domain.DocSetDetail>());

                db.SaveChanges();
            }
        }
Exemplo n.º 19
0
            public override void OnActionExecuting(ActionExecutingContext context)
            {
                var hc = context.HttpContext;

                //日志记录,设置“__nolog”参数可忽略日志记录,为压力测试等环境考虑(即一些不需要记录请求日志的需求)

                //如果需要记录更详细的日志,可提取请求的参数、表单信息写入日志
                //可能信息量较大,需要考虑分开存储,推荐方案:使用sqlite-net-pcl包按月或按天拆分写入SQLite数据库文件

                if (GlobalTo.GetValue <bool>("logs:enable") && string.IsNullOrWhiteSpace(hc.Request.Query["__nolog"].ToString()))
                {
                    string controller = context.RouteData.Values["controller"].ToString().ToLower();
                    string action     = context.RouteData.Values["action"].ToString().ToLower();
                    string url        = hc.Request.Path.ToString() + hc.Request.QueryString.Value;

                    try
                    {
                        //客户端信息
                        var ct = new Fast.ClientTo(hc);

                        //用户信息
                        var userinfo = Func.Common.GetLoginUserInfo(hc);

                        //日志保存
                        var mo = new Domain.SysLog()
                        {
                            LogId          = Guid.NewGuid().ToString(),
                            SuName         = userinfo.UserName,
                            SuNickname     = userinfo.Nickname,
                            LogAction      = controller + "/" + action,
                            LogUrl         = url,
                            LogIp          = ct.IPv4.Split(',')[0].Trim(),
                            LogCreateTime  = DateTime.Now,
                            LogBrowserName = ct.BrowserName,
                            LogSystemName  = ct.SystemName,
                            LogGroup       = 1
                        };

                        mo.LogContent = DicDescription[mo.LogAction.ToLower()];

                        #region 分批写入日志

                        //分批写入满足的条件:缓存的日志数量
                        int cacheLogCount = GlobalTo.GetValue <int>("logs:batchwritecount");
                        //分批写入满足的条件:缓存的时长,单位秒
                        int cacheLogTime = GlobalTo.GetValue <int>("logs:batchwritetime");

                        //日志记录
                        var cacheLogsKey = "Global_Logs";
                        //上次写入的时间
                        var cacheLogWriteKey = "Global_Logs_Write";

                        if (!(Core.CacheTo.Get(cacheLogsKey) is List <Domain.SysLog> cacheLogs))
                        {
                            cacheLogs = new List <Domain.SysLog>();
                        }
                        cacheLogs.Add(mo);

                        var cacheLogWrite = Core.CacheTo.Get(cacheLogWriteKey) as DateTime?;
                        if (!cacheLogWrite.HasValue)
                        {
                            cacheLogWrite = DateTime.Now;
                        }

                        if (cacheLogs?.Count > cacheLogCount || DateTime.Now.ToTimestamp() - cacheLogWrite.Value.ToTimestamp() > cacheLogTime)
                        {
                            //异步写入日志
                            System.Threading.ThreadPool.QueueUserWorkItem(_ =>
                            {
                                //写入日志前查询IP所属区域
                                var dbpath   = GlobalTo.GetValue("logs:dbpath").Replace("~", GlobalTo.ContentRootPath);
                                using var ds = new IP2Region.DbSearcher(dbpath);

                                foreach (var log in cacheLogs)
                                {
                                    try
                                    {
                                        var ips = log.LogIp.Split(',');
                                        var ipi = new List <string>();

                                        foreach (var ip in ips)
                                        {
                                            //内容格式:国家|区域|省份|市|运营商。无数据默认为0。
                                            var listIpInfo = ds.MemorySearch(ip.Trim().Replace("::1", "127.0.0.1")).Region.Split('|').ToList();

                                            listIpInfo.RemoveAt(1);
                                            listIpInfo = listIpInfo.Where(x => x != "0").Distinct().ToList();

                                            ipi.Add(string.Join(",", listIpInfo));
                                        }

                                        log.LogCity = string.Join(";", ipi);
                                    }
                                    catch (Exception)
                                    {
                                        log.LogCity = "fail";
                                    }
                                }

                                using var db = new Data.ContextBase(Data.ContextBase.DCOB().Options);
                                db.SysLog.AddRange(cacheLogs);
                                db.SaveChanges();

                                //清空数据及更新时间
                                cacheLogs     = null;
                                cacheLogWrite = DateTime.Now;

                                Core.CacheTo.Set(cacheLogsKey, cacheLogs, 3600 * 24 * 30);
                                Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite, 3600 * 24 * 30);
                            });
                        }
                        else
                        {
                            Core.CacheTo.Set(cacheLogsKey, cacheLogs, 3600 * 24 * 30);
                            Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite, 3600 * 24 * 30);
                        }

                        #endregion
                    }
                    catch (Exception)
                    {
                        //throw new System.Exception("写入操作日志失败");
                    }
                }

                base.OnActionExecuting(context);
            }
Exemplo n.º 20
0
        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        public IActionResult Verify()
        {
            var vm = new ActionResultVM();

            var id = RouteData.Values["id"]?.ToString().ToUpper();

            if (!string.IsNullOrWhiteSpace(id))
            {
                var uinfo = new Application.UserAuthService(HttpContext).Get();

                switch (id.ToLower())
                {
                //发送验证邮箱
                case "send":
                {
                    if (User.Identity.IsAuthenticated)
                    {
                        using var db = new Data.ContextBase();
                        var usermo = db.UserInfo.Find(uinfo.UserId);
                        if (usermo.UserMailValid == 1)
                        {
                            vm.Msg = "邮箱已经完成验证";
                        }
                        else if (string.IsNullOrWhiteSpace(usermo.UserMail))
                        {
                            vm.Msg = "邮箱不能为空";
                        }
                        else
                        {
                            var cacheKey = "Global_VerifyMail_" + usermo.UserMail;
                            var issend   = Core.CacheTo.Get(cacheKey) as bool?;
                            if (issend == true)
                            {
                                vm.Msg = "1分钟内只能发送一次验证信息";
                            }
                            else
                            {
                                var tml = Core.FileTo.ReadText(GlobalTo.WebRootPath + "/lib/mailchecker/list.txt");
                                if (tml.Contains(usermo.UserMail.Split('@').LastOrDefault()))
                                {
                                    vm.Msg = "该邮箱已被屏蔽";
                                }
                                else
                                {
                                    //发送验证

                                    var ToMail = usermo.UserMail;

                                    var vjson = new
                                    {
                                        mail = ToMail,
                                        ts   = DateTime.Now.ToTimestamp()
                                    }.ToJson();
                                    var vcode = Core.CalcTo.EnDES(vjson, GlobalTo.GetValue("VerifyCode:Key")).ToLower();

                                    var VerifyLink = string.Format(GlobalTo.GetValue("VerifyCode:Url"), vcode);

                                    var txt = Core.FileTo.ReadText(GlobalTo.WebRootPath + "/template/sendmailverify.html");
                                    txt = txt.Replace("@ToMail@", ToMail).Replace("@VerifyLink@", VerifyLink);

                                    vm = Application.MailService.Send(ToMail, $"[{GlobalTo.GetValue("Common:EnglishName")}] 验证你的邮箱", txt);

                                    if (vm.Code == 200)
                                    {
                                        vm.Msg = "已发送成功";
                                        Core.CacheTo.Set(cacheKey, true, 60, false);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        vm.Msg = "请登录";
                    }
                }
                break;

                //验证邮箱
                default:
                    try
                    {
                        var vjson = Core.CalcTo.DeDES(id, GlobalTo.GetValue("VerifyCode:Key")).ToJObject();
                        if (DateTime.Now.ToTimestamp() - Convert.ToInt32(vjson["ts"]) < 60 * 5)
                        {
                            var mail = vjson["mail"].ToString();
                            if (string.IsNullOrWhiteSpace(mail))
                            {
                                vm.Msg = "邮件地址有误";
                            }
                            else
                            {
                                using var db = new Data.ContextBase();
                                var usermo = db.UserInfo.FirstOrDefault(x => x.UserMail == mail);
                                if (usermo != null)
                                {
                                    if (usermo.UserMailValid == 1)
                                    {
                                        vm.Msg = "已验证,勿重复验证";
                                    }
                                    else
                                    {
                                        usermo.UserMailValid = 1;

                                        db.UserInfo.Update(usermo);

                                        int num = db.SaveChanges();

                                        vm.Set(num > 0);
                                        if (vm.Code == 200)
                                        {
                                            vm.Msg = "恭喜你,验证成功";
                                        }
                                    }
                                }
                                else
                                {
                                    vm.Msg = "邮件地址无效";
                                }
                            }
                        }
                        else
                        {
                            vm.Msg = "链接已过期(5分钟内有效)";
                        }
                    }
                    catch (Exception)
                    {
                        vm.Msg = "链接已失效";
                    }
                    break;
                }
            }
            else
            {
                vm.Msg = "缺失验证码信息";
            }

            return(View(vm));
        }
Exemplo n.º 21
0
        public ActionResultVM SaveUserInfo(Domain.UserInfo mo)
        {
            var vm = new ActionResultVM();

            if (string.IsNullOrWhiteSpace(mo.Nickname))
            {
                vm.Set(ARTag.refuse);
                vm.Msg = "昵称不能为空";

                return(vm);
            }

            int uid = new Application.UserAuthService(HttpContext).Get().UserId;

            using (var db = new Data.ContextBase())
            {
                var usermo = db.UserInfo.Find(uid);

                //变更账号
                if (!string.IsNullOrWhiteSpace(mo.UserName) && usermo.UserNameChange != 1 && usermo.UserName != mo.UserName)
                {
                    //账号重复
                    if (db.UserInfo.Any(x => x.UserName == mo.UserName))
                    {
                        vm.Set(ARTag.exist);
                        vm.Msg = "账号已经存在";

                        return(vm);
                    }
                    else
                    {
                        usermo.UserName       = mo.UserName;
                        usermo.UserNameChange = 1;
                    }
                }

                //变更邮箱
                if (mo.UserMail != usermo.UserMail)
                {
                    usermo.UserMailValid = 0;

                    //邮箱正则验证
                    if (!string.IsNullOrWhiteSpace(mo.UserMail))
                    {
                        if (!Fast.ParsingTo.IsMail(mo.UserMail))
                        {
                            vm.Set(ARTag.invalid);
                            vm.Msg = "邮箱格式有误";

                            return(vm);
                        }
                        else
                        {
                            if (db.UserInfo.Any(x => x.UserMail == mo.UserMail))
                            {
                                vm.Set(ARTag.exist);
                                vm.Msg = "邮箱已经存在";

                                return(vm);
                            }
                        }
                    }
                }

                usermo.UserMail  = mo.UserMail;
                usermo.Nickname  = mo.Nickname;
                usermo.UserPhone = mo.UserPhone;
                usermo.UserUrl   = mo.UserUrl;

                db.UserInfo.Update(usermo);
                var num = db.SaveChanges();

                //更新授权信息
                using (var ac = new AccountController())
                {
                    ac.SetAuth(HttpContext, usermo, true);
                }

                vm.Set(num > 0);
            };

            return(vm);
        }
Exemplo n.º 22
0
        /// <summary>
        /// 公共登录验证
        /// </summary>
        /// <param name="vt">登录类型</param>
        /// <param name="mo">用户信息</param>
        /// <param name="isremember">记住账号</param>
        /// <returns></returns>
        private ActionResultVM ValidateLogin(ValidateloginType vt, Domain.UserInfo mo, bool isremember = true)
        {
            var vm = new ActionResultVM();

            string sql = string.Empty;

            using var db = new Data.ContextBase();
            var uiR = db.UserInfo;

            Domain.UserInfo outMo = new Domain.UserInfo();

            switch (vt)
            {
            case ValidateloginType.local:
                if (string.IsNullOrWhiteSpace(mo.UserName) || string.IsNullOrWhiteSpace(mo.UserPwd))
                {
                    vm.Msg = "用户名或密码不能为空";
                    return(vm);
                }
                else
                {
                    mo.UserPwd = Core.CalcTo.MD5(mo.UserPwd);

                    //邮箱登录
                    if (Fast.ParsingTo.IsMail(mo.UserName))
                    {
                        outMo = uiR.FirstOrDefault(x => x.UserMail == mo.UserName && x.UserPwd == mo.UserPwd);
                    }
                    else
                    {
                        outMo = uiR.FirstOrDefault(x => x.UserName == mo.UserName && x.UserPwd == mo.UserPwd);
                    }
                }
                break;

            case ValidateloginType.qq:
                outMo = uiR.FirstOrDefault(x => x.OpenId1.Equals(mo.OpenId1));
                break;

            case ValidateloginType.weibo:
                outMo = uiR.FirstOrDefault(x => x.OpenId2.Equals(mo.OpenId2));
                break;

            case ValidateloginType.github:
                outMo = uiR.FirstOrDefault(x => x.OpenId3.Equals(mo.OpenId3));
                break;

            case ValidateloginType.taobao:
                outMo = uiR.FirstOrDefault(x => x.OpenId4.Equals(mo.OpenId4));
                break;

            case ValidateloginType.microsoft:
                outMo = uiR.FirstOrDefault(x => x.OpenId5.Equals(mo.OpenId5));
                break;

            case ValidateloginType.dingtalk:
                outMo = uiR.FirstOrDefault(x => x.OpenId6.Equals(mo.OpenId6));
                break;
            }

            if (outMo == null || outMo.UserId == 0)
            {
                vm.Msg = "用户名或密码错误";
                return(vm);
            }

            if (outMo.LoginLimit == 1)
            {
                vm.Msg = "用户已被禁止登录";
                return(vm);
            }

            //刷新登录标记
            outMo.UserLoginTime = DateTime.Now;
            outMo.UserSign      = outMo.UserLoginTime.Value.ToTimestamp().ToString();
            uiR.Update(outMo);
            var num = db.SaveChanges();

            if (num < 1)
            {
                vm.Msg = "请求登录被拒绝";
                return(vm);
            }

            try
            {
                //登录标记 缓存5分钟,绝对过期
                var usk = "UserSign_" + outMo.UserId;
                Core.CacheTo.Set(usk, outMo.UserSign, 5 * 60, false);

                //写入授权
                SetAuth(HttpContext, outMo, isremember);

                //生成Token
                vm.Data = Application.UserAuthService.TokenMake(outMo);

                vm.Set(ARTag.success);
            }
            catch (Exception ex)
            {
                vm.Set(ex);
            }

            return(vm);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 登录授权回调
        /// </summary>
        /// <param name="authorizeResult">获取授权码以及防伪标识</param>
        /// <returns></returns>
        public IActionResult AuthCallback(LoginBase.AuthorizeResult authorizeResult)
        {
            var vm = new ActionResultVM();

            try
            {
                if (string.IsNullOrWhiteSpace(authorizeResult.code))
                {
                    vm.Set(ARTag.unauthorized);
                }
                else
                {
                    //唯一标示
                    string openId = string.Empty;
                    //注册信息
                    var mo = new Domain.UserInfo()
                    {
                        LoginLimit     = 0,
                        UserSex        = 0,
                        UserCreateTime = DateTime.Now
                    };
                    //头像
                    string avatar = string.Empty;
                    //头像(高清)
                    string avatarhd = string.Empty;

                    Enum.TryParse(RouteData.Values["id"]?.ToString(), true, out ValidateloginType vtype);

                    switch (vtype)
                    {
                    case ValidateloginType.qq:
                    {
                        //获取 access_token
                        var tokenEntity = QQ.AccessToken(new QQ_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });

                        //获取 OpendId
                        var openidEntity = QQ.OpenId(new QQ_OpenId_RequestEntity()
                            {
                                access_token = tokenEntity.access_token
                            });

                        //获取 UserInfo
                        var userEntity = QQ.OpenId_Get_User_Info(new QQ_OpenAPI_RequestEntity()
                            {
                                access_token = tokenEntity.access_token,
                                openid       = openidEntity.openid
                            });

                        //身份唯一标识
                        openId     = openidEntity.openid;
                        mo.OpenId1 = openId;

                        mo.Nickname = userEntity.nickname;
                        mo.UserSex  = userEntity.gender == "男" ? 1 : 2;
                        mo.UserSay  = "";
                        mo.UserUrl  = "";

                        avatar   = userEntity.figureurl_qq_1;
                        avatarhd = userEntity.figureurl_qq_2;
                    }
                    break;

                    case ValidateloginType.weibo:
                    {
                        //获取 access_token
                        var tokenEntity = Weibo.AccessToken(new Weibo_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });

                        //获取 access_token 的授权信息
                        var tokenInfoEntity = Weibo.GetTokenInfo(new Weibo_GetTokenInfo_RequestEntity()
                            {
                                access_token = tokenEntity.access_token
                            });

                        //获取 users/show
                        var userEntity = Weibo.UserShow(new Weibo_UserShow_RequestEntity()
                            {
                                access_token = tokenEntity.access_token,
                                uid          = Convert.ToInt64(tokenInfoEntity.uid)
                            });

                        openId     = tokenEntity.access_token;
                        mo.OpenId2 = openId;

                        mo.Nickname = userEntity.screen_name;
                        mo.UserSex  = userEntity.gender == "m" ? 1 : userEntity.gender == "f" ? 2 : 0;
                        mo.UserSay  = userEntity.description;
                        mo.UserUrl  = userEntity.domain;

                        avatar   = userEntity.profile_image_url;
                        avatarhd = userEntity.avatar_large;
                    }
                    break;

                    case ValidateloginType.github:
                    {
                        //获取 access_token
                        var tokenEntity = GitHub.AccessToken(new GitHub_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });

                        //获取 user
                        var userEntity = GitHub.User(new GitHub_User_RequestEntity()
                            {
                                access_token = tokenEntity.access_token
                            });

                        openId     = userEntity.id.ToString();
                        mo.OpenId3 = openId;

                        mo.Nickname = userEntity.name;
                        mo.UserSay  = userEntity.bio;
                        mo.UserUrl  = userEntity.blog;
                        mo.UserMail = userEntity.email;

                        avatar   = userEntity.avatar_url;
                        avatarhd = userEntity.avatar_url;
                    }
                    break;

                    case ValidateloginType.taobao:
                    {
                        //获取 access_token
                        var tokenEntity = TaoBao.AccessToken(new TaoBao_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });

                        openId     = tokenEntity.open_uid;
                        mo.OpenId4 = openId;

                        mo.Nickname = "淘宝用户";
                    }
                    break;

                    case ValidateloginType.microsoft:
                    {
                        //获取 access_token
                        var tokenEntity = MicroSoft.AccessToken(new MicroSoft_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });

                        //获取 user
                        var userEntity = MicroSoft.User(new MicroSoft_User_RequestEntity()
                            {
                                access_token = tokenEntity.access_token
                            });

                        openId     = userEntity.id.ToString();
                        mo.OpenId5 = openId;

                        mo.Nickname = userEntity.last_name + userEntity.first_name;
                        mo.UserMail = userEntity.emails?["account"].ToStringOrEmpty();
                    }
                    break;

                    case ValidateloginType.dingtalk:
                    {
                        //获取 user
                        var userEntity = DingTalk.User(new DingTalk_User_RequestEntity(), authorizeResult.code);

                        openId     = userEntity.openid;
                        mo.OpenId6 = openId;

                        mo.Nickname = userEntity.nick;
                    }
                    break;
                    }

                    mo.UserCreateTime = DateTime.Now;
                    mo.UserName       = openId;
                    mo.UserPwd        = Core.CalcTo.MD5(openId);
                    if (!string.IsNullOrWhiteSpace(avatar))
                    {
                        mo.UserPhoto = Core.UniqueTo.LongId().ToString() + ".jpg";
                    }

                    if (string.IsNullOrWhiteSpace(openId))
                    {
                        vm.Set(ARTag.unauthorized);
                        vm.Msg = "身份验证失败";
                    }
                    else
                    {
                        //判断是绑定操作
                        bool isbind = User.Identity.IsAuthenticated && authorizeResult.state.StartsWith("bind");
                        if (isbind)
                        {
                            int uid = new Application.UserAuthService(HttpContext).Get().UserId;

                            using (var db = new Data.ContextBase())
                            {
                                //检测是否绑定其它账号
                                var queryIsBind = db.UserInfo.Where(x => x.UserId != uid);
                                switch (vtype)
                                {
                                case ValidateloginType.qq:
                                    queryIsBind = queryIsBind.Where(x => x.OpenId1 == openId);
                                    break;

                                case ValidateloginType.weibo:
                                    queryIsBind = queryIsBind.Where(x => x.OpenId2 == openId);
                                    break;

                                case ValidateloginType.github:
                                    queryIsBind = queryIsBind.Where(x => x.OpenId3 == openId);
                                    break;

                                case ValidateloginType.taobao:
                                    queryIsBind = queryIsBind.Where(x => x.OpenId4 == openId);
                                    break;

                                case ValidateloginType.microsoft:
                                    queryIsBind = queryIsBind.Where(x => x.OpenId5 == openId);
                                    break;

                                case ValidateloginType.dingtalk:
                                    queryIsBind = queryIsBind.Where(x => x.OpenId6 == openId);
                                    break;
                                }
                                if (queryIsBind.Count() > 0)
                                {
                                    return(Content("已绑定其它账号,不能重复绑定"));
                                }

                                var userInfo = db.UserInfo.Find(uid);

                                switch (vtype)
                                {
                                case ValidateloginType.qq:
                                    userInfo.OpenId1 = openId;
                                    break;

                                case ValidateloginType.weibo:
                                    userInfo.OpenId2 = openId;
                                    break;

                                case ValidateloginType.github:
                                    userInfo.OpenId3 = openId;
                                    break;

                                case ValidateloginType.taobao:
                                    userInfo.OpenId4 = openId;
                                    break;

                                case ValidateloginType.microsoft:
                                    userInfo.OpenId5 = openId;
                                    break;

                                case ValidateloginType.dingtalk:
                                    userInfo.OpenId6 = openId;
                                    break;
                                }
                                db.UserInfo.Update(userInfo);
                                db.SaveChanges();
                            }

                            return(Redirect("/user/setting"));
                        }
                        else
                        {
                            using var db = new Data.ContextBase();
                            Domain.UserInfo vmo = null;
                            switch (vtype)
                            {
                            case ValidateloginType.qq:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId1 == openId);
                                break;

                            case ValidateloginType.weibo:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId2 == openId);
                                break;

                            case ValidateloginType.github:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId3 == openId);
                                break;

                            case ValidateloginType.taobao:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId4 == openId);
                                break;

                            case ValidateloginType.microsoft:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId5 == openId);
                                break;

                            case ValidateloginType.dingtalk:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId6 == openId);
                                break;
                            }
                            //未注册
                            if (vmo == null)
                            {
                                var ruvm = RegisterUser(mo);
                                if (ruvm.Code == 200)
                                {
                                    vm = ValidateLogin(vtype, mo);
                                    //拉取头像
                                    if (vm.Code == 200 && (!string.IsNullOrWhiteSpace(avatar) || !string.IsNullOrWhiteSpace(avatarhd)))
                                    {
                                        try
                                        {
                                            using var wc = new System.Net.WebClient();
                                            var fullpath = System.IO.Path.Combine(GlobalTo.WebRootPath, GlobalTo.GetValue("StaticResource:RootDir"),
                                                                                  GlobalTo.GetValue("StaticResource:AvatarPath"));

                                            if (!System.IO.Directory.Exists(fullpath))
                                            {
                                                System.IO.Directory.CreateDirectory(fullpath);
                                            }
                                            if (!string.IsNullOrWhiteSpace(avatar))
                                            {
                                                wc.DownloadFile(avatar, System.IO.Path.Combine(fullpath, mo.UserPhoto));
                                            }
                                            if (!string.IsNullOrWhiteSpace(avatarhd))
                                            {
                                                wc.DownloadFile(avatarhd, System.IO.Path.Combine(fullpath, mo.UserPhoto.Replace(".jpg", "_lg.jpg")));
                                            }
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                }
                                else
                                {
                                    vm.Msg = ruvm.Msg;
                                }
                            }
                            else
                            {
                                vm = ValidateLogin(vtype, vmo);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);

                Filters.FilterConfigs.WriteLog(HttpContext, ex);
            }

            //成功
            if (vm.Code == 200)
            {
                var rurl = Request.Cookies["ReturnUrl"];
                rurl = string.IsNullOrWhiteSpace(rurl) ? "/" : rurl;

                if (rurl.StartsWith("http"))
                {
                    rurl += "?cookie=ok";
                }

                return(Redirect(rurl));
            }
            else
            {
                string msg = "【登录失败】( " + vm.Msg + " )".ToEncode();
                return(Redirect("/home/error?msg=" + msg));
            }
        }
Exemplo n.º 24
0
            public override void OnActionExecuting(ActionExecutingContext context)
            {
                var    hc         = context.HttpContext;
                string controller = context.RouteData.Values["controller"].ToString().ToLower();
                string action     = context.RouteData.Values["action"].ToString().ToLower();
                var    ca         = "/" + controller + "/" + action;
                string url        = hc.Request.Path.ToString() + hc.Request.QueryString.Value;

                //用户信息
                var userinfo = Application.CommonService.GetLoginUserInfo(hc);

                //角色有权限访问配置的菜单
                if (!Application.CommonService.QueryMenuIsAuth(userinfo.RoleId, ca))
                {
                    context.Result = new ContentResult()
                    {
                        Content    = "unauthorized",
                        StatusCode = 401
                    };
                }

                //日志记录,设置“__nolog”参数可忽略日志记录,为压力测试等环境考虑(即一些不需要记录请求日志的需求)
                if (GlobalTo.GetValue <bool>("logs:enable") && string.IsNullOrWhiteSpace(hc.Request.Query["__nolog"].ToString()))
                {
                    try
                    {
                        //客户端信息
                        var ct = new ClientTo(hc);

                        //日志保存
                        var mo = new Domain.SysLog()
                        {
                            SuName        = userinfo.UserName,
                            SuNickname    = userinfo.Nickname,
                            LogAction     = ca,
                            LogUrl        = url,
                            LogIp         = ct.IPv4,
                            LogUserAgent  = ct.UserAgent,
                            LogCreateTime = DateTime.Now,
                            LogGroup      = 1,
                            LogLevel      = "I"
                        };

                        if (DicDescription.ContainsKey(ca))
                        {
                            mo.LogContent = DicDescription[ca];
                        }

                        #region 分批写入日志

                        //分批写入满足的条件:缓存的日志数量
                        int cacheLogCount = GlobalTo.GetValue <int>("logs:CacheWriteCount");
                        //分批写入满足的条件:缓存的时长,单位秒
                        int cacheLogTime = GlobalTo.GetValue <int>("logs:CacheWriteSecond");

                        //日志记录
                        var cacheLogsKey = "Global_Logs";
                        //上次写入的时间
                        var cacheLogWriteKey = "Global_Logs_Write";

                        if (!(Core.CacheTo.Get(cacheLogsKey) is List <Domain.SysLog> cacheLogs))
                        {
                            cacheLogs = new List <Domain.SysLog>();
                        }
                        cacheLogs.Add(mo);

                        var cacheLogWrite = Core.CacheTo.Get(cacheLogWriteKey) as DateTime?;
                        if (!cacheLogWrite.HasValue)
                        {
                            cacheLogWrite = DateTime.Now;
                        }

                        if (cacheLogs?.Count > cacheLogCount || DateTime.Now.ToTimestamp() - cacheLogWrite.Value.ToTimestamp() > cacheLogTime)
                        {
                            //异步写入日志
                            System.Threading.ThreadPool.QueueUserWorkItem(_ =>
                            {
                                try
                                {
                                    var ipto = new IPAreaTo();
                                    //写入日志前
                                    foreach (var log in cacheLogs)
                                    {
                                        log.LogId   = Core.UniqueTo.LongId().ToString();
                                        log.LogArea = ipto.Parse(log.LogIp);

                                        var uato           = new UserAgentTo(log.LogUserAgent);
                                        log.LogBrowserName = uato.BrowserName + " " + uato.BrowserVersion;
                                        log.LogSystemName  = uato.SystemName + " " + uato.SystemVersion;
                                        if (uato.IsBot)
                                        {
                                            log.LogGroup = 2;
                                        }
                                    }

                                    using var db = new Data.ContextBase(Data.ContextBase.DCOB().Options);
                                    db.SysLog.AddRange(cacheLogs);
                                    db.SaveChanges();

                                    //清空数据及更新时间
                                    cacheLogs     = null;
                                    cacheLogWrite = DateTime.Now;

                                    Core.CacheTo.Set(cacheLogsKey, cacheLogs);
                                    Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("写入日志出错:" + ex.Message);
                                }
                            });
                        }
                        else
                        {
                            Core.CacheTo.Set(cacheLogsKey, cacheLogs);
                            Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite);
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("写入日志出错:" + ex.Message);
                    }
                }

                base.OnActionExecuting(context);
            }
Exemplo n.º 25
0
        public ActionResultVM Add(Domain.GuffRecord mo)
        {
            var vm = new ActionResultVM();

            try
            {
                var uinfo = new Application.UserAuthService(HttpContext).Get();

                if (string.IsNullOrWhiteSpace(mo.GrContent) && string.IsNullOrWhiteSpace(mo.GrImage) && string.IsNullOrWhiteSpace(mo.GrAudio) && string.IsNullOrWhiteSpace(mo.GrVideo))
                {
                    vm.Code = 1;
                    vm.Msg  = "内容不能为空(内容、图片、音频、视频 至少有一项有内容)";
                }
                else if (string.IsNullOrWhiteSpace(mo.GrTag))
                {
                    vm.Code = 2;
                    vm.Msg  = "标签不能为空";
                }
                else if (uinfo.UserId == 0)
                {
                    vm.Set(ARTag.unauthorized);
                }
                else
                {
                    using var db = new Data.ContextBase();

                    if (db.UserInfo.Find(uinfo.UserId).UserMailValid != 1)
                    {
                        vm.Code = 1;
                        vm.Msg  = "请先验证邮箱";
                    }
                    else
                    {
                        var now = DateTime.Now;

                        mo.Uid          = uinfo.UserId;
                        mo.GrId         = Core.UniqueTo.LongId().ToString();
                        mo.GrCreateTime = now;
                        mo.GrUpdateTime = now;
                        mo.GrStatus     = 1;
                        mo.GrReadNum    = 0;
                        mo.GrLaud       = 0;
                        mo.GrMark       = 0;
                        mo.GrReplyNum   = 0;
                        mo.GrOpen ??= 1;

                        mo.GrTypeName  = Fast.ParsingTo.JsSafeJoin(mo.GrTypeName);
                        mo.GrTypeValue = Fast.ParsingTo.JsSafeJoin(mo.GrTypeValue);
                        mo.GrObject    = Fast.ParsingTo.JsSafeJoin(mo.GrObject);
                        mo.GrImage     = Fast.ParsingTo.JsSafeJoin(mo.GrImage);
                        mo.GrAudio     = Fast.ParsingTo.JsSafeJoin(mo.GrAudio);
                        mo.GrVideo     = Fast.ParsingTo.JsSafeJoin(mo.GrVideo);
                        mo.GrFile      = Fast.ParsingTo.JsSafeJoin(mo.GrFile);
                        mo.GrTag       = Fast.ParsingTo.JsSafeJoin(mo.GrTag);

                        db.GuffRecord.Add(mo);

                        int num = db.SaveChanges();

                        vm.Data = mo.GrId;
                        vm.Set(num > 0);
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                Filters.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemplo n.º 26
0
        public ActionResultVM Detail(string id)
        {
            var vm = new ActionResultVM();

            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    vm.Set(ARTag.invalid);
                }
                else
                {
                    var ctype = Application.EnumService.ConnectionType.GuffRecord.ToString();

                    var uinfo = new Application.UserAuthService(HttpContext).Get();

                    using var db = new Data.ContextBase();
                    var query = from a in db.GuffRecord
                                join b in db.UserInfo on a.Uid equals b.UserId
                                join c in db.UserConnection.Where(x => x.UconnTargetType == ctype && x.UconnAction == 1 && x.Uid == uinfo.UserId) on a.GrId equals c.UconnTargetId into cg
                                from c1 in cg.DefaultIfEmpty()
                                where a.GrId == id
                                select new
                    {
                        a,
                        c1.UconnTargetId,
                        b.Nickname
                    };
                    var qm = query.FirstOrDefault();
                    if (qm == null)
                    {
                        vm.Set(ARTag.invalid);
                    }
                    else
                    {
                        if (qm.a.GrOpen == 1 || uinfo.UserId == qm.a.Uid)
                        {
                            // 阅读 +1
                            qm.a.GrReadNum += 1;
                            db.Update(qm.a);
                            db.SaveChanges();

                            qm.a.Spare1 = string.IsNullOrEmpty(qm.UconnTargetId) ? "" : "laud";
                            qm.a.Spare2 = (uinfo.UserId == qm.a.Uid) ? "owner" : "";
                            qm.a.Spare3 = qm.Nickname;

                            vm.Data = qm.a;

                            vm.Set(ARTag.success);
                        }
                        else
                        {
                            vm.Set(ARTag.unauthorized);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                Filters.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemplo n.º 27
0
        public ActionResultVM UpdateUserPhoto(string type, string source)
        {
            var vm = new ActionResultVM();

            var uinfo = new Application.UserAuthService(HttpContext).Get();

            try
            {
                var fullpath = Path.Combine(GlobalTo.WebRootPath, GlobalTo.GetValue("StaticResource:RootDir"), GlobalTo.GetValue("StaticResource:AvatarPath")) + "/";

                if (!Directory.Exists(fullpath))
                {
                    Directory.CreateDirectory(fullpath);
                }

                if (string.IsNullOrWhiteSpace(uinfo.UserPhoto))
                {
                    uinfo.UserPhoto = Core.UniqueTo.LongId() + ".jpg";
                }
                var upname = uinfo.UserPhoto.Split('?')[0];
                var npnew  = upname + "?" + DateTime.Now.ToTimestamp();

                switch (type)
                {
                case "file":
                {
                    source = source.Substring(source.LastIndexOf(",") + 1);
                    byte[] bytes = Convert.FromBase64String(source);
                    using var ms  = new MemoryStream(bytes);
                    using var bmp = new System.Drawing.Bitmap(ms);
                    var hp = fullpath + upname.Replace(".", "_lg.");
                    bmp.Save(hp, ImageFormat.Jpeg);
                    Fast.ImageTo.MinImg(hp, fullpath, upname, 40, 40, "wh");

                    using (var db = new Data.ContextBase())
                    {
                        var usermo = db.UserInfo.Find(uinfo.UserId);
                        usermo.UserPhoto = npnew;
                        db.UserInfo.Update(usermo);
                        int num = db.SaveChanges();
                        if (num > 0)
                        {
                            using var ac = new AccountController();
                            ac.SetAuth(HttpContext, usermo);
                        }
                    }

                    vm.Set(ARTag.success);
                }
                break;

                case "link":
                {
                    using var wc = new System.Net.WebClient();
                    var hp = fullpath + upname.Replace(".", "_lg.");
                    wc.DownloadFile(source, hp);
                    Fast.ImageTo.MinImg(hp, fullpath, upname, 40, 40, "wh");

                    using (var db = new Data.ContextBase())
                    {
                        var usermo = db.UserInfo.Find(uinfo.UserId);
                        usermo.UserPhoto = npnew;
                        db.UserInfo.Update(usermo);
                        int num = db.SaveChanges();
                        if (num > 0)
                        {
                            using var ac = new AccountController();
                            ac.SetAuth(HttpContext, usermo);
                        }
                    }

                    vm.Set(ARTag.success);
                }
                break;
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
            }

            return(vm);
        }
Exemplo n.º 28
0
        public ActionResultVM ReplyAdd(Domain.UserReply mo, string id)
        {
            var vm = new ActionResultVM();

            try
            {
                var uinfo = new Application.UserAuthService(HttpContext).Get();

                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    mo.Uid = uinfo.UserId;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(mo.UrAnonymousName) || !Fast.ParsingTo.IsMail(mo.UrAnonymousMail))
                    {
                        vm.Set(ARTag.invalid);
                        vm.Msg = "昵称、邮箱不能为空";

                        return(vm);
                    }

                    mo.Uid = 0;
                }

                if (string.IsNullOrWhiteSpace(id))
                {
                    vm.Set(ARTag.invalid);
                }
                else if (string.IsNullOrWhiteSpace(mo.UrContent))
                {
                    vm.Set(ARTag.invalid);
                    vm.Msg = "回复内容不能为空";
                }
                else
                {
                    using var db = new Data.ContextBase();
                    var guffmo = db.GuffRecord.Find(id);
                    if (guffmo == null)
                    {
                        vm.Set(ARTag.invalid);
                    }
                    else
                    {
                        mo.Uid          = uinfo.UserId;
                        mo.UrTargetType = Application.EnumService.ConnectionType.GuffRecord.ToString();
                        mo.UrTargetId   = id;
                        mo.UrCreateTime = DateTime.Now;
                        mo.UrStatus     = 1;
                        mo.UrTargetPid  = 0;

                        mo.UrAnonymousLink = Fast.ParsingTo.JsSafeJoin(mo.UrAnonymousLink);

                        db.UserReply.Add(mo);

                        guffmo.GrReplyNum += 1;
                        db.GuffRecord.Update(guffmo);

                        int num = db.SaveChanges();
                        vm.Set(num > 0);
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                Filters.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemplo n.º 29
0
        public ActionResultVM Connection(string type, int ac, string id)
        {
            var vm = new ActionResultVM();

            try
            {
                var uinfo = new Application.UserAuthService(HttpContext).Get();

                if (uinfo.UserId == 0)
                {
                    vm.Set(ARTag.unauthorized);
                }
                else if (string.IsNullOrWhiteSpace(id))
                {
                    vm.Set(ARTag.invalid);
                }
                else if (!new List <string> {
                    "add", "cancel"
                }.Contains(type))
                {
                    vm.Set(ARTag.invalid);
                }
                else if (!new List <int> {
                    1, 2
                }.Contains(ac))
                {
                    vm.Set(ARTag.invalid);
                }
                else
                {
                    using var db = new Data.ContextBase();
                    var currMo = db.GuffRecord.Find(id);

                    if (currMo == null)
                    {
                        vm.Set(ARTag.invalid);
                    }
                    else
                    {
                        var ctype = Application.EnumService.ConnectionType.GuffRecord.ToString();
                        switch (type)
                        {
                        case "add":
                        {
                            if (db.UserConnection.Any(x => x.Uid == uinfo.UserId && x.UconnTargetType == ctype && x.UconnTargetId == id && x.UconnAction == ac))
                            {
                                vm.Set(ARTag.exist);
                            }
                            else
                            {
                                //关联记录
                                var ucmo = new Domain.UserConnection()
                                {
                                    UconnId         = Core.UniqueTo.LongId().ToString(),
                                    Uid             = uinfo.UserId,
                                    UconnTargetType = Application.EnumService.ConnectionType.GuffRecord.ToString(),
                                    UconnTargetId   = id,
                                    UconnAction     = ac,
                                    UconnCreateTime = DateTime.Now
                                };

                                db.Add(ucmo);

                                switch (ac)
                                {
                                case 1:
                                    currMo.GrLaud += 1;
                                    break;

                                case 2:
                                    currMo.GrMark += 1;
                                    break;
                                }
                                db.Update(currMo);

                                int num = db.SaveChanges();

                                vm.Set(num > 0);
                            }
                        }
                        break;

                        case "cancel":
                        {
                            var curruc = db.UserConnection.FirstOrDefault(x => x.Uid == uinfo.UserId && x.UconnTargetType == ctype && x.UconnTargetId == id && x.UconnAction == ac);
                            if (curruc == null)
                            {
                                vm.Set(ARTag.invalid);
                            }
                            else
                            {
                                db.Remove(curruc);

                                switch (ac)
                                {
                                case 1:
                                    currMo.GrLaud -= 1;
                                    break;

                                case 2:
                                    currMo.GrMark -= 1;
                                    break;
                                }
                                db.Update(currMo);

                                int num = db.SaveChanges();

                                vm.Set(num > 0);
                            }
                        }
                        break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                Filters.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemplo n.º 30
0
        /// <summary>
        /// 字典
        /// </summary>
        /// <returns></returns>
        public IActionResult KeyValues()
        {
            string cmd = RouteData.Values["id"]?.ToString();

            if (cmd != null)
            {
                string result = string.Empty;
                var    rt     = new List <object>
                {
                    0,
                    "fail"
                };

                try
                {
                    switch (cmd)
                    {
                    case "grab":
                    {
                        string key   = Request.Form["Key"].ToString();
                        string api   = $"https://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key={key.ToEncode()}&bk_length=600";
                        string apirt = Core.HttpTo.Get(api);
                        if (apirt.Length > 100)
                        {
                            using var db = new Data.ContextBase();
                            var kvMo = db.KeyValues.Where(x => x.KeyName == key).FirstOrDefault();
                            if (kvMo == null)
                            {
                                kvMo = new Domain.KeyValues
                                {
                                    KeyId    = Guid.NewGuid().ToString(),
                                    KeyName  = key.ToLower(),
                                    KeyValue = apirt
                                };
                                db.KeyValues.Add(kvMo);
                            }
                            else
                            {
                                kvMo.KeyValue = apirt;
                                db.KeyValues.Update(kvMo);
                            }

                            rt[0] = db.SaveChanges();
                            rt[1] = kvMo;
                        }
                        else
                        {
                            rt[0] = 0;
                            rt[1] = apirt;
                        }
                    }
                    break;

                    case "synonym":
                    {
                        var keys = Request.Form["keys"].ToString().Split(',').ToList();

                        string mainKey = keys.First().ToLower();
                        keys.RemoveAt(0);

                        var listkvs = new List <Domain.KeyValueSynonym>();
                        foreach (var key in keys)
                        {
                            var kvs = new Domain.KeyValueSynonym
                            {
                                KsId    = Guid.NewGuid().ToString(),
                                KeyName = mainKey,
                                KsName  = key.ToLower()
                            };
                            listkvs.Add(kvs);
                        }

                        using var db = new Data.ContextBase();
                        var mo = db.KeyValueSynonym.Where(x => x.KeyName == mainKey).FirstOrDefault();
                        if (mo != null)
                        {
                            db.KeyValueSynonym.Remove(mo);
                        }
                        db.KeyValueSynonym.AddRange(listkvs);
                        int oldrow = db.SaveChanges();
                        rt[0] = 1;
                        rt[1] = " 受影响 " + oldrow + " 行";
                    }
                    break;

                    case "addtag":
                    {
                        var tags = Request.Form["tags"].ToString().Split(',').ToList();

                        if (tags.Count > 0)
                        {
                            using var db = new Data.ContextBase();
                            var mt = db.Tags.Where(x => tags.Contains(x.TagName)).ToList();
                            if (mt.Count == 0)
                            {
                                var listMo = new List <Domain.Tags>();
                                var tagHs  = new HashSet <string>();
                                foreach (var tag in tags)
                                {
                                    if (tagHs.Add(tag))
                                    {
                                        var mo = new Domain.Tags
                                        {
                                            TagName   = tag.ToLower(),
                                            TagStatus = 1,
                                            TagHot    = 0,
                                            TagIcon   = tag.ToLower() + ".svg"
                                        };
                                        listMo.Add(mo);
                                    }
                                }
                                tagHs.Clear();

                                //新增&刷新缓存
                                db.Tags.AddRange(listMo);
                                rt[0] = db.SaveChanges();

                                Application.CommonService.TagsQuery(false);

                                rt[1] = "操作成功";
                            }
                            else
                            {
                                rt[0] = 0;
                                rt[1] = "标签已存在:" + mt.ToJson();
                            }
                        }
                        else
                        {
                            rt[0] = 0;
                            rt[1] = "新增标签不能为空";
                        }
                    }
                    break;
                    }
                }
                catch (Exception ex)
                {
                    rt[1] = ex.Message;
                    rt.Add(ex.StackTrace);
                }

                result = rt.ToJson();
                return(Content(result));
            }
            return(View());
        }