/// <summary> /// 检查挑战是否过期 /// </summary> /// <param name="expirationSecond"></param> /// <returns></returns> public bool VerifyTime(int expirationSecond) { long now = UnixTimeUtil.GetTimeStampInInt32(); var span = now - this.UinxTime; return(span <= expirationSecond); }
protected bool CheckVerifyCode(string captcha, out string message) { string verifyCode = HttpContext.Session.GetString("VerifyCode"); int time = HttpContext.Session.GetInt32("VerifyCodeTime").GetValueOrDefault(0); int valid = HttpContext.Session.GetInt32("VerifyCodeValid").GetValueOrDefault(0); if (valid != 1 || !UnixTimeUtil.IsValid(time, 60))//验证码的保质期是60秒 { message = "验证码过期或失效"; return(false); } //销毁验证码的标志 HttpContext.Session.SetInt32("VerifyCodeValid", 0); if (string.IsNullOrEmpty(verifyCode) || string.IsNullOrEmpty(captcha)) { message = "错误参数"; return(false); } else { if (captcha.Equals("0") || !captcha.ToLower().Equals(verifyCode)) { message = "验证码错误"; return(false); } } message = ""; return(true); }
public IActionResult VerifyCode() { Response.ContentType = "image/jpeg"; var buffer = captchaGenerator.GenerateImage(out var code); //存session HttpContext.Session.SetString("VerifyCode", code.ToLower()); //使用标志,不允许重复使用一个验证码。 //这个验证码被消费一次后,要置0。 HttpContext.Session.SetInt32("VerifyCodeValid", 1); //验证码生成时间。 HttpContext.Session.SetInt32("VerifyCodeTime", UnixTimeUtil.GetTimeStampInInt32()); //string sessionID = Request.Cookies["SessionID"]; //RedisManager.SetString(sessionID, code); // Response.Cookies.Append("code",code); // 将验证码的token放入cookie // Response.Cookies.Append(VERFIY_CODE_TOKEN_COOKIE_NAME, await SecurityServices.GetVerifyCodeToken(code)); return(File(buffer, "image/png")); }
/// <summary> /// 接口:actionMethod/ /// 查询参数:keyValues/ /// 请求方式:Method 默认GET/ /// 请求数据:Method为POST时,json必填/ /// 是否特定的HTTP头(platform=offline): isplatform 默认false; /// </summary> private string RequestSnd(string actionMethod, Dictionary <string, string> keyValues, Method method = Method.GET, string json = null, bool isplatform = false) { var time = UnixTimeUtil.DtToUnix(DateTime.Now, 2).ToString(); var sSign = GetSign(keyValues, time); var client = new RestClient(Config.Host); var request = new RestRequest(method); foreach (var item in keyValues) { request.AddQueryParameter(item.Key, item.Value); } if (isplatform) { request.AddHeader("platform", "offline"); } request.AddHeader("Gateway-Authid", Config.AppId); request.AddHeader("Gateway-Request-Time", time); request.AddHeader("Gateway-Sign", sSign); request.AddHeader("Gateway-Action-Method", actionMethod); request.AddHeader("Gateway-Access-Token", Config.AccessToken); if (Method.POST == method || method == Method.PUT) { request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", json, ParameterType.RequestBody); } IRestResponse response = client.Execute(request); return(response.Content); }
private async Task InsertLogAsync(string url) { var headers = Request.Headers; StringBuilder stringBuilder = new StringBuilder(); foreach (var item in headers) { stringBuilder.Append(item.Key + "---" + item.Value + "\r\n"); } string RealIP = headers["X-Forwarded-For"].ToString().Split(",")[0]; AccessRecords accessRecords = new AccessRecords() { AccessId = idGenerator.NextId(), IP = RealIP, X_Real_IP = headers["X-Real-IP"], X_Forwarded_For = headers["X-Forwarded-For"], Referrer = headers["Referer"], RequestHeader = stringBuilder.ToString(), AccessTime = DateTime.Now, UnixTime = UnixTimeUtil.GetTimeStampInLong(), TimeInterval = -1, URL = url }; await accessService.InsertAccessAsync(accessRecords).ConfigureAwait(false); }
public IActionResult PutTestingContent(string what) { //http://joplin.morenote.top/api/items/root:/testing.txt:/content //what=testing.txt:/content var response = new PutContextResponseDto() { name = "testing.txt", id = "{AC66705E-090C-4AE6-8933-77A7BAC256E8}", created_time = UnixTimeUtil.GetUnixTimeMillisecondsInLong(), updated_time = UnixTimeUtil.GetUnixTimeMillisecondsInLong() }; return(Json(response, MyJsonConvert.GetLeanoteOptions())); }
public IActionResult UploadUPyun() { var webConfig = configFileService.WebConfig; var options = new UPYunOSSOptions(); options.bucket = webConfig.UpyunConfig.UpyunBucket; options.save_key = "/{year}/{mon}/{day}/{filemd5}{.suffix}"; options.expiration = UnixTimeUtil.GetTimeStampInInt32() + 60; var policy = UpYunOSS.GetPolicy(options); var signature = UpYunOSS.GetSignature(policy, webConfig.UpyunConfig.FormApiSecret); ViewBag.bucket = webConfig.UpyunConfig.UpyunBucket; ViewBag.policy = policy; ViewBag.signature = signature; return(View()); }
public ServerChallenge GenServerChallenge(string tag, string requestNumber, long?userId) { //随机数 var random = RandomTool.CreatSafeRandomBase64(32); var challenge = new ServerChallenge() { Id = this.idGenerator.NextId(), UserId = userId, Tag = tag, RequestNumber = requestNumber, Random = random, UinxTime = UnixTimeUtil.GetTimeStampInInt32() }; SaveServerChallenge(challenge); return(challenge); }
public IEnumerable <ConditionItem> Transform(ConditionItem item, Type type) { if (item == null) { throw new ArgumentNullException("item"); } DateTime willTime; if (DateTime.TryParse(item.Value.ToString(), out willTime)) { var method = item.Method; if (method == QueryMethod.LessThan || method == QueryMethod.LessThanOrEqual) { method = QueryMethod.DateTimeLessThanOrEqual; if (willTime.Hour == 0 && willTime.Minute == 0 && willTime.Second == 0) { willTime = willTime.AddDays(1).AddMilliseconds(-1); } } object value = null; if (type == typeof(DateTime) || type == typeof(DateTime?)) { value = willTime; } else if (type == typeof(int) || type == typeof(int?)) { value = (int)UnixTimeUtil.FromDateTime(willTime); } else if (type == typeof(long) || type == typeof(Guid?)) { value = UnixTimeUtil.FromDateTime(willTime); } return(new[] { new ConditionItem(item.Field, method, value) }); } return(new[] { new ConditionItem(item.Field, item.Method, Convert.ChangeType(item.Value, type, CultureInfo.CurrentCulture)) }); }
public JWT GetJWT(long?tokenId, string userNmae, long?userId, string group, long?exp = 31536000) { JWT_Header header = new JWT_Header() { alg = "SHA1" }; JWT_Payload payload = new JWT_Payload { tokenId = tokenId, iss = "localhost", username = userNmae, userId = userId, group = group, startTime = UnixTimeUtil.GetTimeStampInLong(), exp = exp, random = RandomTool.CreatSafeRandomBase64(8) }; StringBuilder message = new StringBuilder(); message.Append(header.alg); message.Append(payload.tokenId); message.Append(payload.iss); message.Append(payload.username); message.Append(payload.userId); message.Append(payload.group); message.Append(payload.startTime); message.Append(payload.exp); message.Append(payload.random); string password = ""; string signature = SHAEncryptHelper.Hash1Encrypt(message + password); JWT jWT = new JWT() { Header = header, Payload = payload, Signature = signature }; return(jWT); }
public JsonResult GetSyncState(string token) { User user = tokenSerivce.GetUserByToken(token); if (user == null) { ApiRe apiRe = new ApiRe() { Ok = false, Msg = "NOTLOGIN", }; return(Json(apiRe, MyJsonConvert.GetLeanoteOptions())); } ApiGetSyncState apiGetSyncState = new ApiGetSyncState() { LastSyncUsn = user.Usn, LastSyncTime = UnixTimeUtil.GetTimeStampInLong(DateTime.Now) }; return(Json(apiGetSyncState, MyJsonConvert.GetSimpleOptions())); }
public IActionResult DoInstall(string captcha, string config) { WebSiteConfig localWebSiteConfig = configFileService.WebConfig; string path = RuntimeEnvironment.IsWindows?@"C:\morenote\WebSiteConfig.json":"/morenote/WebSiteConfig.json"; if (localWebSiteConfig != null && localWebSiteConfig.IsAlreadyInstalled) { ResponseMessage re = new ResponseMessage() { Ok = false, Msg = $"请设置{path}的IsAlreadyInstalled变量为false" }; return(Json(re, MyJsonConvert.GetSimpleOptions())); } string verifyCode = HttpContext.Session.GetString("VerifyCode"); int? verifyCodeValid = HttpContext.Session.GetInt32("VerifyCodeValid"); int time = HttpContext.Session.GetInt32("VerifyCodeTime").GetValueOrDefault(0); int valid = HttpContext.Session.GetInt32("VerifyCodeValid").GetValueOrDefault(0); if (valid != 1 || !UnixTimeUtil.IsValid(time, 2000)) { ResponseMessage re = new ResponseMessage() { Ok = false, Msg = "验证码过期或失效" }; return(Json(re, MyJsonConvert.GetSimpleOptions())); } //销毁验证码的标志 HttpContext.Session.SetInt32("VerifyCodeValid", 0); if (string.IsNullOrEmpty(verifyCode) || string.IsNullOrEmpty(captcha) || verifyCodeValid == null || verifyCodeValid == 0) { ResponseMessage re = new ResponseMessage() { Ok = false, Msg = "错误参数" }; return(Json(re, MyJsonConvert.GetSimpleOptions())); } else { ResponseMessage re = new ResponseMessage() { Ok = true }; WebSiteConfig webSiteConfig = JsonSerializer.Deserialize <WebSiteConfig>(config); //检查配置文件 if (webSiteConfig.PostgreSql == null) { re = new ResponseMessage() { Ok = false, Msg = "PostgreSql错误参数" }; return(Json(re, MyJsonConvert.GetSimpleOptions())); } configFileService.Save(webSiteConfig, ConfigFileService.GetConfigPath()); //登录成功 re = new ResponseMessage() { Ok = true }; return(Json(re, MyJsonConvert.GetSimpleOptions())); } }