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.Validate(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()
            });
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var captchaedModel =
            context.ActionArguments.Where(p => p.Value is ICaptchable)
            .Select(x => x.Value as ICaptchable)
            .FirstOrDefault();

        if (null == captchaedModel)
        {
            context.ModelState.AddModelError(nameof(captchaedModel.CaptchaCode), "Captcha Code is required");
            context.Result = new BadRequestObjectResult(context.ModelState);
        }
        else
        {
            if (!_captcha.Validate(captchaedModel.CaptchaCode, context.HttpContext.Session))
            {
                context.ModelState.AddModelError(nameof(captchaedModel.CaptchaCode), "Wrong Captcha Code");
                context.Result = new ConflictObjectResult(context.ModelState);
            }
            else
            {
                base.OnActionExecuting(context);
            }
        }
    }
Exemple #3
0
        public async Task <IActionResult> OnPostAsync()
        {
            try
            {
                if (!_captcha.Validate(CaptchaCode, HttpContext.Session))
                {
                    ModelState.AddModelError(nameof(CaptchaCode), "Wrong Captcha Code");
                }

                if (ModelState.IsValid)
                {
                    var uid = await _localAccountService.ValidateAsync(Username, Password);

                    if (uid != Guid.Empty)
                    {
                        var claims = new List <Claim>
                        {
                            new (ClaimTypes.Name, Username),
                            new (ClaimTypes.Role, "Administrator"),
                            new ("uid", uid.ToString())
                        };
                        var ci = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        var p  = new ClaimsPrincipal(ci);

                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, p);

                        await _localAccountService.LogSuccessLoginAsync(uid,
                                                                        HttpContext.Connection.RemoteIpAddress?.ToString());

                        var successMessage = $@"Authentication success for local account ""{Username}""";

                        _logger.LogInformation(successMessage);
                        await _blogAudit.AddEntry(BlogEventType.Authentication, BlogEventId.LoginSuccessLocal, successMessage);

                        return(RedirectToPage("/Admin/Post"));
                    }
                    ModelState.AddModelError(string.Empty, "Invalid Login Attempt.");
                    return(Page());
                }

                var failMessage = $@"Authentication failed for local account ""{Username}""";

                _logger.LogWarning(failMessage);
                await _blogAudit.AddEntry(BlogEventType.Authentication, BlogEventId.LoginFailedLocal, failMessage);

                Response.StatusCode = StatusCodes.Status400BadRequest;
                ModelState.AddModelError(string.Empty, "Bad Request.");
                return(Page());
            }
            catch (Exception e)
            {
                _logger.LogWarning($@"Authentication failed for local account ""{Username}""");

                ModelState.AddModelError(string.Empty, e.Message);
                return(Page());
            }
        }
Exemple #4
0
        public IActionResult Index(HomeModel model)
        {
            if (ModelState.IsValid)
            {
                bool isValidCaptcha = _captcha.Validate(model.CaptchaCode, HttpContext.Session);
                return(Content(isValidCaptcha ? "Success" : "Invalid captcha code"));
            }

            return(BadRequest());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!_captcha.Validate(Input.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError("Input.CaptchaCode", "Captcha code is not correct.");
                return(Page());
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { area = "Identity", code },
                    protocol: Request.Scheme);

                await _emailSender.SendEmailAsync(
                    Input.Email,
                    "Reset Password",
                    $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
Exemple #6
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (!_allowRegistering)
            {
                return(Unauthorized());
            }
            if (!_captcha.Validate(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));
        }
Exemple #7
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                if (!_captcha.Validate(Input.CaptchaCode, HttpContext.Session))
                {
                    ModelState.AddModelError("Input.CaptchaCode", "Captcha code is not correct.");
                    return(Page());
                }

                if (!await _queryHelper.CheckEmail(Input.Email))
                {
                    ModelState.AddModelError("Input.Email", "Account with this Email already exists.");

                    return(Page());
                }


                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, Login = Input.Prefix.ToLower() + Input.Login.ToLower()
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "user");

                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);


                    var acc = new Data.DataModels.Account();
                    acc.userId = user.Id;
                    acc.User   = user;
                    _db.GameAccount.Add(acc);

                    user.AccountId = acc.Id;

                    await _db.SaveChangesAsync();

                    string ssn = HelperFunctions.GenerateSSN();
                    string key = _config.GetSection("md5password").GetSection("Key").Value;

                    if (string.IsNullOrEmpty(key))
                    {
                        try
                        {
                            //await _queryHelper.InsertSSN(ssn, Input.Prefix.ToLower() + Input.Login.ToLower(), Input.Email);
                            await _queryHelper.InsertUserAccount(Input.Prefix.ToLower() + Input.Login.ToLower(), Input.Email);

                            await _queryHelper.InsertUserInfo(Input.Prefix.ToLower() + Input.Login.ToLower(), ssn);

                            //don't pass md5password: if you are not using md5 password in l2auth
                            await _queryHelper.InsertUserAuth(Input.Prefix.ToLower() + Input.Login.ToLower(), Input.Password);

                            await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                              $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
                        }
                        catch (SqlException e)
                        {
                            Console.WriteLine("Errooooor: " + e.Message);
                        }
                    }
                    else
                    {
                        try
                        {
                            //await _queryHelper.InsertSSN(ssn, Input.Prefix.ToLower() + Input.Login.ToLower(), Input.Email);
                            await _queryHelper.InsertUserAccount(Input.Prefix.ToLower() + Input.Login.ToLower(), Input.Email);

                            await _queryHelper.InsertUserInfo(Input.Prefix.ToLower() + Input.Login.ToLower(), ssn);

                            //don't pass md5password: if you are not using md5 password in l2auth
                            await _queryHelper.InsertUserAuth(Input.Prefix.ToLower() + Input.Login.ToLower(), Input.Password, md5password : HelperFunctions.hCrypt(Input.Password, key));

                            await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                              $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
                        }
                        catch (SqlException e)
                        {
                            Console.WriteLine("Errooooor: " + e.Message);
                        }
                    }


                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl, login = Input.Prefix.ToLower() + Input.Login.ToLower(), password = Input.Password }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemple #8
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            if (!_captcha.Validate(Input.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError("Input.CaptchaCode", "Captcha code is not correct.");
                return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToPage("./ResetPasswordConfirmation"));
            }


            var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);

            if (result.Succeeded)
            {
                string key = _config.GetSection("md5password").GetSection("Key").Value;

                if (string.IsNullOrEmpty(key))
                {
                    try
                    {
                        await _queryHelper.ResetPaassword(user.Login, Input.Password);
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine("Errooooor: " + e.Message);
                    }
                }
                else
                {
                    try
                    {
                        await _queryHelper.ResetPaassword(user.Login, Input.Password, md5password : HelperFunctions.hCrypt(Input.Password, key));
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine("Errooooor: " + e.Message);
                    }
                }



                return(RedirectToPage("./ResetPasswordConfirmation"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return(Page());
        }