public async Task <IActionResult> NewComment(Guid postId, NewCommentModel model, [FromServices] ISessionBasedCaptcha captcha)
        {
            if (!string.IsNullOrWhiteSpace(model.Email) && !Helper.IsValidEmailAddress(model.Email))
            {
                ModelState.AddModelError(nameof(model.Email), "Invalid Email address.");
                return(BadRequest(ModelState.CombineErrorMessages()));
            }

            if (!_blogConfig.ContentSettings.EnableComments)
            {
                return(Forbid());
            }

            if (!captcha.ValidateCaptchaCode(model.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError(nameof(model.CaptchaCode), "Wrong Captcha Code");
                return(Conflict(ModelState));
            }

            var response = await _commentService.CreateAsync(new(postId)
            {
                Username  = model.Username,
                Content   = model.Content,
                Email     = model.Email,
                IpAddress = (bool)HttpContext.Items["DNT"] ? "N/A" : HttpContext.Connection.RemoteIpAddress?.ToString()
            });
Exemple #2
0
        public async Task <IActionResult> NewComment(PostSlugViewModelWrapper model,
                                                     [FromServices] ISessionBasedCaptcha captcha)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(Json(new CommentResponse(false, CommentResponseCode.InvalidModel)));
                }

                if (!_blogConfig.ContentSettings.EnableComments)
                {
                    Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    return(Json(new CommentResponse(false, CommentResponseCode.CommentDisabled)));
                }

                // Validate BasicCaptcha Code
                if (!captcha.ValidateCaptchaCode(model.NewCommentViewModel.CaptchaCode, HttpContext.Session))
                {
                    Logger.LogWarning("Wrong Captcha Code");
                    ModelState.AddModelError(nameof(model.NewCommentViewModel.CaptchaCode), "Wrong Captcha Code");

                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(Json(new CommentResponse(false, CommentResponseCode.WrongCaptcha)));
                }

                var commentPostModel = model.NewCommentViewModel;
                var response         = await _commentService.CreateAsync(new NewCommentRequest(commentPostModel.PostId)
                {
                    Username  = commentPostModel.Username,
                    Content   = commentPostModel.Content,
                    Email     = commentPostModel.Email,
                    IpAddress = HttpContext.Connection.RemoteIpAddress.ToString()
                });

                if (_blogConfig.NotificationSettings.SendEmailOnNewComment && null != _notificationClient)
                {
                    _ = Task.Run(async() =>
                    {
                        await _notificationClient.NotifyNewCommentAsync(response, s => Utils.MarkdownToContent(s, Utils.MarkdownConvertType.Html));
                    });
                }
                var cResponse = new CommentResponse(true,
                                                    _blogConfig.ContentSettings.RequireCommentReview ?
                                                    CommentResponseCode.Success :
                                                    CommentResponseCode.SuccessNonReview);

                return(Json(cResponse));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error NewComment");
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new CommentResponse(false, CommentResponseCode.UnknownError)));
            }
        }
