Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="email">注册者的电子邮件</param>
        /// <param name="pwd">注册者的口令</param>
        /// <param name="iu"></param>
        /// <returns></returns>
        public async Task <JsonResult> DoRegister(string email, string pwd, string iu, string captcha)
        {
            if (!configFileService.WebConfig.SecurityConfig.OpenRegister)
            {
                return(Json(new ApiRe()
                {
                    Ok = false,
                    Msg = "管理员已经将注册功能关闭"
                }, MyJsonConvert.GetSimpleOptions()));
            }
            string errorMessage = string.Empty;
            bool   result       = await authService.Register(email, pwd, iu.ToLongByHex());

            if (result)
            {
                return(Json(new ApiRe()
                {
                    Ok = true,
                    Msg = "Success"
                }, MyJsonConvert.GetSimpleOptions()));
            }
            else
            {
                return(Json(new ApiRe()
                {
                    Ok = false,
                    Msg = $"注册失败:{errorMessage}"
                }, MyJsonConvert.GetSimpleOptions()));
            }
        }
Exemplo n.º 2
0
        public JsonResult DoRegister(string email, string pwd, string iu)
        {
            if (!ConfigService.IsOpenRegister())
            {
                return(Json(new ApiRe()
                {
                    Ok = false,
                    Msg = "管理员已经将注册功能关闭"
                }, MyJsonConvert.GetSimpleOptions()));
            }
            bool result = AuthService.Register(email, pwd, MyConvert.HexToLong(iu));

            if (result)
            {
                return(Json(new ApiRe()
                {
                    Ok = true,
                    Msg = "Success"
                }, MyJsonConvert.GetSimpleOptions()));
            }
            else
            {
                return(Json(new ApiRe()
                {
                    Ok = false,
                    Msg = "注册失败"
                }, MyJsonConvert.GetSimpleOptions()));
            }
        }
Exemplo n.º 3
0
        public JsonResult MakeCredentialOptions(string token, string authType)
        {
            var tokenVerify = tokenSerivce.VerifyToken(token);

            if (!tokenVerify)
            {
                var apiRe = new ApiRe()
                {
                    Ok  = false,
                    Msg = "注册失败,token无效"
                };
                return(Json(apiRe, MyJsonConvert.GetSimpleOptions()));
            }
            var user = userService.GetUserByToken(token);

            var attachment = AuthenticatorAttachment.Platform;
            var ok         = Enum.TryParse <AuthenticatorAttachment>(authType, true, out attachment);

            //注册选项
            var opts = new MakeCredentialParams(user.Username, user.UserId);

            if (ok)
            {
                opts.AuthenticatorSelection.AuthenticatorAttachment = attachment;
            }
            var credentialCreateOptions = fido2Service.MakeCredentialOptions(user, opts);

            return(Json(credentialCreateOptions));
        }
