예제 #1
0
        public async Task <CheckResult> CheckProblemAsync(int probid, ClaimsPrincipal user)
        {
            int cid    = Contest.Id;
            int?userId = user.IsInRole("Administrator") ? default(int?) : int.Parse(user.GetUserId() ?? "-110");

            if (await Db.ContestProblems.Where(cp => cp.ContestId == cid && cp.ProblemId == probid).AnyAsync())
            {
                return(CheckResult.Fail("Problem has been added."));
            }

            IQueryable <Problem> query;

            if (userId == null)
            {
                query = Db.Problems
                        .Where(p => p.Id == probid);
            }
            else
            {
                query = Db.ProblemAuthors
                        .Where(pa => pa.ProblemId == probid && pa.UserId == userId)
                        .Join(Db.Problems, pa => pa.ProblemId, p => p.Id, (pa, p) => p);
            }

            var prob = await query.FirstOrDefaultAsync();

            if (prob == null)
            {
                return(CheckResult.Fail("Problem not found or access denined."));
            }

            return(CheckResult.Succeed(prob.Title));
        }
예제 #2
0
        private CheckResult CheckRequest(string userId, string passWord, string signature, string timestamp,
                                         string nonce, Guid appid)
        {
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(passWord))
            {
                return(CheckResult.Fail("用户名或密码为空"));
            }

            if (string.IsNullOrEmpty(signature))
            {
                return(CheckResult.Fail("请求签名为空"));
            }

            if (string.IsNullOrEmpty(timestamp))
            {
                return(CheckResult.Fail("时间戳为空"));
            }

            if (string.IsNullOrEmpty(nonce))
            {
                return(CheckResult.Fail("随机数为空"));
            }

            if (appid == Guid.Empty)
            {
                return(CheckResult.Fail("应用接入ID非法"));
            }

            return(CheckResult.Success());
        }
예제 #3
0
        private CheckResult <string> CheckedFileParamter(HttpPostedFile postFile)
        {
            if (postFile == null && postFile.ContentLength == 0)
            {
                return(CheckResult <string> .Fail("没有文件"));
            }

            //文件名
            string _fileName = uploadFileSetting.IsUseOldFileName ? postFile.FileName : DateTime.Now.FormatDate(12) + Path.GetExtension(postFile.FileName);
            //验证格式
            CheckResult <string> _checkFileTypeResult = CheckingType(postFile.FileName);

            if (!_checkFileTypeResult.State)
            {
                return(_checkFileTypeResult);
            }

            //验证大小
            CheckResult <string> _checkFileSizeResult = CheckSize(postFile);

            if (!_checkFileSizeResult.State)
            {
                return(_checkFileSizeResult);
            }

            return(CheckResult <string> .Success(_fileName));
        }
예제 #4
0
        /// <summary>
        ///     检查请求签名合法性
        /// </summary>
        /// <param name="signature">加密签名字符串</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <param name="appConfig">应用接入配置信息</param>
        /// <returns>CheckResult</returns>
        public CheckResult CheckRequestSignature(string signature, string timestamp, string nonce, AppConfig appConfig)
        {
            ValidateOperator.Begin()
            .NotNullOrEmpty(signature, "加密签名字符串")
            .NotNullOrEmpty(timestamp, "时间戳")
            .NotNullOrEmpty(nonce, "随机数")
            .NotNull(appConfig, "AppConfig");
            var appSecret        = appConfig.AppSecret;
            var signatureExpired = appConfig.SignatureExpiredMinutes;

            string[] data = { appSecret, timestamp, nonce };
            Array.Sort(data);
            var signatureText = string.Join("", data);

            signatureText = Md5Encryptor.Encrypt(signatureText);

            if (!signature.CompareIgnoreCase(signatureText) && CheckHelper.IsNumber(timestamp))
            {
                return(CheckResult.Success());
            }
            var timestampMillis =
                UnixEpochHelper.DateTimeFromUnixTimestampMillis(timestamp.ToDoubleOrDefault());
            var minutes = DateTime.UtcNow.Subtract(timestampMillis).TotalMinutes;

            return(minutes > signatureExpired?CheckResult.Fail("签名时间戳失效") : CheckResult.Success());
        }
예제 #5
0
 private CheckResult CheckRequest(string token, Guid appid)
 {
     if (string.IsNullOrEmpty(token))
     {
         return(CheckResult.Fail("用户令牌为空"));
     }
     return(Guid.Empty == appid?CheckResult.Fail("应用ID非法") : CheckResult.Success());
 }