Exemple #3
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (!_captcha.ValidateCaptchaCode(model.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError(string.Empty, "Invalid captacha code!");
            }
            var app = (await _apiService.AppInfoAsync(model.AppId)).App;

            if (!ModelState.IsValid)
            {
                model.Recover(app.AppName, app.IconPath);
                return(View(model));
            }
            bool exists = _dbContext.UserEmails.Any(t => t.EmailAddress == model.Email.ToLower());

            if (exists)
            {
                ModelState.AddModelError(string.Empty, $"An user with email '{model.Email}' already exists!");
                model.Recover(app.AppName, app.IconPath);
                return(View(model));
            }
            var user = new GatewayUser
            {
                UserName          = model.Email,
                Email             = model.Email,
                NickName          = model.Email.Split('@')[0],
                PreferedLanguage  = model.PreferedLanguage,
                IconFilePath      = Values.DefaultImagePath,
                RegisterIPAddress = HttpContext.Connection.RemoteIpAddress.ToString()
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var primaryMail = new UserEmail
                {
                    EmailAddress  = model.Email.ToLower(),
                    OwnerId       = user.Id,
                    ValidateToken = Guid.NewGuid().ToString("N")
                };
                _dbContext.UserEmails.Add(primaryMail);
                await _dbContext.SaveChangesAsync();

                // Send him an confirmation email here:
                await _emailSender.SendConfirmation(user.Id, primaryMail.EmailAddress, primaryMail.ValidateToken);

                await _authLogger.LogAuthRecord(user.Id, HttpContext.Connection.RemoteIpAddress.ToString(), true, app.AppId);

                await _signInManager.SignInAsync(user, isPersistent : true);

                return(await _authManager.FinishAuth(user, model, app.ForceConfirmation));
            }
            AddErrors(result);
            model.Recover(app.AppName, app.IconPath);
            return(View(model));
        }
        public IActionResult Index(HomeModel model)
        {
            if (ModelState.IsValid)
            {
                bool isValidCaptcha = _captcha.ValidateCaptchaCode(model.CaptchaCode, HttpContext.Session);
                return(Content(isValidCaptcha ? "Success" : "Invalid captcha code"));
            }

            return(BadRequest());
        }
        public async Task <IActionResult> Post(PostCommentDto dto)
        {
            if (ModelState.IsValid)
            {
                if (_captcha.ValidateCaptchaCode(dto.Code, HttpContext.Session))
                {
                    dto.IPv4 = Request.Host.ToString();
                    await _commentService.CreateAsync(dto);

                    return(RedirectToAction("Detail", "Article", new { id = dto.ArticleId }));
                }
                else
                {
                    TempData["ErrorCaptcha"] = true;
                }
            }
            TempData.Put("ErrorModel", dto);
            return(RedirectToAction("Detail", "Article", new { id = dto.ArticleId }));
        }
        public async Task <IActionResult> NewComment(Guid postId, NewCommentModel model, [FromServices] ISessionBasedCaptcha captcha)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (!_blogConfig.ContentSettings.EnableComments)
            {
                return(Forbid());
            }

            if (!captcha.ValidateCaptchaCode(model.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError(nameof(model.CaptchaCode), "Wrong Captcha Code");
                return(Conflict(ModelState));
            }

            var response = await _commentService.CreateAsync(new CommentRequest(postId)
            {
                Username  = model.Username,
                Content   = model.Content,
                Email     = model.Email,
                IpAddress = DNT ? "N/A" : HttpContext.Connection.RemoteIpAddress.ToString()
            });

            if (_blogConfig.NotificationSettings.SendEmailOnNewComment && _notificationClient is not null)
            {
                _ = Task.Run(async() =>
                {
                    await _notificationClient.NotifyCommentAsync(response,
                                                                 s => ContentProcessor.MarkdownToContent(s, ContentProcessor.MarkdownConvertType.Html));
                });
            }

            if (_blogConfig.ContentSettings.RequireCommentReview)
            {
                return(Created("moonglade://empty", response));
            }

            return(Ok());
        }