Exemplo n.º 4
0
        /// <summary>
        /// 登陆
        ///  成功返回 {Ok: true, Item: token }
        ///  失败返回 {Ok: false, Msg: ""}
        /// </summary>
        /// <param name="email"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        //[HttpPost]
        public JsonResult Login(string email, string pwd)
        {
            string tokenStr = "";
            User   user;

            if (AuthService.LoginByPWD(email, pwd, out tokenStr, out user))
            {
                SetUserIdToSession(user.UserId);
                AuthOk authOk = new AuthOk()
                {
                    Ok       = true,
                    Token    = tokenStr,
                    UserId   = user.UserId.ToString("x"),
                    Email    = user.Email,
                    Username = user.Username
                };
                return(Json(authOk, MyJsonConvert.GetSimpleOptions()));
            }
            else
            {
                ApiRe apiRe = new ApiRe()
                {
                    Ok  = false,
                    Msg = "用户名或密码有误"
                };
                string json = JsonSerializer.Serialize(apiRe, MyJsonConvert.GetSimpleOptions());
                return(Json(apiRe, MyJsonConvert.GetSimpleOptions()));
            }
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Register(string email, string pwd)
        {
            //ex:API当前不使用cookie和session判断用户身份,
            //API调用必须显式的提供token字段,以证明身份
            //API调用者必须是管理员身份或者超级管理员身份,否则调用无效
            //如果用户设置二次验证必须显示提供二次验证码
            ApiRe re = new ApiRe();

            if (!this.config.SecurityConfig.OpenRegister)
            {
                re.Msg = "服务器管理员已经禁止用户注册功能";
                return(LeanoteJson(re));
            }

            if (await authService.Register(email, pwd, 0))
            {
                re = new ApiRe()
                {
                    Ok  = true,
                    Msg = "注册成功"
                };
            }
            else
            {
                re = new ApiRe()
                {
                    Ok  = false,
                    Msg = "注册失败"
                };
            }
            return(Json(re, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 6
0
        public IActionResult SetRTEditorPreferences(string rtOption)
        {
            var re        = new ResponseMessage();
            var mdHashSet = new HashSet <string>();

            mdHashSet.Add("ace");
            mdHashSet.Add("vditor");

            var rthashSet = new HashSet <string>();

            rthashSet.Add("tinymce");
            rthashSet.Add("textbus");
            //参数判断
            if (string.IsNullOrEmpty(rtOption) || !rthashSet.Contains(rtOption))
            {
                re.Msg = "Parameter error ";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            var user = GetUserBySession();

            //设置编辑器偏好
            userService.SetRTEditorPreferences(user.UserId, rtOption);
            re.Ok = true;
            return(Json(re, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 7
0
        public IActionResult DoLogin(string email, string pwd, string captcha)
        {
            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 || !UnixTimeHelper.IsValid(time, 15))
            {
                Re re = new Re()
                {
                    Ok = false, Msg = "验证码过期或失效"
                };
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            //销毁验证码的标志
            HttpContext.Session.SetInt32("VerifyCodeValid", 0);
            if (string.IsNullOrEmpty(verifyCode) || string.IsNullOrEmpty(captcha))
            {
                Re re = new Re()
                {
                    Ok = false, Msg = "错误参数"
                };
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            else
            {
                if (!captcha.ToLower().Equals(verifyCode))
                {
                    Re re = new Re()
                    {
                        Ok = false, Msg = "验证码错误"
                    };
                    return(Json(re, MyJsonConvert.GetSimpleOptions()));
                }
                string token;
                User   user;
                if (!AuthService.LoginByPWD(email, pwd, out token, out user))
                {
                    //登录失败
                    Re re = new Re()
                    {
                        Ok = false, Msg = "wrongUsernameOrPassword"
                    };
                    return(Json(re, MyJsonConvert.GetSimpleOptions()));
                }
                else
                {
                    //登录成功
                    HttpContext.Session.SetString("_token", token);
                    HttpContext.Session.SetString("_userId", user.UserId.ToString("x"));
                    Re re = new Re()
                    {
                        Ok = true
                    };
                    return(Json(re, MyJsonConvert.GetSimpleOptions()));
                }
            }
        }
Exemplo n.º 8
0
        //todo:注销函数
        public JsonResult Logout()
        {
            //ex:API当前不使用cookie和session判断用户身份,
            //API调用必须显式的提供token字段,以证明身份

            ApiRe apiRe = new ApiRe()
            {
                Ok  = true,
                Msg = "未提供注销功能"
            };

            return(Json(apiRe, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> UploadAvatar()
        {
            var re = await uploadImage("logo", null);

            if (re.Ok)
            {
                re.Ok = userService.UpdateAvatar(GetUserIdBySession(), re.Id);
                if (re.Ok)
                {
                    UpdateSession("Logo", re.Id);
                }
            }

            return(Json(re, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> fetch([FromBody] FetchFileRequest fetchFileRequest, string token)
        {
            var user = tokenSerivce.GetUserByToken(token);

            if (user == null)
            {
                Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                return(Content("401"));
            }


            string msg = string.Empty;

            //请求
            //var fetchFileRequest = JsonSerializer.Deserialize<FetchFileRequest>(json);
            //判断下载路径

            if (fetchFileRequest.url.StartsWith("/api"))
            {
                fetchFileRequest.url = config.APPConfig.SiteUrl + fetchFileRequest.url;
            }

            //下载文件
            var fileModel = await DownLoadFile(fetchFileRequest.url);


            //保存到本地
            var resultURL = UploadImagesOrAttach(ref fileModel, out msg, user.UserId);

            if (string.IsNullOrEmpty(resultURL))
            {
                resultURL = fetchFileRequest.url;
            }
            //返回的消息体
            var fetchResponse = new FetchFileResponse()
            {
                msg  = msg,
                data = new FetchData()
                {
                    originalURL = fetchFileRequest.url,
                    url         = resultURL
                }
            };

            return(Json(fetchResponse, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> RegisterCredentials(string token, string keyName, string data)
        {
            try
            {
                var tokenVerify = tokenSerivce.VerifyToken(token);
                if (!tokenVerify)
                {
                    var apiRe = new ApiRe()
                    {
                        Ok  = false,
                        Msg = "注册失败,token无效"
                    };
                    return(Json(apiRe, MyJsonConvert.GetSimpleOptions()));
                }
                JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions
                {
                    Encoder    = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                    Converters =
                    {
                        new JsonStringEnumMemberConverter(),
                        new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
                    },
                    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
                };
                options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

                options.Converters.Add(new Base64UrlConverter());

                var attestationResponse = JsonSerializer.Deserialize <AuthenticatorAttestationRawResponse>(data, options);

                var user = userService.GetUserByToken(token);
                if (string.IsNullOrEmpty(keyName) || !MyStringUtil.IsNumAndEnCh(keyName))
                {
                    keyName = "key";
                }
                var success = await fido2Service.RegisterCredentials(user, keyName, attestationResponse);

                // 4. return "ok" to the client
                return(Json(success));
            }
            catch (Exception e)
            {
                return(Json(new CredentialMakeResult(status: "error", errorMessage: FormatException(e), result: null)));
            }
        }
Exemplo n.º 12
0
        public IActionResult upload(string token)
        {
            var user = tokenSerivce.GetUserByToken(token);

            if (user == null)
            {
                Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                return(Content("401"));
            }

            string             msg  = null;
            var                data = UploadImagesOrAttach(user.UserId, out msg);
            UploadFileResponse uploadFileResponse = new UploadFileResponse()
            {
                data = data
            };

            return(Json(uploadFileResponse, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 13
0
        public IActionResult GetLikesAndComments([ModelBinder(typeof(Hex2LongModelBinder))] long?noteId, string callback)
        {
            long?userId = GetUserIdBySession();
            Dictionary <string, dynamic> result = new Dictionary <string, dynamic>();

            // 我也点过?
            var isILikeIt = false;

            if (userId != null)
            {
                isILikeIt = blogService.IsILikeIt(noteId, userId);
                var userAndBlog = userService.GetUserAndBlog(userId);
                result.Add("visitUserInfo", userAndBlog);
            }

            // 点赞用户列表
            bool hasMoreLikedUser = false;
            var  likedUsers       = blogService.ListLikedUsers(noteId, false, out hasMoreLikedUser);
            // 评论
            var page = this.GetPage();

            blogService.ListComments(userId, noteId, page, 15, out Page pageInfo, out BlogCommentPublic[] comments, out Dictionary <string, UserAndBlog> commentUserInfo);

            result.Add("isILikeIt", isILikeIt);
            result.Add("likedUsers", likedUsers);
            result.Add("hasMoreLikedUser", hasMoreLikedUser);
            result.Add("pageInfo", pageInfo);
            result.Add("comments", comments);
            result.Add("commentUserInfo", commentUserInfo);

            ResponseMessage re = new ResponseMessage()
            {
                Ok   = true,
                Item = result
            };

            string json          = JsonSerializer.Serialize(re, MyJsonConvert.GetSimpleOptions());
            string jsonpCallback = $"jsonpCallback({json});";

            return(new JavaScriptResult(jsonpCallback));
        }
Exemplo n.º 14
0
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var token = context.HttpContext.Session.GetString("token");

            if (token == null || string.IsNullOrEmpty(token))
            {
                token = context.HttpContext.Request.Query["token"];
            }
            if (token == null || string.IsNullOrEmpty(token))
            {
                if (context.HttpContext.Request.Form != null && context.HttpContext.Request.Form.Any())
                {
                    token = context.HttpContext.Request.Form["token"];
                }
            }
            if (token == null || string.IsNullOrEmpty(token))
            {
                token = context.HttpContext.Request.Headers["token"];
            }
            if (token == null || string.IsNullOrEmpty(token))
            {
                token = context.HttpContext.Session.GetString("token");
            }

            if (token == null || string.IsNullOrEmpty(token) || !tokenSerivce.VerifyToken(token))
            {
                context.HttpContext.Session.Remove("token");
                //context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                ApiRe apiRe = new ApiRe()
                {
                    Ok  = false,
                    Msg = "NOTLOGIN",
                };
                //return Json(apiRe, MyJsonConvert.GetOptions());
                context.Result = new JsonResult(apiRe, MyJsonConvert.GetSimpleOptions());

                return;
            }
        }
Exemplo n.º 15
0
        public IActionResult Predict(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Content("error"));
            }
            var modelOutput = spamService.Predict(input);
            var spam        = new SpamInfo()
            {
                SpamId       = idGenerator.NextId(),
                Input        = input,
                Prediction   = modelOutput.Prediction,
                Score        = modelOutput.Score,
                ManualCheck  = false,
                ManualResult = false,
                CreatData    = DateTime.Now
            };

            spamService.AddSpamInfo(spam);
            return(Json(modelOutput, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 16
0
        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()));
        }
Exemplo n.º 17
0
        //获得同步状态
        //  [HttpPost]
        public JsonResult GetSyncState(string token)
        {
            User user = TokenSerivce.GetUserByToken(token);

            if (user == null)
            {
                ApiRe apiRe = new ApiRe()
                {
                    Ok  = false,
                    Msg = "Not logged in",
                };
                string json = JsonSerializer.Serialize(apiRe, MyJsonConvert.GetSimpleOptions());

                return(Json(apiRe, MyJsonConvert.GetOptions()));
            }
            ApiGetSyncState apiGetSyncState = new ApiGetSyncState()
            {
                LastSyncUsn  = user.Usn,
                LastSyncTime = UnixTimeHelper.GetTimeStampInLong(DateTime.Now)
            };

            return(Json(apiGetSyncState, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 18
0
        //todo:注册
        public JsonResult Register(string email, string pwd)
        {
            //ex:API当前不使用cookie和session判断用户身份,
            //API调用必须显式的提供token字段,以证明身份
            ApiRe apiRe;

            if (AuthService.Register(email, pwd, 0))
            {
                apiRe = new ApiRe()
                {
                    Ok  = true,
                    Msg = "注册成功"
                };
            }
            else
            {
                apiRe = new ApiRe()
                {
                    Ok  = false,
                    Msg = "注册失败"
                };
            }
            return(Json(apiRe, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 19
0
        public JsonResult SetNotebook2Blog(string notebookId, bool isBlog)
        {
            var result = notebookService.ToBlog(GetUserIdBySession(), notebookId.ToLongByHex(), isBlog);

            return(Json(result, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 20
0
        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()));
            }
        }
Exemplo n.º 21
0
        //public IActionResult DoLogin(string email, string pwd, string captcha)
        public async Task <IActionResult> DoLogin(string email, string pwd, string captcha)
        {
            var number = distributedCache.GetInt(errorCountKey);

            //是否需要验证码
            if (this.config.SecurityConfig.NeedVerificationCode == NeedVerificationCode.ON ||
                (this.config.SecurityConfig.NeedVerificationCode == NeedVerificationCode.AUTO) && number > 10)
            {
                string errorMessage = string.Empty;
                //检查验证码是否一样
                if (!CheckVerifyCode(captcha, out errorMessage))
                {
                    ResponseMessage re = new ResponseMessage()
                    {
                        Ok = false, Msg = errorMessage
                    };
                    return(Json(re, MyJsonConvert.GetSimpleOptions()));
                }
            }
            var tokenStr = await authService.LoginByPWD(email, pwd);

            if (string.IsNullOrEmpty(tokenStr))
            {
                //登录失败
                ResponseMessage re = new ResponseMessage()
                {
                    Ok = false, Msg = "wrongUsernameOrPassword"
                };

                number++;
                distributedCache.SetInt(errorCountKey, number.Value);
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            else
            {
                var user = userService.GetUserByEmail(email);
                distributedCache.SetInt(errorCountKey, 0);
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, user.UserId.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Username));

                if (!string.IsNullOrEmpty(user.Role))
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));//角色 用户组
                }


                if (user.Jurisdiction != null && user.Jurisdiction.Any())
                {
                    foreach (var item in user.Jurisdiction)
                    {
                        identity.AddClaim(new Claim(item.AuthorizationType, item.AuthorizationValue));//授权
                    }
                }
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTime.Now.AddDays(1)
                }).ConfigureAwait(false);

                //var token=   tokenSerivce.GenerateToken();

                //登录成功
                HttpContext.Session.SetString("token", tokenStr);
                HttpContext.Session.SetString("UserId", user.UserId.ToHex24());
                HttpContext.Session.SetBool("Verified", user.Verified);

                HttpContext.Response.Cookies.Append("token", tokenStr,
                                                    new CookieOptions()
                {
                    HttpOnly = true,
                    Domain   = config.APPConfig.Domain,
                    SameSite = SameSiteMode.Lax,
                    Secure   = true,
                    MaxAge   = TimeSpan.FromDays(30)
                });

                ResponseMessage re = new ResponseMessage()
                {
                    Ok = true
                };


                var jti = idGenerator.NextId();
                //签署JWT
                var claims = new List <Claim>()
                {
                    new Claim(JwtRegisteredClaimNames.Jti, jti.ToHex()),
                    new Claim(ClaimTypes.Name, user.Username),
                    new Claim(ClaimTypes.Sid, user.UserId.ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email),
                    new Claim(JwtRegisteredClaimNames.Sub, "{B362F518-1C49-437B-962B-8D83A0A0285E}"),
                };
                //网站密钥
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.SecurityConfig.Secret));

                var jwtToken = new JwtSecurityToken(

                    issuer: config.APPConfig.SiteUrl,
                    audience: config.APPConfig.SiteUrl,
                    claims: claims,
                    notBefore: DateTime.Now,

                    expires: DateTime.Now.AddYears(100),

                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)

                    );
                var jwt = new JwtSecurityTokenHandler().WriteToken(jwtToken);
                re.Payload = jwt;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
        }
Exemplo n.º 22
0
        public IActionResult GetInfoJson()
        {
            JoplinServerInfo joplinServerInfo = new JoplinServerInfo();

            return(Json(joplinServerInfo, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 23
0
        public static string ToJsonForSimple <T>(this T t)
        {
            string json = JsonSerializer.Serialize(t, MyJsonConvert.GetSimpleOptions());

            return(json);
        }
Exemplo n.º 24
0
 protected IActionResult SimpleJson(object?data)
 {
     return(Json(data, MyJsonConvert.GetSimpleOptions()));
 }
Exemplo n.º 25
0
        public async Task <IActionResult> UpdateNoteTitleAndContent(string token, string noteId, string noteTitle, string content, string dataSignJson, string digitalEnvelopeJson)
        {
            var user = tokenSerivce.GetUserByToken(token);
            var re   = new ApiRe();

            if (user == null)
            {
                return(LeanoteJson(re));
            }
            DigitalEnvelope digitalEnvelope = null;
            var             verify          = false;

            if (this.config.SecurityConfig.ForceDigitalEnvelope)
            {
                //数字信封
                if (this.config.SecurityConfig.ForceDigitalEnvelope)
                {
                    digitalEnvelope = DigitalEnvelope.FromJSON(digitalEnvelopeJson);
                    var data = digitalEnvelope.GetPayLoadValue(this.gMService, this.config.SecurityConfig.PrivateKey);
                    if (data == null)
                    {
                        throw new Exception("数字信封解密失败");
                    }
                    //赋予解密的数字信封
                    content = data;
                }
            }

            if (this.config.SecurityConfig.ForceDigitalSignature)
            {
                //验证签名
                var dataSign = DataSignDTO.FromJSON(dataSignJson);
                verify = await this.ePassService.VerifyDataSign(dataSign);

                if (!verify)
                {
                    return(LeanoteJson(re));
                }
                verify = dataSign.SignData.Operate.Equals("/api/Note/UpdateNoteTitleAndContent");
                if (!verify)
                {
                    re.Msg = "Operate is not Equals ";
                    return(LeanoteJson(re));
                }
                //签字签名和数字信封数据
                if (dataSign != null)
                {
                    var dataSM3 = gMService.SM3(noteId + noteTitle + content);
                    var signSM3 = dataSign.SignData.Hash;
                    if (!dataSM3.ToUpper().Equals(signSM3.ToUpper()))
                    {
                        re.Msg = "SM3 is error";
                        re.Ok  = false;
                        return(LeanoteJson(re));
                    }
                }

                //签名存证
                this.dataSignService.AddDataSign(dataSign, "UpdateNoteTitleAndContent");
            }

            //-------------校验参数合法性
            if (user == null)
            {
                re.Msg = "NOlogin";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }

            // 先判断USN的问题, 因为很可能添加完附件后, 会有USN冲突, 这时附件就添错了
            var note = noteService.GetNote(noteId.ToLongByHex(), user.UserId);

            verify = noteRepositoryService.Verify(note.NotesRepositoryId, user.UserId, RepositoryAuthorityEnum.Write);
            if (!verify)
            {
                return(LeanoteJson(re));
            }

            if (note == null || note.NoteId == 0)
            {
                re.Msg = "notExists";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            var des = MyHtmlHelper.SubHTMLToRaw(content, 200);

            var noteContentId = idGenerator.NextId();

            NoteContent noteContent = new NoteContent()
            {
                NoteContentId = noteContentId,
                Abstract      = content,
                Content       = content,

                UserId        = user.UserId,
                NoteId        = note.NoteId,
                CreatedTime   = DateTime.Now,
                UpdatedTime   = DateTime.Now,
                UpdatedUserId = user.UserId
            };

            if (this.config.SecurityConfig.DataBaseEncryption)
            {
                noteContent.Abstract = "DataBaseEncryption";
            }

            noteContentService.UpdateNoteContent(note.NoteId, noteContent);

            noteService.UpdateNoteTitle(note.NoteId, noteTitle);

            var usn = noteRepositoryService.IncrUsn(note.NotesRepositoryId);

            noteService.UpdateUsn(note.NoteId, usn);
            re.Ok   = true;
            re.Data = note;
            if (this.config.SecurityConfig.ForceDigitalEnvelope)
            {
                var key  = digitalEnvelope.getSM4Key(this.gMService, this.config.SecurityConfig.PrivateKey);
                var json = note.ToJson();

                var payLoad = new PayLoadDTO();
                payLoad.SetData(json);

                var payLoadJson = payLoad.ToJson();

                var jsonHex = Common.Utils.HexUtil.ByteArrayToString(Encoding.UTF8.GetBytes(payLoadJson));

                var enc = gMService.SM4_Encrypt_CBC(jsonHex, key, digitalEnvelope.IV, true);
                re.Data       = enc;
                re.Encryption = true;
            }

            return(LeanoteJson(re));
        }
Exemplo n.º 26
0
        public JsonResult UpdateNote(ApiNote noteOrContent, string token)
        {
            Note noteUpdate     = new Note();
            var  needUpdateNote = false;
            var  re             = new ReUpdate();
            long?tokenUserId    = GetUserIdByToken(token);
            var  noteId         = noteOrContent.NoteId.ToLongByHex();

            //-------------校验参数合法性
            if (tokenUserId == 0)
            {
                re.Msg = "NOlogin";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }

            if (string.IsNullOrEmpty(noteOrContent.NoteId))
            {
                re.Msg = "noteIdNotExists";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }

            if (noteOrContent.Usn < 1)
            {
                re.Msg = "usnNotExists";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            // 先判断USN的问题, 因为很可能添加完附件后, 会有USN冲突, 这时附件就添错了
            var note        = noteService.GetNote(noteId, tokenUserId);
            var noteContent = noteContentService.GetNoteContent(note.NoteId, tokenUserId, false);

            if (note == null || note.NoteId == 0)
            {
                re.Msg = "notExists";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            //判断服务器版本与客户端版本是否一致
            if (note.Usn != noteOrContent.Usn)
            {
                re.Msg = "conflict";
                re.Ok  = false;
                return(Json(re, MyJsonConvert.GetSimpleOptions()));
            }
            //-------------更新文件和附件内容
            if (noteOrContent.Files != null && noteOrContent.Files.Length > 0)
            {
                for (int i = 0; i < noteOrContent.Files.Length; i++)
                {
                    var file = noteOrContent.Files[i];
                    if (file.HasBody)
                    {
                        if (!string.IsNullOrEmpty(file.LocalFileId))
                        {
                            var result = UploadImages("FileDatas[" + file.LocalFileId + "]", tokenUserId, noteId, file.IsAttach, out long?serverFileId, out string msg);
                            if (!result)
                            {
                                if (string.IsNullOrEmpty(msg))
                                {
                                    re.Msg = "fileUploadError";
                                }
                                if (!string.Equals(msg, "notImage", System.StringComparison.OrdinalIgnoreCase))
                                {
                                    return(Json(re, MyJsonConvert.GetLeanoteOptions()));
                                }
                            }
                            else
                            {
                                // 建立映射
                                file.FileId            = serverFileId.ToHex24();
                                noteOrContent.Files[i] = file;
                            }
                        }
                        else
                        {
                            return(Json(new ReUpdate()
                            {
                                Ok = false,
                                Msg = "LocalFileId_Is_NullOrEmpty",
                                Usn = 0
                            }, MyJsonConvert.GetSimpleOptions()));
                        }
                    }
                }
            }
            //更新用户元数据
            //int usn = UserService.IncrUsn(tokenUserId);

            // 移到外面来, 删除最后一个file时也要处理, 不然总删不掉
            // 附件问题, 根据Files, 有些要删除的, 只留下这些
            if (noteOrContent.Files != null)
            {
                attachService.UpdateOrDeleteAttachApiAsync(noteId, tokenUserId, noteOrContent.Files);
            }
            //-------------更新笔记内容
            var  afterContentUsn = 0;
            var  contentOk       = false;
            var  contentMsg      = "";
            long?contentId       = 0;

            if (noteOrContent.Content != null)
            {
                // 把fileId替换下
                FixPostNotecontent(ref noteOrContent);
                // 如果传了Abstract就用之
                if (noteOrContent.Abstract != null)
                {
                    noteOrContent.Abstract = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Abstract, 200);
                }
                else
                {
                    noteOrContent.Abstract = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Content, 200);
                }
            }
            else
            {
                noteOrContent.Abstract = MyHtmlHelper.SubHTMLToRaw(noteContent.Content, 200);
            }
            //上传noteContent的变更
            contentOk = noteContentService.UpdateNoteContent(
                noteOrContent,
                out contentMsg,
                out contentId
                );
            //返回处理结果
            if (!contentOk)
            {
                re.Ok  = false;
                re.Msg = contentMsg;
                re.Usn = afterContentUsn;
                return(Json(re, MyJsonConvert.GetLeanoteOptions()));
            }

            //-------------更新笔记元数据
            int afterNoteUsn = 0;
            var noteOk       = false;
            var noteMsg      = "";

            noteOk = noteService.UpdateNote(
                ref noteOrContent,
                tokenUserId,
                contentId,
                true,
                true,
                out noteMsg,
                out afterNoteUsn
                );
            if (!noteOk)
            {
                re.Ok  = false;
                re.Msg = noteMsg;
                return(Json(re, MyJsonConvert.GetLeanoteOptions()));
            }
            //处理结果
            //-------------API返回客户端信息
            note = noteService.GetNote(noteId, tokenUserId);
            // noteOrContent.NoteId = noteId.ToHex24();
            // noteOrContent.UserId = tokenUserId.ToHex24();
            //  noteOrContent.Title = note.Title;
            // noteOrContent.Tags = note.Tags;
            // noteOrContent.IsMarkdown = note.IsMarkdown;
            // noteOrContent.IsBlog = note.IsBlog;
            //noteOrContent.IsTrash = note.IsTrash;
            //noteOrContent.IsDeleted = note.IsDeleted;
            //noteOrContent.IsTrash = note.IsTrash;

            //noteOrContent.Usn = note.Usn;
            //noteOrContent.CreatedTime = note.CreatedTime;
            //noteOrContent.UpdatedTime = note.UpdatedTime;
            //noteOrContent.PublicTime = note.PublicTime;

            noteOrContent.Content     = "";
            noteOrContent.Usn         = afterNoteUsn;
            noteOrContent.UpdatedTime = DateTime.Now;
            noteOrContent.IsDeleted   = false;
            noteOrContent.UserId      = tokenUserId.ToHex24();
            return(Json(noteOrContent, MyJsonConvert.GetLeanoteOptions()));
        }
Exemplo n.º 27
0
        public async Task <IActionResult> AddNote(ApiNote noteOrContent, string token)
        {
            var re = new ApiRe();

            var user = tokenSerivce.GetUserByToken(token);

            if (user == null)
            {
                return(LeanoteJson(re));
            }

            //json 返回状态乱

            long?tokenUserId = GetUserIdByToken(token);;
            long?myUserId    = tokenUserId;

            if (noteOrContent == null || string.IsNullOrEmpty(noteOrContent.NotebookId))
            {
                return(Json(new ApiRe()
                {
                    Ok = false, Msg = "notebookIdNotExists"
                }, MyJsonConvert.GetSimpleOptions()));
            }
            long?noteId = idGenerator.NextId();

            if (noteOrContent.Title == null)
            {
                noteOrContent.Title = "无标题";
            }

            // TODO 先上传图片/附件, 如果不成功, 则返回false
            //-------------新增文件和附件内容
            int attachNum = 0;

            if (noteOrContent.Files != null && noteOrContent.Files.Length > 0)
            {
                for (int i = 0; i < noteOrContent.Files.Length; i++)
                {
                    var file = noteOrContent.Files[i];
                    if (file.HasBody)
                    {
                        if (!string.IsNullOrEmpty(file.LocalFileId))
                        {
                            var result = UploadImages("FileDatas[" + file.LocalFileId + "]", tokenUserId, noteId, file.IsAttach, out long?serverFileId, out string msg);
                            if (!result)
                            {
                                if (string.IsNullOrEmpty(msg))
                                {
                                    re.Msg = "fileUploadError";
                                }
                                else
                                {
                                    re.Msg = msg;
                                    return(Json(re, MyJsonConvert.GetLeanoteOptions()));
                                }
                            }
                            else
                            {
                                // 建立映射
                                file.FileId            = serverFileId.ToHex24();
                                noteOrContent.Files[i] = file;
                                if (file.IsAttach)
                                {
                                    attachNum++;
                                }
                            }
                        }
                        else
                        {   //存在疑问
                            return(Json(new ReUpdate()
                            {
                                Ok = false,
                                Msg = "LocalFileId_Is_NullOrEmpty",
                                Usn = 0
                            }, MyJsonConvert.GetSimpleOptions()));
                        }
                    }
                }
            }
            else
            {
            }
            //-------------替换笔记内容中的文件ID
            FixPostNotecontent(ref noteOrContent);
            if (noteOrContent.Tags != null)
            {
                if (noteOrContent.Tags.Length > 0 && noteOrContent.Tags[0] == null)
                {
                    noteOrContent.Tags = Array.Empty <string>();
                    //noteOrContent.Tags= new string[] { ""};
                }
            }
            //-------------新增笔记对象
            Note note = new Note()
            {
                UserId        = tokenUserId,
                NoteId        = noteId,
                CreatedUserId = tokenUserId,
                UpdatedUserId = noteId,
                NotebookId    = noteOrContent.NotebookId.ToLongByHex(),
                Title         = noteOrContent.Title,
                Tags          = noteOrContent.Tags,
                Desc          = noteOrContent.Desc,
                IsBlog        = noteOrContent.IsBlog.GetValueOrDefault(),
                IsMarkdown    = noteOrContent.IsMarkdown.GetValueOrDefault(),
                AttachNum     = attachNum,
                CreatedTime   = noteOrContent.CreatedTime,
                UpdatedTime   = noteOrContent.UpdatedTime,
                ContentId     = idGenerator.NextId()
            };

            //-------------新增笔记内容对象
            NoteContent noteContent = new NoteContent()
            {
                NoteContentId = note.ContentId,
                NoteId        = noteId,
                UserId        = tokenUserId,
                IsBlog        = note.IsBlog,
                Content       = noteOrContent.Content,
                Abstract      = noteOrContent.Abstract,
                CreatedTime   = noteOrContent.CreatedTime,
                UpdatedTime   = noteOrContent.UpdatedTime,
                IsHistory     = false
            };

            //-------------得到Desc, abstract
            if (string.IsNullOrEmpty(noteOrContent.Abstract))
            {
                if (noteOrContent.IsMarkdown.GetValueOrDefault())
                {
                    // note.Desc = MyHtmlHelper.SubMarkDownToRaw(noteOrContent.Content, 200);
                    noteContent.Abstract = MyHtmlHelper.SubMarkDownToRaw(noteOrContent.Content, 200);
                }
                else
                {
                    //note.Desc = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Content, 200);
                    noteContent.Abstract = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Content, 200);
                }
            }
            else
            {
                note.Desc = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Abstract, 200);
            }
            if (noteOrContent.Desc == null)
            {
                if (noteOrContent.IsMarkdown.GetValueOrDefault())
                {
                    note.Desc = MyHtmlHelper.SubMarkDownToRaw(noteOrContent.Content, 200);
                }
                else
                {
                    note.Desc = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Content, 200);
                }
            }
            else
            {
                note.Desc = noteOrContent.Desc;
            }

            note = noteService.AddNoteAndContent(note, noteContent, myUserId);
            //-------------将笔记与笔记内容保存到数据库
            if (note == null || note.NoteId == 0)
            {
                return(Json(new ApiRe()
                {
                    Ok = false,
                    Msg = "AddNoteAndContent_is_error"
                }));
            }
            //-------------API返回客户端信息
            noteOrContent.NoteId      = noteId.ToHex24();
            noteOrContent.UserId      = tokenUserId.ToHex24();
            noteOrContent.Title       = note.Title;
            noteOrContent.Tags        = note.Tags;
            noteOrContent.IsMarkdown  = note.IsMarkdown;
            noteOrContent.IsBlog      = note.IsBlog;
            noteOrContent.IsTrash     = note.IsTrash;
            noteOrContent.IsDeleted   = note.IsDeleted;
            noteOrContent.IsTrash     = note.IsTrash;
            noteOrContent.IsTrash     = note.IsTrash;
            noteOrContent.Usn         = note.Usn;
            noteOrContent.CreatedTime = note.CreatedTime;
            noteOrContent.UpdatedTime = note.UpdatedTime;
            noteOrContent.PublicTime  = note.PublicTime;
            //Files = files

            //------------- 删除API中不需要返回的内容
            noteOrContent.Content  = "";
            noteOrContent.Abstract = "";
            //	apiNote := info.NoteToApiNote(note, noteOrContent.Files)

            return(Json(noteOrContent, MyJsonConvert.GetLeanoteOptions()));
        }
Exemplo n.º 28
0
        public JsonResult UpdateNotebookTitle(string notebookId, string title)
        {
            var result = notebookService.UpdateNotebookTitle(notebookId.ToLongByHex(), GetUserIdBySession(), title);

            return(Json(result, MyJsonConvert.GetSimpleOptions()));
        }
Exemplo n.º 29
0
        public static string ToJsonForDic(this Dictionary <string, long> t)
        {
            string json = JsonSerializer.Serialize(t, MyJsonConvert.GetSimpleOptions());

            return(json);
        }