예제 #6
0
        /// <summary>
        ///     根据appId获取请求通道配置信息
        /// </summary>
        /// <param name="appid">appId</param>
        /// <returns>AppConfig</returns>
        public CheckResult <AppConfig> Get(Guid appid)
        {
            var appConfig = _configContext.Get <AppConfig>(appid.ToString());

            return(appConfig != null
                ? CheckResult <AppConfig> .Success(appConfig)
                : CheckResult <AppConfig> .Fail($"{appid}配置参数缺失."));
        }
예제 #7
0
 protected override CheckResult <IdentityUser> GetIdentityUser(string userId, string passWord)
 {
     if (userId == "2c96ff542072420bc8d33bdd73bb9488" && passWord == "0000")
     {
         return(CheckResult <IdentityUser> .Success(new IdentityUser
                                                    { UserId = userId.ToGuidOrDefault(Guid.Empty), Password = passWord }));
     }
     return(CheckResult <IdentityUser> .Fail("用户名称或密码错误。"));
 }
예제 #8
0
        /// <summary>
        /// 检查文件大小
        /// </summary>
        /// <param name="postFile">HttpPostedFile</param>
        private CheckResult <string> CheckSize(HttpPostedFile postFile)
        {
            if (postFile.ContentLength / 1024.0 / 1024.0 > uploadFileSetting.MaxSizeM)
            {
                return(CheckResult <string> .Fail(string.Format("对不起上传文件过大,不能超过{0}M!", uploadFileSetting.MaxSizeM)));
            }

            return(CheckResult <string> .Success());
        }
예제 #9
0
        private CheckResult CheckedPostFile(HttpPostedFile postedFile)
        {
            if (postedFile == null && postedFile.ContentLength == 0)
            {
                return(CheckResult.Fail(GetCodeMessage(4)));
            }

            return(CheckResult.Success());
        }
예제 #10
0
        /// <summary>
        /// 判断请求图片的缓存是否存在
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <returns>是否存在</returns>
        private CheckResult CheckedRequestImageCache(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]))
            {
                context.Response.StatusCode        = 304;
                context.Response.StatusDescription = "Not Modified";
                return(CheckResult.Success());
            }

            return(CheckResult.Fail(null));
        }
예제 #11
0
 private CheckResult CheckedValidateTokenParamter(string token, Guid appid)
 {
     if (string.IsNullOrEmpty(token))
     {
         return(CheckResult.Fail("用户令牌为空"));
     }
     if (Guid.Empty == appid)
     {
         return(CheckResult.Fail("应用ID非法"));
     }
     return(CheckResult.Success());
 }
예제 #12
0
        private static CheckResult CheckedFileDownloadParamter(string fileName, string filePhysicsPath)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(CheckResult.Fail("下载文件名称不能为空。"));
            }

            if (!CheckHelper.IsFilePath(filePhysicsPath) || !File.Exists(filePhysicsPath))
            {
                return(CheckResult.Fail("下载文件路径不合法或者文件不实际存在。"));
            }

            return(CheckResult.Success());
        }
예제 #13
0
        private CheckResult CheckedUploadImageParamter(string fileEx, double fileSize)
        {
            if (!FileHelper.CheckValidExt(SetAllowFormat, fileEx))
            {
                return(CheckResult.Fail(GetCodeMessage(2)));
            }

            if (fileSize > SetAllowSize)
            {
                return(CheckResult.Fail(GetCodeMessage(3)));
            }

            return(CheckResult.Success());
        }
예제 #14
0
        /// <summary>
        /// 检查图片参数,1.是否是合法路径,2.是否物理存在,3.是否是图片后缀
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <param name="checkedFileExist">是否检查物理存在</param>
        /// <returns>检验是否合法</returns>
        private static CheckResult CheckedImageParamter(string imagePath, bool checkedFileExist)
        {
            if (!CheckHelper.IsFilePath(imagePath))
            {
                return(CheckResult.Fail(string.Format("{0}是非法路径。", imagePath)));
            }
            if (checkedFileExist && !File.Exists(imagePath))
            {
                return(CheckResult.Fail(string.Format("{0}并非实际存在。", imagePath)));
            }
            string _imageExt = FileHelper.GetFileEx(imagePath);

            if (!FileHelper.CheckValidExt(ImageHelper.AllowExt, _imageExt))
            {
                return(CheckResult.Fail(string.Format("{0}并非图片格式,目前支持的图片格式:{1}。", imagePath, ImageHelper.AllowExt)));
            }
            return(CheckResult.Success());
        }
예제 #15
0
        /// <summary>
        /// 验证文件类型
        /// </summary>
        /// <param name="fileName">文件名称.</param>
        private CheckResult <string> CheckingType(string fileName)
        {
            if (uploadFileSetting.FileType != "*")
            {
                // 获取允许允许上传类型列表
                string[] _typeList = uploadFileSetting.FileType.Split(',');
                // 获取上传文件类型(小写)
                string _type = Path.GetExtension(fileName).ToLowerInvariant();

                // 验证类型
                if (_typeList.Contains(_type) == false)
                {
                    return(CheckResult <string> .Fail("文件类型非法"));
                }
            }

            return(CheckResult <string> .Success());
        }