Exemple #7
0
        public async Task <IActionResult> NewComment(PostSlugViewModelWrapper model,
                                                     [FromServices] ISessionBasedCaptcha captcha)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // Validate BasicCaptcha Code
                    if (!captcha.ValidateCaptchaCode(model.NewCommentViewModel.CaptchaCode, HttpContext.Session))
                    {
                        Logger.LogWarning("Wrong Captcha Code");
                        ModelState.AddModelError(nameof(model.NewCommentViewModel.CaptchaCode), "Wrong Captcha Code");

                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        var cResponse = new CommentResponse(false, CommentResponseCode.WrongCaptcha);
                        return(Json(cResponse));
                    }

                    var commentPostModel = model.NewCommentViewModel;
                    var response         = await _commentService.AddCommentAsync(new NewCommentRequest(commentPostModel.PostId)
                    {
                        Username  = commentPostModel.Username,
                        Content   = commentPostModel.Content,
                        Email     = commentPostModel.Email,
                        IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
                        UserAgent = GetUserAgent()
                    });

                    if (response.IsSuccess)
                    {
                        if (_blogConfig.EmailSettings.SendEmailOnNewComment && null != _notificationClient)
                        {
                            _ = Task.Run(async() =>
                            {
                                await _notificationClient.SendNewCommentNotificationAsync(response.Item, s => Utils.ConvertMarkdownContent(s, Utils.MarkdownConvertType.Html));
                            });
                        }
                        var cResponse = new CommentResponse(true,
                                                            _blogConfig.ContentSettings.RequireCommentReview ?
                                                            CommentResponseCode.Success :
                                                            CommentResponseCode.SuccessNonReview);

                        return(Json(cResponse));
                    }

                    CommentResponse failedResponse;
                    switch (response.ResponseCode)
                    {
                    case (int)ResponseFailureCode.EmailDomainBlocked:
                        Logger.LogWarning("User email domain is blocked.");
                        Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.EmailDomainBlocked);
                        break;

                    case (int)ResponseFailureCode.CommentDisabled:
                        Logger.LogWarning("Comment is disabled in settings, but user somehow called NewComment() method.");
                        Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.CommentDisabled);
                        break;

                    default:
                        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.UnknownError);
                        break;
                    }
                    return(Json(failedResponse));
                }

                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new CommentResponse(false, CommentResponseCode.InvalidModel)));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error NewComment");
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new CommentResponse(false, CommentResponseCode.UnknownError)));
            }
        }
        public IActionResult NewComment(PostSlugViewModelWrapper model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // Validate BasicCaptcha Code
                    if (!_captcha.ValidateCaptchaCode(model.NewCommentModel.CaptchaCode, HttpContext.Session))
                    {
                        Logger.LogWarning($"Wrong Captcha Code, model: {JsonConvert.SerializeObject(model.NewCommentModel)}");
                        ModelState.AddModelError(nameof(model.NewCommentModel.CaptchaCode), "Wrong Captcha Code");

                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        var cResponse = new CommentResponse(false, CommentResponseCode.WrongCaptcha);
                        return(Json(cResponse));
                    }

                    var commentPostModel = model.NewCommentModel;
                    var response         = _commentService.NewComment(commentPostModel.Username, commentPostModel.Content,
                                                                      commentPostModel.PostId, commentPostModel.Email,
                                                                      HttpContext.Connection.RemoteIpAddress.ToString(),
                                                                      GetUserAgent());

                    if (response.IsSuccess)
                    {
                        if (_blogConfig.EmailConfiguration.SendEmailOnNewComment)
                        {
                            var postTitle = _postService.GetPostTitle(commentPostModel.PostId);
                            Task.Run(async() =>
                            {
                                await _emailService.SendNewCommentNotificationAsync(response.Item, postTitle);
                            });
                        }
                        var cResponse = new CommentResponse(true, CommentResponseCode.Success);
                        return(Json(cResponse));
                    }

                    CommentResponse failedResponse;
                    switch (response.ResponseCode)
                    {
                    case (int)ResponseFailureCode.EmailDomainBlocked:
                        Logger.LogWarning($"User email domain is blocked. model: {JsonConvert.SerializeObject(model)}");
                        Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.EmailDomainBlocked);
                        break;

                    case (int)ResponseFailureCode.CommentDisabled:
                        Logger.LogWarning($"Comment is disabled in settings, but user somehow called NewComment() method. model: {JsonConvert.SerializeObject(model)}");
                        Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.CommentDisabled);
                        break;

                    default:
                        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.UnknownError);
                        break;
                    }
                    return(Json(failedResponse));
                }

                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new CommentResponse(false, CommentResponseCode.InvalidModel)));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error NewComment");
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new CommentResponse(false, CommentResponseCode.UnknownError)));
            }
        }
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (!_allowRegistering)
            {
                return(Unauthorized());
            }
            if (!_captcha.ValidateCaptchaCode(model.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError(string.Empty, "Invalid captcha code!");
            }
            var app = (await _apiService.AppInfoAsync(model.AppId)).App;

            if (!ModelState.IsValid)
            {
                model.Recover(app.AppName, app.IconPath);
                return(View(model));
            }
            bool exists = _dbContext.UserEmails.Any(t => t.EmailAddress == model.Email.ToLower());

            if (exists)
            {
                ModelState.AddModelError(string.Empty, $"An user with email '{model.Email}' already exists!");
                model.Recover(app.AppName, app.IconPath);
                return(View(model));
            }
            var countStart = DateTime.UtcNow - TimeSpan.FromDays(1);
            var requestIp  = HttpContext.Connection.RemoteIpAddress.ToString();

            if (await _dbContext.Users
                .Where(t => t.RegisterIPAddress == requestIp)
                .Where(t => t.AccountCreateTime > countStart)
                .CountAsync() > 5)
            {
                ModelState.AddModelError(string.Empty, "You can't create more than 5 accounts in one day!");
                model.Recover(app.AppName, app.IconPath);
                return(View(model));
            }
            var user = new GatewayUser
            {
                UserName          = model.Email,
                Email             = model.Email,
                NickName          = model.Email.Split('@')[0],
                PreferedLanguage  = model.PreferedLanguage,
                IconFilePath      = AuthValues.DefaultImagePath,
                RegisterIPAddress = requestIp
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var primaryMail = new UserEmail
                {
                    EmailAddress  = model.Email.ToLower(),
                    OwnerId       = user.Id,
                    ValidateToken = Guid.NewGuid().ToString("N"),
                    LastSendTime  = DateTime.UtcNow
                };
                await _dbContext.UserEmails.AddAsync(primaryMail);

                await _dbContext.SaveChangesAsync();

                // Send him an confirmation email here:
                _cannonService.FireAsync <ConfirmationEmailSender>(async(sender) =>
                {
                    await sender.SendConfirmation(user.Id, primaryMail.EmailAddress, primaryMail.ValidateToken);
                });
                await _authLogger.LogAuthRecord(user.Id, HttpContext, true, app.AppId);

                await _signInManager.SignInAsync(user, isPersistent : true);

                return(await _authManager.FinishAuth(user, model, app.ForceConfirmation, app.TrustedApp));
            }
            AddErrors(result);
            model.Recover(app.AppName, app.IconPath);
            return(View(model));
        }