Exemple #1
0
        public SharedResultVM MenuTree()
        {
            var vm = new SharedResultVM();

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

                var list = db.DocSetDetail.Where(x => x.DsCode == code).OrderBy(x => x.DsdOrder).Select(x => new
                {
                    x.DsdId,
                    x.DsdPid,
                    x.DsdTitle,
                    x.DsdOrder,
                    IsCatalog = string.IsNullOrEmpty(x.DsdContentMd)
                }).ToList();

                var listtree = Core.TreeTo.ListToTree(list, "DsdPid", "DsdId", new List <string> {
                    Guid.Empty.ToString()
                });
                if (string.IsNullOrWhiteSpace(listtree))
                {
                    vm.Set(SharedEnum.RTag.lack);
                }
                else
                {
                    vm.Data = listtree.ToJArray();
                    vm.Set(SharedEnum.RTag.success);
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                Apps.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemple #2
0
        public IActionResult DelMessage()
        {
            var vm = new SharedResultVM();

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

            if (!string.IsNullOrWhiteSpace(id))
            {
                var uinfo = Apps.LoginService.Get(HttpContext);

                var um = db.UserMessage.Find(id);
                if (um == null)
                {
                    vm.Set(SharedEnum.RTag.lack);
                }
                else if (um?.Uid != uinfo.UserId)
                {
                    vm.Set(SharedEnum.RTag.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()));
            }
        }
Exemple #3
0
        public SharedResultVM UpdateNewPassword(string oldpwd, string newpwd1, string newpwd2)
        {
            var vm = new SharedResultVM();

            if (string.IsNullOrWhiteSpace(oldpwd) || string.IsNullOrWhiteSpace(newpwd1))
            {
                vm.Msg = "密码不能为空";
            }
            else if (newpwd1.Length < 5)
            {
                vm.Msg = "密码长度至少 5 位";
            }
            else if (newpwd1 != newpwd2)
            {
                vm.Msg = "两次输入的密码不一致";
            }
            else
            {
                var userinfo = Apps.LoginService.GetLoginUserInfo(HttpContext);

                var mo = db.SysUser.Find(userinfo.UserId);
                if (mo != null && mo.SuPwd == Core.CalcTo.MD5(oldpwd))
                {
                    mo.SuPwd = Core.CalcTo.MD5(newpwd1);
                    db.SysUser.Update(mo);

                    vm.Set(db.SaveChanges() > 0);
                }
                else
                {
                    vm.Msg = "现有密码错误";
                }
            }

            return(vm);
        }
Exemple #4
0
        public SharedResultVM QueryNoteOne(int id)
        {
            var vm = new SharedResultVM();

            var uinfo = Apps.LoginService.Get(HttpContext);

            var mo = db.Notepad.Find(id);

            if (mo == null)
            {
                vm.Set(SharedEnum.RTag.invalid);
            }
            else if (mo.Uid == uinfo.UserId)
            {
                vm.Set(SharedEnum.RTag.success);
                vm.Data = mo;
            }
            else
            {
                vm.Set(SharedEnum.RTag.unauthorized);
            }

            return(vm);
        }
Exemple #5
0
    /// <summary>
    /// 入口
    /// </summary>
    /// <param name="tdb"></param>
    /// <param name="conn"></param>
    /// <param name="databaseName"></param>
    /// <param name="dkCall"></param>
    /// <returns></returns>
    static SharedResultVM Entry(SharedEnum.TypeDB tdb, string conn, string databaseName, Func <DataKit, object> dkCall)
    {
        var vm = new SharedResultVM();

        try
        {
            var dk = DataKit.Init(tdb, conn, databaseName);
            if (dk != null)
            {
                vm.Data = dkCall(dk);
                vm.Set(SharedEnum.RTag.success);
            }
            else
            {
                vm.Set(SharedEnum.RTag.error);
            }
        }
        catch (Exception ex)
        {
            vm.Set(ex);
        }

        return(vm);
    }
Exemple #6
0
        public SharedResultVM LsitReplySave(UserReply mo, UserMessage um)
        {
            var vm = new SharedResultVM();

            vm = Apps.LoginService.CompleteInfoValid(HttpContext);
            if (vm.Code == 200)
            {
                if (!mo.Uid.HasValue || string.IsNullOrWhiteSpace(mo.UrContent) || string.IsNullOrWhiteSpace(mo.UrTargetId))
                {
                    vm.Set(SharedEnum.RTag.lack);
                }
                else
                {
                    var uinfo = Apps.LoginService.Get(HttpContext);
                    mo.Uid = uinfo.UserId;

                    var now = DateTime.Now;

                    //回复消息
                    um.UmId         = UniqueTo.LongId().ToString();
                    um.UmTriggerUid = mo.Uid;
                    um.UmType       = Application.EnumService.MessageType.UserWriting.ToString();
                    um.UmTargetId   = mo.UrTargetId;
                    um.UmAction     = 2;
                    um.UmStatus     = 1;
                    um.UmContent    = mo.UrContent;
                    um.UmCreateTime = now;

                    //回复内容
                    mo.UrCreateTime = now;
                    mo.UrStatus     = 1;
                    mo.UrTargetPid  = 0;
                    mo.UrTargetType = Application.EnumService.ReplyType.UserWriting.ToString();

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

                    db.UserReply.Add(mo);

                    //回填文章最新回复记录
                    var mow = db.UserWriting.FirstOrDefault(x => x.UwId.ToString() == mo.UrTargetId);
                    if (mow != null)
                    {
                        mow.UwReplyNum += 1;
                        mow.UwLastUid   = mo.Uid;
                        mow.UwLastDate  = now;

                        um.UmTargetIndex = mow.UwReplyNum;

                        db.UserWriting.Update(mow);
                    }

                    if (um.Uid != um.UmTriggerUid)
                    {
                        db.UserMessage.Add(um);
                    }

                    int num = db.SaveChanges();

                    vm.Set(num > 0);
                }
            }

            return(vm);
        }
Exemple #7
0
        public SharedResultVM WriteSave(UserWriting mo, string TagIds)
        {
            var vm = new SharedResultVM();

            try
            {
                vm = Apps.LoginService.CompleteInfoValid(HttpContext);
                if (vm.Code == 200)
                {
                    var uinfo = Apps.LoginService.Get(HttpContext);

                    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();

                    mo.Uid          = uinfo.UserId;
                    mo.UwCreateTime = DateTime.Now;
                    mo.UwUpdateTime = mo.UwCreateTime;
                    mo.UwLastUid    = mo.Uid;
                    mo.UwLastDate   = mo.UwCreateTime;
                    mo.UwReplyNum   = 0;
                    mo.UwReadNum    = 0;
                    mo.UwOpen       = 1;
                    mo.UwLaud       = 0;
                    mo.UwMark       = 0;
                    mo.UwStatus     = 1;

                    db.UserWriting.Add(mo);
                    db.SaveChanges();

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

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

                    //标签热点+1
                    var listTagId = listwt.Select(x => x.TagId.Value);
                    var listTags  = db.Tags.Where(x => listTagId.Contains(x.TagId)).ToList();
                    listTags.ForEach(x => x.TagHot += 1);
                    db.Tags.UpdateRange(listTags);

                    int num = db.SaveChanges();

                    vm.Data = mo.UwId;
                    vm.Set(num > 0);
                }
            }
            catch (Exception ex)
            {
                ConsoleTo.Log(ex);
                vm.Set(ex);
            }

            return(vm);
        }
Exemple #8
0
        public SharedResultVM Export(QueryDataInputVM ivm, string title = "export")
        {
            var vm = new SharedResultVM();

            //虚拟路径
            string vpath = GlobalTo.GetValue("StaticResource:TmpDir");
            //物理路径
            var ppath = PathTo.Combine(GlobalTo.WebRootPath, vpath);

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

            //文件名
            string filename = $"{title.Replace(" ", "").Trim()}_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";

            //导出的表数据
            var dtReport = new DataTable();

            try
            {
                switch (ivm.TableName?.ToLower())
                {
                default:
                    vm.Set(SharedEnum.RTag.invalid);
                    break;

                //角色
                case "sysrole":
                {
                    using var ctl = new SettingController(db);
                    dtReport      = ExportService.ModelsMapping(ivm, ctl.QuerySysRole(ivm));
                }
                break;

                //用户
                case "sysuser":
                {
                    using var ctl = new SettingController(db);
                    dtReport      = ExportService.ModelsMapping(ivm, ctl.QuerySysUser(ivm));
                }
                break;

                //日志
                case "syslog":
                {
                    using var ctl = new SettingController(db);
                    dtReport      = ExportService.ModelsMapping(ivm, ctl.QuerySysLog(ivm));
                }
                break;

                //字典
                case "sysdictionary":
                {
                    using var ctl = new SettingController(db);
                    dtReport      = ExportService.ModelsMapping(ivm, ctl.QuerySysDictionary(ivm));
                }
                break;
                }

                Console.WriteLine($"Export table rows : {dtReport.Rows.Count}");
                if (vm.Msg != SharedEnum.RTag.invalid.ToString())
                {
                    //生成
                    if (NpoiTo.DataTableToExcel(dtReport, PathTo.Combine(ppath, filename)))
                    {
                        vm.Data = PathTo.Combine(vpath, filename);

                        //生成的Excel继续操作
                        ExportService.ExcelDraw(PathTo.Combine(ppath, filename), ivm);

                        vm.Set(SharedEnum.RTag.success);
                    }
                    else
                    {
                        vm.Set(SharedEnum.RTag.fail);
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
            }

            return(vm);
        }
Exemple #9
0
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="code">分享码</param>
        /// <param name="filename"></param>
        /// <param name="xml"></param>
        /// <param name="mof"></param>
        /// <returns></returns>
        public IActionResult Index(string code, string filename, string xml, Domain.Draw mof)
        {
            var id  = RouteData.Values["id"]?.ToString();
            var sid = RouteData.Values["sid"]?.ToString();

            var kid = string.Empty;

            if (id?.Length == 20)
            {
                kid = id;
            }
            else if (sid?.Length == 20)
            {
                kid = sid;
            }
            if (!string.IsNullOrEmpty(kid))
            {
                var sck = "SharedCode_" + kid;
                //有分享码
                if (!string.IsNullOrWhiteSpace(code))
                {
                    Response.Cookies.Append(sck, code);
                }
                else
                {
                    code = Request.Cookies[sck]?.ToString();
                }
            }

            var uinfo = Apps.LoginService.Get(HttpContext);

            if (!string.IsNullOrWhiteSpace(filename))
            {
                filename = filename.ToUrlDecode();
            }
            if (!string.IsNullOrWhiteSpace(xml))
            {
                xml = xml.ToUrlDecode();
            }

            //新增、编辑
            if (id == "open")
            {
                //编辑
                if (!string.IsNullOrWhiteSpace(sid))
                {
                    var vm = new SharedResultVM();
                    var mo = db.Draw.Find(sid);

                    //分享码
                    var isShare = !string.IsNullOrWhiteSpace(mo?.Spare1) && mo?.Spare1 == code;
                    if (mo?.DrOpen == 1 || mo?.Uid == uinfo.UserId || isShare)
                    {
                        vm.Set(SharedEnum.RTag.success);
                        vm.Data = mo;
                    }
                    else
                    {
                        vm.Set(SharedEnum.RTag.unauthorized);
                    }
                    return(Content(vm.ToJson()));
                }
                return(Ok());
            }
            //新增、编辑表单
            else if (id == "form")
            {
                object model = null;
                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    if (!string.IsNullOrWhiteSpace(sid))
                    {
                        var mo = db.Draw.Find(sid);
                        if (mo.Uid == uinfo.UserId)
                        {
                            model = mo;
                        }
                    }
                }

                return(View("_PartialDrawForm", model));
            }
            //保存标题等信息
            else if (id == "saveform")
            {
                var vm = Apps.LoginService.CompleteInfoValid(HttpContext);
                if (vm.Code == 200)
                {
                    int num = 0;
                    if (string.IsNullOrWhiteSpace(mof.DrId))
                    {
                        mof.DrId         = mof.DrType[0] + Core.UniqueTo.LongId().ToString();
                        mof.DrCreateTime = DateTime.Now;
                        mof.Uid          = uinfo.UserId;
                        mof.DrOrder      = 100;
                        mof.DrStatus     = 1;

                        db.Draw.Add(mof);
                        num = db.SaveChanges();
                    }
                    else
                    {
                        var newmo = db.Draw.Find(mof.DrId);
                        if (newmo.Uid != uinfo.UserId)
                        {
                            vm.Set(SharedEnum.RTag.unauthorized);
                        }
                        else
                        {
                            newmo.DrRemark = mof.DrRemark;
                            newmo.DrName   = mof.DrName;
                            newmo.DrOpen   = mof.DrOpen;
                            newmo.Spare1   = mof.Spare1;

                            db.Draw.Update(newmo);
                            num = db.SaveChanges();
                        }
                    }
                    vm.Set(num > 0);
                }

                if (vm.Code == 200)
                {
                    return(Redirect("/draw/user/" + uinfo?.UserId));
                }
                else
                {
                    return(Content(vm.Msg));
                }
            }
            //保存内容
            else if (id == "save")
            {
                var vm = Apps.LoginService.CompleteInfoValid(HttpContext);
                if (vm.Code == 200)
                {
                    //新增
                    if (string.IsNullOrWhiteSpace(sid))
                    {
                        var mo = new Domain.Draw
                        {
                            DrName    = filename,
                            DrContent = xml,

                            DrId         = mof.DrType[0] + Core.UniqueTo.LongId().ToString(),
                            DrType       = mof.DrType,
                            DrCreateTime = DateTime.Now,
                            DrOpen       = 1,
                            DrOrder      = 100,
                            DrStatus     = 1,
                            Uid          = uinfo.UserId
                        };

                        db.Draw.Add(mo);

                        var num = db.SaveChanges();
                        vm.Set(num > 0);
                        vm.Data = mo.DrId;
                    }
                    else
                    {
                        var mo = db.Draw.Find(sid);
                        if (mo?.Uid == uinfo.UserId)
                        {
                            mo.DrName    = filename;
                            mo.DrContent = xml;

                            db.Draw.Update(mo);

                            var num = db.SaveChanges();
                            vm.Set(num > 0);
                        }
                        else
                        {
                            vm.Set(SharedEnum.RTag.unauthorized);
                        }
                    }
                }

                return(Content(vm.ToJson()));
            }
            //删除
            else if (id == "del")
            {
                var vm = new SharedResultVM();

                if (User.Identity.IsAuthenticated)
                {
                    var mo = db.Draw.Find(sid);
                    if (mo.Uid == uinfo.UserId)
                    {
                        db.Remove(mo);
                        int num = db.SaveChanges();

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

                if (vm.Code == 200)
                {
                    return(Redirect("/draw/discover"));
                }
                else
                {
                    return(Content(vm.ToJson()));
                }
            }
            //插入图片
            else if (id == "upload")
            {
                var errno = -1;
                var msg   = "fail";
                var url   = "";

                var subdir = GlobalTo.GetValue("StaticResource:DrawPath");
                var vm     = new Web.Controllers.api.APIController().Upload(Request.Form.Files[0], subdir);

                if (vm.Code == 200)
                {
                    var jd = vm.Data.ToJson().ToJObject();
                    url   = jd["server"].ToString() + jd["path"].ToString();
                    errno = 0;
                    msg   = "ok";
                }

                return(Content(new
                {
                    errno,
                    msg,
                    data = new
                    {
                        url
                    }
                }.ToJson()));
            }

            ViewData["vid"] = id;

            var vname = string.Format("_Partial{0}View", id.StartsWith('m') ? "Mind" : "Draw");

            return(View(vname));
        }
Exemple #10
0
        public async Task <SharedResultVM> Upload(IFormFileCollection files, int?temp, string subdir)
        {
            var vm = new SharedResultVM();

            try
            {
                if (files.Count > 0)
                {
                    var now = DateTime.Now;

                    //虚拟路径
                    var vpath = GlobalTo.GetValue("StaticResource:RootDir");
                    if (temp == 1)
                    {
                        vpath = GlobalTo.GetValue("StaticResource:TmpDir");
                    }
                    else
                    {
                        vpath = PathTo.Combine(vpath, subdir, now.ToString("yyyy'/'MM'/'dd"));
                    }

                    //物理路径
                    var ppath = PathTo.Combine(GlobalTo.WebRootPath, vpath);
                    if (!Directory.Exists(ppath))
                    {
                        Directory.CreateDirectory(ppath);
                    }

                    var listPath = new List <string>();
                    for (int i = 0; i < files.Count; i++)
                    {
                        var file     = files[i];
                        var ext      = Path.GetExtension(file.FileName);
                        var filename = now.ToString("HHmmss") + RandomTo.NumCode() + ext;

                        using (var stream = new FileStream(PathTo.Combine(ppath, filename), FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }

                        listPath.Add(PathTo.Combine(vpath, filename));
                    }

                    if (listPath.Count == 1)
                    {
                        vm.Data = listPath.FirstOrDefault();
                    }
                    else
                    {
                        vm.Data = listPath;
                    }
                    vm.Set(SharedEnum.RTag.success);
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
            }

            return(vm);
        }
Exemple #11
0
        private static SharedResultVM UploadCheck(IFormFile file, byte[] content, string ext, string subdir)
        {
            var vm = new SharedResultVM();

            if (file != null)
            {
                ext = Path.GetExtension(file.FileName);
            }

            if (string.IsNullOrWhiteSpace(ext) || !ext.Contains('.') || ext.EndsWith("exe"))
            {
                vm.Set(SharedEnum.RTag.refuse);
                vm.Msg = "Invalid extension";
            }
            else
            {
                var    now      = DateTime.Now;
                string filename = now.ToString("HHmmss") + RandomTo.NumCode() + ext;

                if (!string.IsNullOrWhiteSpace(subdir) && !ParsingTo.IsLinkPath(subdir))
                {
                    vm.Set(SharedEnum.RTag.invalid);
                    vm.Msg = "subdir 仅为字母、数字";
                }
                else
                {
                    //虚拟路径
                    var vpath = PathTo.Combine(subdir, now.ToString("yyyy'/'MM'/'dd"));
                    //物理根路径
                    var prp = GlobalTo.GetValue("StaticResource:PhysicalRootPath").Replace("~", GlobalTo.ContentRootPath);
                    //物理路径
                    var ppath = PathTo.Combine(prp, vpath);
                    //创建物理目录
                    if (!Directory.Exists(ppath))
                    {
                        Directory.CreateDirectory(ppath);
                    }

                    using var fs = new FileStream(PathTo.Combine(ppath, filename), FileMode.CreateNew);
                    if (file != null)
                    {
                        file.CopyTo(fs);
                    }
                    else
                    {
                        fs.Write(content, 0, content.Length);
                    }
                    fs.Flush();
                    fs.Close();

                    //输出
                    vm.Data = new
                    {
                        server = GlobalTo.GetValue("StaticResource:Server"),
                        path   = PathTo.Combine(vpath, filename)
                    };
                    vm.Set(SharedEnum.RTag.success);
                }
            }

            return(vm);
        }
Exemple #12
0
        public SharedResultVM DatabaseExportDemo()
        {
            var vm = new SharedResultVM();

            try
            {
                var export_before = "db/backup_demo_before.zip";
                var export_demo   = "db/backup_demo.zip";

                //备份
                if (DatabaseExport(export_before).Code == 200)
                {
                    //清理仅保留示例数据

                    using var db = ContextBaseFactory.CreateDbContext();

                    db.UserInfo.RemoveRange(db.UserInfo.ToList());
                    db.UserInfo.Add(new Domain.UserInfo()
                    {
                        UserId         = 1,
                        UserName       = "******",
                        UserPwd        = "e10adc3949ba59abbe56e057f20f883e",//123456
                        UserCreateTime = DateTime.Now
                    });

                    db.UserConnection.RemoveRange(db.UserConnection.ToList());
                    db.UserMessage.RemoveRange(db.UserMessage.ToList());
                    db.UserReply.RemoveRange(db.UserReply.Where(x => x.UrTargetId != "117").ToList());
                    db.UserWriting.RemoveRange(db.UserWriting.Where(x => x.UwId != 117).ToList());
                    db.UserWritingTags.RemoveRange(db.UserWritingTags.Where(x => x.UwId != 117).ToList());

                    db.Tags.RemoveRange(db.Tags.Where(x => x.TagId != 58 && x.TagId != 96).ToList());

                    db.Run.RemoveRange(db.Run.OrderBy(x => x.RunCreateTime).Skip(1).ToList());

                    db.OperationRecord.RemoveRange(db.OperationRecord.ToList());

                    db.Notepad.RemoveRange(db.Notepad.ToList());

                    db.KeyValues.RemoveRange(db.KeyValues.Where(x => x.KeyName != "https" && x.KeyName != "browser").ToList());
                    db.KeyValueSynonym.RemoveRange(db.KeyValueSynonym.ToList());

                    db.GuffRecord.RemoveRange(db.GuffRecord.ToList());

                    db.Gist.RemoveRange(db.Gist.Where(x => x.GistCode != "5373307231488995367").ToList());
                    db.GistSync.RemoveRange(db.GistSync.Where(x => x.GistCode != "5373307231488995367").ToList());

                    db.GiftRecord.RemoveRange(db.GiftRecord.ToList());
                    db.GiftRecordDetail.RemoveRange(db.GiftRecordDetail.ToList());

                    db.Draw.RemoveRange(db.Draw.Where(x => x.DrId != "d4969500168496794720" && x.DrId != "m4976065893797151245").ToList());

                    db.DocSet.RemoveRange(db.DocSet.Where(x => x.DsCode != "4840050256984581805" && x.DsCode != "5036967707833574483").ToList());
                    db.DocSetDetail.RemoveRange(db.DocSetDetail.Where(x => x.DsCode != "4840050256984581805" && x.DsCode != "5036967707833574483").ToList());

                    var num = db.SaveChanges();

                    //导出示例数据
                    vm = DatabaseExport(export_demo);

                    //导入恢复
                    if (DatabaseImport(export_before, true).Code == 200)
                    {
                        var fullPath = PathTo.Combine(GlobalTo.ContentRootPath, "db", export_before);
                        System.IO.File.Delete(fullPath);
                    }
                }
            }
            catch (Exception ex)
            {
                vm.Set(ex);
            }

            return(vm);
        }
Exemple #13
0
        public SharedResultVM GistSync()
        {
            var vm = new SharedResultVM();

            try
            {
                using var db = ContextBaseFactory.CreateDbContext();

                //同步用户ID
                int UserId = GlobalTo.GetValue <int>("Work:GistSync:UserId");

                //日志
                var listLog = new List <object>()
                {
                    "Gist代码片段同步"
                };

                var listGist = db.Gist.Where(x => x.Uid == UserId).OrderBy(x => x.GistCreateTime).ToList();

                var codes = listGist.Select(x => x.GistCode).ToList();

                var listGs = db.GistSync.Where(x => x.Uid == UserId).ToList();

                //执行命令记录
                var dicSync = new Dictionary <string, string>();

                foreach (var gist in listGist)
                {
                    var gs = listGs.FirstOrDefault(x => x.GistCode == gist.GistCode);
                    //新增
                    if (gs == null)
                    {
                        dicSync.Add(gist.GistCode, "add");
                    }
                    else if (gs?.GsGitHubTime != gist.GistUpdateTime || gs?.GsGiteeTime != gist.GistUpdateTime)
                    {
                        dicSync.Add(gist.GistCode, "update");
                    }
                }

                //删除
                var delCode = listGs.Select(x => x.GistCode).Except(listGist.Select(x => x.GistCode)).ToList();

                var token_gh = GlobalTo.GetValue("ApiKey:GitHub:GistToken");
                var token_ge = GlobalTo.GetValue("ApiKey:Gitee:GistToken");

                listLog.Add("同步新增、修改:" + dicSync.Count + " 条");
                listLog.Add(dicSync);

                //同步新增、修改
                if (dicSync.Count > 0)
                {
                    foreach (var key in dicSync.Keys)
                    {
                        var st   = dicSync[key];
                        var gist = listGist.FirstOrDefault(x => x.GistCode == key);
                        var gs   = listGs.FirstOrDefault(x => x.GistCode == key);

                        #region 发送主体
                        var jo = new JObject
                        {
                            ["access_token"] = token_ge,//only gitee

                            ["description"] = gist.GistRemark,
                            ["public"]      = gist.GistOpen == 1
                        };

                        var jc = new JObject
                        {
                            ["content"] = gist.GistContent
                        };

                        var jf = new JObject
                        {
                            [gist.GistFilename] = jc
                        };

                        jo["files"] = jf;

                        byte[] sendData = Encoding.UTF8.GetBytes(jo.ToJson());
                        #endregion

                        switch (st)
                        {
                        case "add":
                        {
                            var gsmo = new Domain.GistSync()
                            {
                                GistCode     = key,
                                Uid          = UserId,
                                GistFilename = gist.GistFilename
                            };

                            //GitHub
                            {
                                var hwr = HttpTo.HWRequest("https://api.github.com/gists", "POST", sendData);
                                hwr.Headers.Add(HttpRequestHeader.Authorization, "token " + token_gh);
                                hwr.ContentType = "application/json";
                                hwr.UserAgent   = "Netnr Agent";

                                var rt = HttpTo.Url(hwr);

                                gsmo.GsGitHubId   = rt.ToJObject()["id"].ToString();
                                gsmo.GsGitHubTime = gist.GistUpdateTime;
                            }

                            //Gitee
                            {
                                var hwr = HttpTo.HWRequest("https://gitee.com/api/v5/gists", "POST", sendData);
                                hwr.ContentType = "application/json";

                                var rt = HttpTo.Url(hwr);

                                gsmo.GsGiteeId   = rt.ToJObject()["id"].ToString();
                                gsmo.GsGiteeTime = gist.GistUpdateTime;
                            }

                            _ = db.GistSync.Add(gsmo);
                            _ = db.SaveChanges();

                            listLog.Add("新增一条成功");
                            listLog.Add(gsmo);
                        }
                        break;

                        case "update":
                        {
                            if (gs.GistFilename != gist.GistFilename)
                            {
                                jo["files"][gs.GistFilename] = null;
                                gs.GistFilename = gist.GistFilename;
                            }

                            //GitHub
                            {
                                var hwr = HttpTo.HWRequest("https://api.github.com/gists/" + gs.GsGitHubId, "PATCH", sendData);
                                hwr.Headers.Add(HttpRequestHeader.Authorization, "token " + token_gh);
                                hwr.ContentType = "application/json";
                                hwr.UserAgent   = "Netnr Agent";

                                _ = HttpTo.Url(hwr);

                                gs.GsGitHubTime = gist.GistUpdateTime;
                            }

                            //Gitee
                            {
                                var hwr = HttpTo.HWRequest("https://gitee.com/api/v5/gists/" + gs.GsGiteeId, "PATCH", sendData);
                                hwr.ContentType = "application/json";

                                _ = HttpTo.Url(hwr);

                                gs.GsGiteeTime = gist.GistUpdateTime;
                            }

                            _ = db.GistSync.Update(gs);
                            _ = db.SaveChanges();

                            listLog.Add("更新一条成功");
                            listLog.Add(gs);
                        }
                        break;
                        }

                        Thread.Sleep(1000 * 2);
                    }
                }

                listLog.Add("同步删除:" + delCode.Count + " 条");
                listLog.Add(delCode);

                //同步删除
                if (delCode.Count > 0)
                {
                    foreach (var code in delCode)
                    {
                        var gs = listGs.FirstOrDefault(x => x.GistCode == code);

                        var dc = "00".ToCharArray();

                        #region GitHub
                        var hwr_gh = HttpTo.HWRequest("https://api.github.com/gists/" + gs.GsGitHubId, "DELETE");
                        hwr_gh.Headers.Add(HttpRequestHeader.Authorization, "token " + token_gh);
                        hwr_gh.UserAgent = "Netnr Agent";
                        var resp_gh = (HttpWebResponse)hwr_gh.GetResponse();
                        if (resp_gh.StatusCode == HttpStatusCode.NoContent)
                        {
                            dc[0] = '1';
                        }
                        #endregion

                        #region Gitee
                        var hwr_ge  = HttpTo.HWRequest("https://gitee.com/api/v5/gists/" + gs.GsGiteeId + "?access_token=" + token_ge, "DELETE");
                        var resp_ge = (HttpWebResponse)hwr_ge.GetResponse();
                        if (resp_ge.StatusCode == HttpStatusCode.NoContent)
                        {
                            dc[1] = '1';
                        }
                        #endregion

                        if (string.Join("", dc) == "11")
                        {
                            _ = db.GistSync.Remove(gs);
                            _ = db.SaveChanges();

                            listLog.Add("删除一条成功");
                            listLog.Add(gs);
                        }
                        else
                        {
                            listLog.Add("删除一条异常");
                            listLog.Add(dc);
                        }

                        Thread.Sleep(1000 * 2);
                    }
                }

                listLog.Add("完成同步");

                vm.Set(SharedEnum.RTag.success);
                vm.Data = listLog;
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                ConsoleTo.Log(ex);
            }

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

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

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

                    switch (vtype)
                    {
                    case LoginBase.LoginType.QQ:
                    {
                        //获取 access_token
                        var tokenEntity = QQ.AccessToken(new QQ_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //获取 OpendId
                        var openidEntity = QQ.OpenId(tokenEntity.access_token);
                        Console.WriteLine(openidEntity.ToJson());

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

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

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

                        avatar = userEntity.figureurl_2;
                    }
                    break;

                    case LoginBase.LoginType.WeiBo:
                    {
                        //获取 access_token
                        var tokenEntity = Weibo.AccessToken(new Weibo_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //获取 access_token 的授权信息
                        var tokenInfoEntity = Weibo.GetTokenInfo(tokenEntity.access_token);
                        Console.WriteLine(tokenInfoEntity.ToJson());

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

                        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.avatar_large;
                    }
                    break;

                    case LoginBase.LoginType.WeChat:
                    {
                        //获取 access_token
                        var tokenEntity = Netnr.Login.WeChat.AccessToken(new WeChat_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //openId = tokenEntity.openid;

                        //获取 user
                        var userEntity = Netnr.Login.WeChat.Get_User_Info(new WeChat_OpenAPI_RequestEntity()
                            {
                                access_token = tokenEntity.access_token,
                                openid       = tokenEntity.openid
                            });
                        Console.WriteLine(userEntity.ToJson());

                        avatar = userEntity.headimgurl;
                    }
                    break;

                    case LoginBase.LoginType.GitHub:
                    {
                        //获取 access_token
                        var tokenEntity = GitHub.AccessToken(new GitHub_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //获取 user
                        var userEntity = GitHub.User(tokenEntity.access_token);
                        Console.WriteLine(userEntity.ToJson());

                        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;
                    }
                    break;

                    case LoginBase.LoginType.Gitee:
                    {
                        //获取 access_token
                        var tokenEntity = Gitee.AccessToken(new Gitee_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //获取 user
                        var userEntity = Gitee.User(tokenEntity.access_token);
                        Console.WriteLine(userEntity.ToJson());

                        //openId = userEntity.id.ToString();

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

                        avatar = userEntity.avatar_url;
                    }
                    break;

                    case LoginBase.LoginType.TaoBao:
                    {
                        //获取 access_token
                        var tokenEntity = TaoBao.AccessToken(new TaoBao_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

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

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

                    case LoginBase.LoginType.MicroSoft:
                    {
                        //获取 access_token
                        var tokenEntity = MicroSoft.AccessToken(new MicroSoft_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //获取 user
                        var userEntity = MicroSoft.User(tokenEntity.access_token);
                        Console.WriteLine(userEntity.ToJson());

                        openId     = userEntity.id;
                        mo.OpenId5 = openId;

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

                    case LoginBase.LoginType.DingTalk:
                    {
                        //获取 user
                        var userEntity = DingTalk.User(new DingTalk_User_RequestEntity(), authorizeResult.code);
                        Console.WriteLine(userEntity.ToJson());

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

                        mo.Nickname = userEntity.nick;
                    }
                    break;

                    case LoginBase.LoginType.Google:
                    {
                        //获取 access_token
                        var tokenEntity = Google.AccessToken(new Google_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //获取 user
                        var userEntity = Google.User(tokenEntity.access_token);
                        Console.WriteLine(userEntity.ToJson());

                        //openId = userEntity.sub;

                        avatar = userEntity.picture;
                    }
                    break;

                    case LoginBase.LoginType.AliPay:
                    {
                        //获取 access_token
                        var tokenEntity = AliPay.AccessToken(new AliPay_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //openId = tokenEntity.user_id;

                        //获取 user
                        var userEntity = AliPay.User(new AliPay_User_RequestEntity()
                            {
                                auth_token = tokenEntity.access_token
                            });
                        Console.WriteLine(userEntity.ToJson());

                        avatar = userEntity.avatar;
                    }
                    break;

                    case LoginBase.LoginType.StackOverflow:
                    {
                        //获取 access_token
                        var tokenEntity = StackOverflow.AccessToken(new StackOverflow_AccessToken_RequestEntity()
                            {
                                code = authorizeResult.code
                            });
                        Console.WriteLine(tokenEntity.ToJson());

                        //获取 user
                        var userEntity = StackOverflow.User(new StackOverflow_User_RequestEntity()
                            {
                                access_token = tokenEntity.access_token
                            });
                        Console.WriteLine(userEntity.ToJson());

                        //openId= userEntity.user_id;

                        avatar = userEntity.profile_image;
                    }
                    break;
                    }

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

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

                            //检测是否绑定其它账号
                            var queryIsBind = db.UserInfo.Where(x => x.UserId != uid);
                            switch (vtype)
                            {
                            case LoginBase.LoginType.QQ:
                                queryIsBind = queryIsBind.Where(x => x.OpenId1 == openId);
                                break;

                            case LoginBase.LoginType.WeiBo:
                                queryIsBind = queryIsBind.Where(x => x.OpenId2 == openId);
                                break;

                            case LoginBase.LoginType.GitHub:
                                queryIsBind = queryIsBind.Where(x => x.OpenId3 == openId);
                                break;

                            case LoginBase.LoginType.TaoBao:
                                queryIsBind = queryIsBind.Where(x => x.OpenId4 == openId);
                                break;

                            case LoginBase.LoginType.MicroSoft:
                                queryIsBind = queryIsBind.Where(x => x.OpenId5 == openId);
                                break;

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

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

                            switch (vtype)
                            {
                            case LoginBase.LoginType.QQ:
                                userInfo.OpenId1 = openId;
                                break;

                            case LoginBase.LoginType.WeiBo:
                                userInfo.OpenId2 = openId;
                                break;

                            case LoginBase.LoginType.GitHub:
                                userInfo.OpenId3 = openId;
                                break;

                            case LoginBase.LoginType.TaoBao:
                                userInfo.OpenId4 = openId;
                                break;

                            case LoginBase.LoginType.MicroSoft:
                                userInfo.OpenId5 = openId;
                                break;

                            case LoginBase.LoginType.DingTalk:
                                userInfo.OpenId6 = openId;
                                break;
                            }
                            db.UserInfo.Update(userInfo);
                            db.SaveChanges();

                            return(Redirect("/user/setting"));
                        }
                        else
                        {
                            Domain.UserInfo vmo = null;
                            switch (vtype)
                            {
                            case LoginBase.LoginType.QQ:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId1 == openId);
                                break;

                            case LoginBase.LoginType.WeiBo:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId2 == openId);
                                break;

                            case LoginBase.LoginType.GitHub:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId3 == openId);
                                break;

                            case LoginBase.LoginType.TaoBao:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId4 == openId);
                                break;

                            case LoginBase.LoginType.MicroSoft:
                                vmo = db.UserInfo.FirstOrDefault(x => x.OpenId5 == openId);
                                break;

                            case LoginBase.LoginType.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))
                                    {
                                        try
                                        {
                                            //物理根路径
                                            var prp   = GlobalTo.GetValue("StaticResource:PhysicalRootPath").Replace("~", GlobalTo.ContentRootPath);
                                            var ppath = PathTo.Combine(prp, GlobalTo.GetValue("StaticResource:AvatarPath"));

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

                                            HttpTo.DownloadSave(HttpTo.HWRequest(avatar), PathTo.Combine(ppath, mo.UserPhoto));
                                        }
                                        catch (Exception ex)
                                        {
                                            Console.WriteLine(ex);
                                        }
                                    }
                                }
                                else
                                {
                                    vm.Msg = ruvm.Msg;
                                }
                            }
                            else
                            {
                                vm = ValidateLogin(vtype, vmo);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Apps.FilterConfigs.WriteLog(HttpContext, ex);
                Response.Headers["X-Output-Msg"] = ex.ToJson();
                vm.Set(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
            {
                return(Redirect("/home/error"));
            }
        }
Exemple #15
0
        /// <summary>
        /// 公共登录验证
        /// </summary>
        /// <param name="vt">登录类型</param>
        /// <param name="mo">用户信息</param>
        /// <param name="isremember">记住账号</param>
        /// <returns></returns>
        private SharedResultVM ValidateLogin(LoginBase.LoginType?vt, Domain.UserInfo mo, bool isremember = true)
        {
            var vm = new SharedResultVM();

            string sql = string.Empty;

            var uiR = db.UserInfo;

            Domain.UserInfo outMo = new();

            switch (vt)
            {
            case LoginBase.LoginType.QQ:
                outMo = uiR.FirstOrDefault(x => x.OpenId1.Equals(mo.OpenId1));
                break;

            case LoginBase.LoginType.WeiBo:
                outMo = uiR.FirstOrDefault(x => x.OpenId2.Equals(mo.OpenId2));
                break;

            case LoginBase.LoginType.GitHub:
                outMo = uiR.FirstOrDefault(x => x.OpenId3.Equals(mo.OpenId3));
                break;

            case LoginBase.LoginType.TaoBao:
                outMo = uiR.FirstOrDefault(x => x.OpenId4.Equals(mo.OpenId4));
                break;

            case LoginBase.LoginType.MicroSoft:
                outMo = uiR.FirstOrDefault(x => x.OpenId5.Equals(mo.OpenId5));
                break;

            case LoginBase.LoginType.DingTalk:
                outMo = uiR.FirstOrDefault(x => x.OpenId6.Equals(mo.OpenId6));
                break;

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

                    //邮箱登录
                    if (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;
            }

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

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

            try
            {
                //刷新登录标记
                outMo.UserLoginTime = DateTime.Now;
                outMo.UserSign      = outMo.UserLoginTime.Value.ToTimestamp().ToString();
                uiR.Update(outMo);
                db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            try
            {
                //登录标记 缓存5分钟,绝对过期
                if (GlobalTo.GetValue <bool>("Common:SingleSignOn"))
                {
                    var usk = "UserSign_" + outMo.UserId;
                    CacheTo.Set(usk, outMo.UserSign, 5 * 60, false);
                }

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

                //生成Token
                vm.Data = Apps.LoginService.TokenMake(outMo);

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

            return(vm);
        }
Exemple #16
0
        public SharedResultVM Connection(string type, int ac, string id)
        {
            return(SharedResultVM.Try(vm =>
            {
                var uinfo = Apps.LoginService.Get(HttpContext);

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

                    if (currMo == null)
                    {
                        vm.Set(SharedEnum.RTag.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(SharedEnum.RTag.exist);
                                }
                                else
                                {
                                    //关联记录
                                    var ucmo = new Domain.UserConnection()
                                    {
                                        UconnId = 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(SharedEnum.RTag.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;
                        }
                    }
                }

                return vm;
            }));
        }
Exemple #17
0
        public SharedResultVM Update([FromForm] Domain.GuffRecord mo)
        {
            var vm = new SharedResultVM();

            try
            {
                var uinfo = Apps.LoginService.Get(HttpContext);

                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(SharedEnum.RTag.unauthorized);
                }
                else
                {
                    var currMo = db.GuffRecord.Find(mo.GrId);

                    if (currMo == null)
                    {
                        vm.Set(SharedEnum.RTag.invalid);
                    }
                    else if (currMo.Uid != uinfo.UserId)
                    {
                        vm.Set(SharedEnum.RTag.unauthorized);
                    }
                    else
                    {
                        currMo.GrTypeName  = ParsingTo.JsSafeJoin(mo.GrTypeName);
                        currMo.GrTypeValue = ParsingTo.JsSafeJoin(mo.GrTypeValue);
                        currMo.GrObject    = ParsingTo.JsSafeJoin(mo.GrObject);

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

                        currMo.GrImage  = ParsingTo.JsSafeJoin(mo.GrImage);
                        currMo.GrAudio  = ParsingTo.JsSafeJoin(mo.GrAudio);
                        currMo.GrVideo  = ParsingTo.JsSafeJoin(mo.GrVideo);
                        currMo.GrFile   = 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);
                Apps.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemple #18
0
        public SharedResultVM Add([FromForm] Domain.GuffRecord mo)
        {
            var vm = new SharedResultVM();

            try
            {
                var uinfo = Apps.LoginService.Get(HttpContext);

                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(SharedEnum.RTag.unauthorized);
                }
                else
                {
                    vm = Apps.LoginService.CompleteInfoValid(HttpContext);
                    if (vm.Code == 200)
                    {
                        var now = DateTime.Now;

                        mo.Uid          = uinfo.UserId;
                        mo.GrId         = 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  = ParsingTo.JsSafeJoin(mo.GrTypeName);
                        mo.GrTypeValue = ParsingTo.JsSafeJoin(mo.GrTypeValue);
                        mo.GrObject    = ParsingTo.JsSafeJoin(mo.GrObject);
                        mo.GrImage     = ParsingTo.JsSafeJoin(mo.GrImage);
                        mo.GrAudio     = ParsingTo.JsSafeJoin(mo.GrAudio);
                        mo.GrVideo     = ParsingTo.JsSafeJoin(mo.GrVideo);
                        mo.GrFile      = ParsingTo.JsSafeJoin(mo.GrFile);
                        mo.GrTag       = 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);
                Apps.FilterConfigs.WriteLog(HttpContext, ex);
            }

            return(vm);
        }
Exemple #19
0
        public async Task <SharedResultVM> LoginValidation(SysUser mo, string captcha, int remember)
        {
            var vm = new SharedResultVM();

            var outMo = new SysUser();

            //跳过验证码
            if (captcha == "_pass_")
            {
                outMo = mo;
            }
            else
            {
                var capt = HttpContext.Session.GetString("captcha");
                HttpContext.Session.Remove("captcha");

                if (string.IsNullOrWhiteSpace(captcha) || (capt ?? "") != Core.CalcTo.MD5(captcha.ToLower()))
                {
                    vm.Set(SharedEnum.RTag.fail);
                    vm.Msg = "验证码错误或已过期";
                    return(vm);
                }

                if (string.IsNullOrWhiteSpace(mo.SuName) || string.IsNullOrWhiteSpace(mo.SuPwd))
                {
                    vm.Set(SharedEnum.RTag.lack);
                    vm.Msg = "用户名或密码不能为空";
                    return(vm);
                }

                outMo = db.SysUser.FirstOrDefault(x => x.SuName == mo.SuName && x.SuPwd == Core.CalcTo.MD5(mo.SuPwd, 32));
            }

            if (outMo == null || string.IsNullOrWhiteSpace(outMo.SuId))
            {
                vm.Set(SharedEnum.RTag.unauthorized);
                vm.Msg = "用户名或密码错误";
                return(vm);
            }

            if (outMo.SuStatus != 1)
            {
                vm.Set(SharedEnum.RTag.refuse);
                vm.Msg = "用户已被禁止登录";
                return(vm);
            }

            try
            {
                #region 授权访问信息

                //登录信息
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.PrimarySid, outMo.SuId));
                identity.AddClaim(new Claim(ClaimTypes.Name, outMo.SuName));
                identity.AddClaim(new Claim(ClaimTypes.GivenName, outMo.SuNickname ?? ""));
                identity.AddClaim(new Claim(ClaimTypes.Role, outMo.SrId));

                //配置
                var authParam = new AuthenticationProperties();
                if (remember == 1)
                {
                    authParam.IsPersistent = true;
                    authParam.ExpiresUtc   = DateTime.Now.AddDays(10);
                }

                //写入
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authParam);

                vm.Set(SharedEnum.RTag.success);
                vm.Data = "/";

                return(vm);

                #endregion
            }
            catch (Exception ex)
            {
                vm.Set(ex);
                return(vm);
            }
        }
Exemple #20
0
        public SharedResultVM DatabaseBackupToGit()
        {
            return(SharedResultVM.Try(vm =>
            {
                if (GlobalTo.GetValue <bool>("ReadOnly"))
                {
                    vm.Set(SharedEnum.RTag.refuse);
                    return vm;
                }

                var now = $"{DateTime.Now:yyyyMMdd_HHmmss}";

                var db = ContextBaseFactory.CreateDbContext();
                var database = db.Database.GetDbConnection().Database;

                var createScript = db.Database.GenerateCreateScript();

                //备份创建脚本
                try
                {
                    var b1 = Convert.ToBase64String(Encoding.UTF8.GetBytes(createScript));
                    var p1 = $"{database}/backup_{now}.sql";

                    vm.Log.Add(PutGitee(b1, p1, now));
                    vm.Log.Add(PutGitHub(b1, p1, now));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    vm.Log.Add(ex.Message);
                }

                Thread.Sleep(1000 * 1);

                //备份数据
                var zipPath = $"db/backup_{now}.zip";
                if (DatabaseExport(zipPath).Code == 200)
                {
                    var ppath = PathTo.Combine(GlobalTo.ContentRootPath, zipPath);

                    try
                    {
                        var b2 = Convert.ToBase64String(System.IO.File.ReadAllBytes(ppath));
                        var p2 = $"{database}/backup_{now}.zip";

                        vm.Log.Add(PutGitee(b2, p2, now));
                        vm.Log.Add(PutGitHub(b2, p2, now));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        vm.Log.Add(ex.Message);

                        System.IO.File.Delete(ppath);
                    }
                    finally
                    {
                        System.IO.File.Delete(ppath);
                    }
                }

                return vm;
            }));
        }