예제 #16
0
        /// <summary>
        /// 检查上传文件是否合法
        /// </summary>
        /// <param name="fileBuffer">文件流</param>
        /// <param name="fileExt">文件后缀</param>
        /// <returns>是否合法</returns>
        private CheckResult CheckedUploadFile(byte[] fileBuffer, string fileExt)
        {
            if (fileBuffer.Length == 0)
            {
                return(CheckResult.Fail("无数据提交"));
            }

            if (fileBuffer.Length > this.MaxFilesize)
            {
                return(CheckResult.Fail("文件大小超过" + this.MaxFilesize + "字节"));
            }

            if (!AllowExt.Contains(fileExt))
            {
                return(CheckResult.Fail("上传文件扩展名必需为:" + string.Join(",", AllowExt)));
            }

            return(CheckResult.Success());
        }
예제 #17
0
        /// <summary>
        /// 验证WebApi签名
        /// </summary>
        /// <param name="signature">签名</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <param name="appSecret">签名加密键</param>
        /// <param name="signatureExpiredMinutes">签名过期分钟</param>
        /// <returns>CheckResult</returns>
        internal static CheckResult Validate(string signature, string timestamp, string nonce, string appSecret, int signatureExpiredMinutes)
        {
            string[] _arrayParamter = { appSecret, timestamp, nonce };
            Array.Sort(_arrayParamter);
            string _signatureString = string.Join("", _arrayParamter);

            _signatureString = MD5Encryptor.Encrypt(_signatureString);

            if (signature.CompareIgnoreCase(signature) && CheckHelper.IsNumber(timestamp))
            {
                DateTime _timestampMillis =
                    UnixEpochHelper.DateTimeFromUnixTimestampMillis(timestamp.ToDoubleOrDefault(0f));
                double _minutes = DateTime.UtcNow.Subtract(_timestampMillis).TotalMinutes;

                if (_minutes > signatureExpiredMinutes)
                {
                    return(CheckResult.Fail("签名时间戳失效"));
                }
            }

            return(CheckResult.Success());
        }
예제 #18
0
        async Task <CheckResult <Rejudging> > IRejudgingContext.SystemTestAsync(int uid)
        {
            if (Contest.GetState() < Entities.ContestState.Ended)
            {
                return(CheckResult <Rejudging> .Fail("Contest should be ended first."));
            }

            if (Contest.Settings.SystemTestRejudgingId != null)
            {
                var rej = await Polygon.Rejudgings.FindAsync(Contest.Id, Contest.Settings.SystemTestRejudgingId.Value);

                return(rej != null
                    ? CheckResult <Rejudging> .Succeed(rej)
                    : CheckResult <Rejudging> .Fail($"Rejudging {Contest.Settings.SystemTestRejudgingId.Value} not found."));
            }

            if (await Polygon.Rejudgings.CountUndoneAsync(Contest.Id) != 0)
            {
                return(CheckResult <Rejudging> .Fail("There's pending rejudgings."));
            }

            var rejudging = new Rejudging
            {
                ContestId  = Contest.Id,
                Reason     = "System Test",
                StartTime  = DateTimeOffset.Now,
                EndTime    = DateTimeOffset.Now,
                IssuedBy   = uid,
                OperatedBy = uid,
                Applied    = true,
            };

            rejudging = await Polygon.Rejudgings.CreateAsync(rejudging);

            var settings = Contest.Settings.Clone();

            settings.SystemTestRejudgingId = rejudging.Id;
            var settingsJson = settings.ToJson();

            await UpdateContestAsync(c => new Entities.Contest {
                SettingsJson = settingsJson
            });

            var startTime = Contest.StartTime !.Value;
            var endTime   = (Contest.StartTime + Contest.EndTime) !.Value;
            int count     = await Polygon.Rejudgings.BatchRejudgeAsync(
                (s, j) => j.Status == Verdict.Accepted && s.Time >= startTime && s.Time <= endTime,
                rejudging, immediateApply : true, stageAsRunning : true);

            if (count == 0)
            {
                await Polygon.Rejudgings.DeleteAsync(rejudging);

                return(CheckResult <Rejudging> .Fail("There's no accepted submissions in this contest."));
            }

            await Mediator.Publish(new Events.ScoreboardRefreshEvent(this));

            await Db.Judgings
            .Where(j => j.RejudgingId == rejudging.Id)
            .BatchUpdateAsync(j => new Judging {
                Status = Verdict.Pending
            });

            return(CheckResult <Rejudging> .Succeed(rejudging));
        }