Exemple #1
0
        public OpResult LogOn(LoginRequest request)
        {
            LoginValidator validator        = new LoginValidator();
            var            validationResult = validator.Validate(request);

            if (!validationResult.IsValid)
            {
                return(OpResult.FailureResult(validationResult.Errors.Select(e => e.ErrorMessage).ToList()));
            }

            var account = _repo.GetFirst <Account>(a => a.UserName == request.UserName);

            if (account == null)
            {
                return(OpResult.FailureResult("Account not found"));
            }

            var salt       = account.PasswordSalt;
            var hashedPass = EncryptionUtil.GeneratePBKDF2Hash(request.Password, salt);

            if (account.PasswordHash != hashedPass)
            {
                return(OpResult.FailureResult("Invalid password"));
            }

            return(OpResult <Account> .SuccessResult(account));
        }
Exemple #2
0
        /// <summary>
        /// Validate login requtest model with fulent validator
        /// </summary>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var validator = new LoginValidator();
            var result    = validator.Validate(this);

            return(result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName })));
        }
        //Token: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIyIiwibmJmIjoxNjE1MTYwMjk4LCJleHAiOjE2MTU3NjUwOTgsImlhdCI6MTYxNTE2MDI5OH0.x5BDep3_P46HhUH0cisSARCq5CGRMCjuDnIHngZAtD35SnaxvRyOYG7LRj0N0iXNw3b869E8jjbFY5aC9YG7jw

        public async Task <IActionResult> Login(LoginViewModel model)
        {
            LoginValidator   validator = new LoginValidator();
            ValidationResult result    = validator.Validate(model);

            if (!result.IsValid)
            {
                return(BadRequest(result.Errors));
            }

            var user = await _context.Users?
                       .FirstOrDefaultAsync(p => p.Username == model.Username);

            if (user == null)
            {
                return(Unauthorized());
            }
            bool check = Crypto.VerifyHashedPassword(user.Password, model.Password);

            if (!check)
            {
                return(Unauthorized());
            }
            var userprofile = new UserProfile();

            userprofile.Username = user.Username;
            userprofile.Token    = CreateToken(user, _configuration);
            return(Ok(userprofile.Token));
        }
Exemple #4
0
        private bool ValidateDataLogin()
        {
            LoginValidator            loginValidator       = new LoginValidator();
            ValidationResult          dataValidationResult = loginValidator.Validate(login);
            IList <ValidationFailure> validationFailures   = dataValidationResult.Errors;
            UserFeedback userFeedback = new UserFeedback(FormGrid, validationFailures);

            userFeedback.ShowFeedback();
            return(dataValidationResult.IsValid);
        }
        public IActionResult Login([FromBody] LoginDto dto
                                   , [FromServices] LoginValidator validator)
        {
            var result = validator.Validate(dto);

            if (result.IsValid)
            {
                string token = _manager.MakeToken(dto.Email);
                return(Ok(new { token }));
            }

            return(UnprocessableEntity(UnprocessableEntityResponse.Message(result.Errors)));
        }
        public void Login_Validation_ShouldValidate(string username, string password, bool valid)
        {
            LoginInputModel loginInput = new LoginInputModel {
                Username = username,
                Password = password
            };

            LoginValidator validator = new LoginValidator();

            ValidationResult result = validator.Validate(loginInput);

            result.IsValid.Should().Be(valid);
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Authenticate([FromForm] LoginViewModel model)
        {
            LoginValidator validator = new LoginValidator(_userManager);
            var            results   = validator.Validate(model);

            if (!results.IsValid)
            {
                TempData[TextConstants.TempDataErrorText] = ValidatorHelper.GetErrorString(results.Errors);
                return(RedirectToAction("Index", "Home"));
            }

            TempData.Remove(TextConstants.TempDataErrorText);
            await Authenticate(model.Username, model.KeepLoggedIn);

            return(RedirectToAction("Index", "Home"));
        }
Exemple #8
0
        public async Task <IActionResult> Login(LoginViewModel login, string returnUrl)
        {
            var validator        = new LoginValidator();
            var validationResult = validator.Validate(login);

            if (validationResult.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(login.Email);

                if (user != null)
                {
                    await _signInManager.SignOutAsync();

                    var result = await _signInManager
                                 .PasswordSignInAsync(user, login.Password, login.RememberMe, false);

                    if (result.Succeeded)
                    {
                        var roles = await _userManager.GetRolesAsync(user);

                        if (roles.Any(r => r == "Admin"))
                        {
                            var url = string.IsNullOrEmpty(returnUrl)
                                ? Url.Action("Index", "Home", new { area = "Admin" })
                                : returnUrl;
                            return(Redirect(url));
                        }

                        return(Redirect(string.IsNullOrEmpty(returnUrl)
                                ? Url.Action("Index", "Home")
                                : returnUrl));
                    }
                }

                validationResult.Errors
                .Add(new ValidationFailure(nameof(LoginViewModel.Email), "Invalid user or password"));
            }

            var model = new MultiFormViewModel();

            foreach (var error in validationResult.Errors)
            {
                model.ValidationErrors.Add(error.ToString());
            }

            return(View("Login-register-forms", model));
        }
        public void Should_ReturnFalse_WhenRequiredInfo_IsNotProvided(string email, string password)
        {
            // Arrange
            var loginDto = new LoginDto()
            {
                Email    = email,
                Password = password
            };

            var loginValidator = new LoginValidator();

            // Act
            var validatorResult = loginValidator.Validate(loginDto);

            // Assert
            validatorResult.IsValid.ShouldBeFalse();
        }
        public void Should_ReturnTrue_WhenRequiredInfo_IsProvided()
        {
            // Arrange
            var loginDto = new LoginDto
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var loginValidator = new LoginValidator();

            // Act
            var validatorResult = loginValidator.Validate(loginDto);

            // Assert
            validatorResult.IsValid.ShouldBeTrue();
        }
Exemple #11
0
        public async Task <IActionResult> Login([FromBody] UserLoginApiModel model)
        {
            var validator   = new LoginValidator(_recaptcha, _resourceManager);
            var validResult = validator.Validate(model);

            if (!validResult.IsValid)
            {
                return(BadRequest(new MessageApiModel()
                {
                    Message = validResult.ToString()
                }));
            }

            var loginResult = await _accountService.LoginUserAsync(model);

            return(Ok(loginResult));
        }
Exemple #12
0
        public GenericOperationResult <LoginReturnDto> LoginUser(LoginDto user)
        {
            var result         = new GenericOperationResult <LoginReturnDto>();
            var loginValidator = new LoginValidator();
            var valid          = loginValidator.Validate(user);

            if (!valid.IsValid)
            {
                result.Messages = valid.Errors.Select(e => e.ErrorMessage).ToList();
                result.Status   = OperationResultStatusEnum.Validation;
                return(result);
            }
            var loggedUser = unitOfWork.Authentication.Login(user.UserName, user.Password);

            if (loggedUser == null)
            {
                result.Messages.Add("Username or password are incorrect");
                result.Status = OperationResultStatusEnum.Exception;
                return(result);
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, loggedUser.Id.ToString()),
                new Claim(ClaimTypes.Name, loggedUser.UserName),
            };
            var key             = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("Token:Secrete").Value));
            var credentials     = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(2),
                SigningCredentials = credentials
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            result.Data = new LoginReturnDto {
                Token = tokenHandler.WriteToken(token)
            };
            result.Status = OperationResultStatusEnum.Succeeded;

            return(result);

            ;
        }
Exemple #13
0
        public ResultModel <Login> Kontrol(Login p)
        {
            LoginValidator validator = new LoginValidator();
            var            result    = validator.Validate(p);

            if (result.IsValid)
            {
                return(new ResultModel <Login>
                {
                    Errors = null,
                    IsValid = true,
                    Message = "Kayıt Başarılı"
                });
            }
            return(new ResultModel <Login>
            {
                Errors = result.Errors.Select(x => x.ErrorMessage).ToList(),
                IsValid = false,
                Message = "Giriş Başarısız"
            });
        }
Exemple #14
0
        public ActionResult Login(Czytelnik czytelnik, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                List <string> errors      = new List <string>();
                var           currentuser = db.Czytelnik.Where(user => user.Uzytkownik.Equals(czytelnik.Uzytkownik) && user.Haslo.Equals(czytelnik.Haslo)).FirstOrDefault();
                if (currentuser != null)
                {
                    LoginValidator   validator = new LoginValidator();
                    ValidationResult result    = validator.Validate(currentuser);

                    if (!result.IsValid)
                    {
                        foreach (ValidationFailure vf in result.Errors)
                        {
                            errors.Add(vf.ErrorMessage);
                        }
                        ViewBag.Error = errors;
                        return(View(czytelnik));
                    }


                    FormsAuthentication.SetAuthCookie(currentuser.ID.ToString(), false);
                    Session["UserID"]   = currentuser.ID.ToString();
                    Session["UserRole"] = currentuser.Rola.ToString();
                    if (!string.IsNullOrEmpty(ReturnUrl))
                    {
                        return(Redirect(ReturnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Ksiazki"));
                    }
                }
                errors.Add("Nieprawidłowy login lub hasło");
                ViewBag.Error = errors;
            }

            return(View(czytelnik));
        }
Exemple #15
0
        public IActionResult Login([FromBody] Login login)
        {
            LoginValidator rules = new LoginValidator();

            var result = rules.Validate(login);

            if (!result.IsValid)
            {
                return(BadRequest(result.Errors));
            }

            var usuario = _repository.Login(login.Email, login.Senha);

            if (usuario == null)
            {
                return(Unauthorized());
            }
            else
            {
                return(Ok(usuario));
            }
        }
Exemple #16
0
        public async Task <JsonResult> Login([FromBody] LoginViewModel loginViewModel)
        {
            var response = new TokenViewModel();

            var validator       = new LoginValidator();
            var validatorResult = validator.Validate(loginViewModel);

            if (validatorResult.IsValid)
            {
                var user        = serviceOfAccount.Get(a => a.UserName == loginViewModel.Login);
                var correctUser = await userManager.CheckPasswordAsync(user, loginViewModel.Password);

                if (!correctUser)
                {
                    response.Errors = new List <string>();
                    (response.Errors as List <string>).Add("Username or password is incorrect!");
                    return(Json(response));
                }

                IList <string> roles = await userManager.GetRolesAsync(user);

                var claims = new List <Claim>
                {
                    new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName),
                    new Claim(ClaimsIdentity.DefaultRoleClaimType, roles.FirstOrDefault()),
                    new Claim("UserId", user.Id)
                };

                response.Token = _tokenService.BuildToken(user.Email, claims);
            }
            else
            {
                response.Errors = validatorResult.Errors.Select(a => a.ErrorMessage).ToList();
            }
            return(Json(response));
        }
Exemple #17
0
        public HttpResponseMessage GetUser([FromBody] LoginView loginView)

        {
            List <string>   errorlist       = null;
            UserDetailsView userDetailsView = null;
            int             code            = (int)HttpStatusCode.OK;

            try
            {
                LoginValidator   validator           = new LoginValidator();
                ValidationResult results             = validator.Validate(loginView);
                bool             validationSucceeded = results.IsValid;
                if (validationSucceeded)
                {
                    Userservice userservice = new Userservice();
                    userDetailsView = userservice.GetUserWithDogs(loginView.UserEmail, loginView.UserPassword);
                    if (userDetailsView != null)
                    {
                        code = (int)HttpStatusCode.OK;
                    }
                    else
                    {
                        code = (int)HttpStatusCode.BadRequest;
                    }


                    //  return Ok();
                }
                else
                {
                    code = (int)HttpStatusCode.BadRequest;

                    errorlist = new List <string>();
                    foreach (var value in results.Errors)
                    {
                        errorlist.Add(value.ErrorCode);
                        //errorlist.Add(value.Errors);
                    }
                    //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errorlist);
                    //IList<ValidationFailure> failures = results.Errors;
                    //List<string> errorlist = new List<string>();
                    //foreach (ValidationFailure _error in failures)
                    //{
                    //    ModelState.AddModelError(_error.PropertyName, _error.ErrorMessage);
                    //    //foreach (var error in value.Errors)
                    //    //  errorlist.Add(value.ErrorMessage);
                    //    //errorlist.Add(value.Errors);
                    //}
                    //   return
                    //  return new System.Web.Http.Controllers.HttpActionContext()
                    //HttpActionContext actionContext = new HttpActionContext();


                    // ThrowResponseException(HttpStatusCode.NotAcceptable, errorlist);
                }
                if ((HttpStatusCode)code == HttpStatusCode.OK)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, userDetailsView));
                }
                else
                {// return Request.CreateResponse(HttpStatusCode.BadRequest, errorlist);
                    return(Request.CreateResponse(code));
                }
            }

            catch
            {
                bool x = ModelState.IsValid;
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
        //  [ValidateAntiForgeryToken]
        public JsonResult Login(LoginViewModel model)
        {
            LoginValidator   validationRules  = new LoginValidator();
            ValidationResult validationResult = validationRules.Validate(model);

            if (!validationResult.IsValid)
            {
                IList <ValidationFailure> failures = validationResult.Errors;
                return(Json(new { code = -1, url = "", msg = "数据不合法" }));
            }

//            if (!ModelState.IsValid)
//            {
//                //  return View(model);
//                return Json(new { code = -1, url = "", msg = "数据不合法" });
//            }
            if (model.UserCode.Trim() == "admin" && model.Password.Trim() == "pass")
            {
                var authTicket = new FormsAuthenticationTicket(1, model.UserCode, DateTime.Now,
                                                               DateTime.Now.AddMinutes(20), false, JsonConvert.SerializeObject(new T_Sys_Role {
                    usercode = "admin", role = "123"
                }));

                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
                {
                    HttpOnly = true,
                    Secure   = FormsAuthentication.RequireSSL,
                    Domain   = FormsAuthentication.CookieDomain,
                    Path     = FormsAuthentication.FormsCookiePath,
                    Expires  = DateTime.Now.AddMinutes(20)
                };
                //客户端脚本不能访问
                //是否仅用https传递cookie
                //与cookie关联的域
                //cookie关联的虚拟路径
                HttpContext context = System.Web.HttpContext.Current;
                if (context == null)
                {
                    throw new InvalidOperationException();
                }

                // 5. 写登录Cookie
                context.Response.Cookies.Remove(authCookie.Name);
                context.Response.Cookies.Add(authCookie);
                Response.Cookies.Add(authCookie);
                //HttpContext.User = new MyFormsPrincipal<T_Sys_User>(authTicket, new T_Sys_User() { UserCode = model.UserCode });
                //FormsAuthentication.SetAuthCookie(model.UserCode, true);

                //                if (Url.IsLocalUrl(returnUrl))
                //                {
                //                    return Redirect(returnUrl);
                //                }

                //  return RedirectToAction("Index", new RouteValueDictionary(new { controller = "Home", action = "Index" }));
                System.Web.HttpContext.Current.Session["user_account"] = new T_Sys_User {
                    UserCode = "admin"
                };
                return(Json(new { code = 0, url = "/Home/IndexNew", msg = "" }));
            }
            else
            {
                var pwd = Encryptor.Md5Hash(model.Password);
                //根据用户登录名查询指定用户实体
                var user = UserBll.LoadEntities(t => t.UserCode == model.UserCode && t.Password == pwd).FirstOrDefault();

                //如果用户不存在,则携带错误消息并返回登录页面
                if (user == null)
                {
                    //ModelState.AddModelError("error_message", "用户不存在");
                    //return View(model);
                    return(Json(new { code = "-1", url = "", msg = "用户不存在" }));
                }

                //如果密码不匹配,则携带错误消息并返回登录页面
                if (user.Password != Encryptor.Md5Hash(model.Password.Trim()))
                {
                    //                    ModelState.AddModelError("error_message", "密码错误,请重新登录");
                    //                    return View(model);
                    return(Json(new { code = "-2", url = "", msg = "密码错误,请重新登录" }));
                }
                FormsAuthentication.SetAuthCookie(user.UserCode, true);
                //将用户实体保存到Session中
                System.Web.HttpContext.Current.Session["user_account"] = user;
                return(Json(new { code = 0, url = "/Home/IndexNew", msg = "" }));
            }

            // return View();
            //return Json(new { code = "-3", url = "", msg = "请检查录入的数据" });
        }
        public ActionResult Login(LoginModel model, string returnUrl, string rememberme)
        {
            ModelState.Remove("AttemptCount");
            if (model.AttemptCount <= 1)
            {
                ModelState["CaptchaInputText"].Errors.Clear();
            }
            model.AttemptCount = model.AttemptCount + 1;
            FluentValidation.IValidator <LoginModel> validator = new LoginValidator();
            var validationResults = validator.Validate(model);

            foreach (var item in validationResults.Errors)
            {
                ModelState.AddModelError(item.PropertyName, item.ErrorMessage);
            }
            if (ModelState.IsValid)
            {
                model.Username = model.Username.Trim();
                model.Password = model.Password.Trim();

                try
                {
                    UserApiResult result = _webClient.UploadData <UserApiResult>("logincloud", model);
                    int           status = result.Status;
                    switch (status)
                    {
                    case 1:
                        var customer = result.User;
                        customer.SchoolId = result.User.SchoolId;
                        _authService.SignIn(customer, rememberme != null?true:false);
                        model.IsAuthenticated = true;
                        if (customer.Role.Equals("schooladmin", StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(RedirectToRoute("SchoolAdmin", new { schooluid = customer.SchoolUId }));
                        }
                        if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                        {
                            return(RedirectToRoute("HomePage"));
                        }

                        return(Redirect(returnUrl));

                    case 3:
                        ModelState.AddModelError("", Resource.PopupLogin_NoAccountError);
                        model.HasError = true;
                        break;

                    case 4:
                        ModelState.AddModelError("", Resource.PopUpLogin_wrongCredentials);
                        model.HasError = true;
                        break;

                    case 6:
                        ModelState.AddModelError("", Resource.Login_Accnotactive);
                        model.HasError = true;
                        break;

                    case 7:
                        ModelState.AddModelError("", Resource.Login_Accdisabled);
                        model.HasError = true;
                        break;

                    case 8:
                        ModelState.AddModelError("", Resource.Login_StudentsNotAllowedlogin);
                        model.HasError = true;
                        break;

                    default:
                        ModelState.AddModelError("", Resource.PopUpLogin_unknownError);
                        model.HasError = true;
                        break;
                    }
                }
                catch (WebException)
                {
                    ModelState.AddModelError("", Resource.PopUpLogin_NetError);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            return(View(model));
        }
Exemple #20
0
        public ValidationResult GetValidationResult(LoginActor model)
        {
            var validator = new LoginValidator(_repository);

            return(validator.Validate(model));
        }
Exemple #21
0
        private async void SignIn()
        {
            if (View != null)
            {
                View.HideKeyboard();
            }

            LoginValidator validator = new LoginValidator();

            Login login = new Login
            {
                Email    = Email,
                Password = Password,
            };

            var result = validator.Validate(login);

            if (result.IsValid)
            {
                mPlatformService.ShowNetworkIndicator();
                mProgressDialogService.ShowProgressDialog();

                var response = await mApiService.PostLogin(login.Email, login.Password);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var userData = response.Data;
                    mCacheService.CurrentUserData = userData;
                    mApiService.UseBeaerToken     = true;

                    // get user key

                    //mPlatformService.ShowNetworkIndicator();
                    //mProgressDialogService.ShowProgressDialog();

                    var response2 = await mApiService.PostSession(mPlatformService.GetDeviceUDID(), userData.UserName);

                    //mPlatformService.HideNetworkIndicator();
                    //mProgressDialogService.HideProgressDialog();

                    if (response2.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        userData.UserKey = response2.Data;
                        mCacheService.CurrentUserData = userData;

                        await GetProfile();

                        ShowViewModel <MainViewModel>();
                    }
                    else
                    {
                        mApiService.UseBeaerToken = false;
                    }
                }
                else
                {
                    mPlatformService.HideNetworkIndicator();
                    mProgressDialogService.HideProgressDialog();

                    if (!string.IsNullOrEmpty(response.ErrorData))
                    {
                        string             errorData = response.ErrorData;
                        ErrorLoginResponse err       = JsonConvert.DeserializeObject <ErrorLoginResponse>(errorData);
                        mMessageboxService.ShowToast(err.Description);
                    }
                }
            }
            else if (result.Errors != null)
            {
                var firstError = result.Errors.First();
                mMessageboxService.ShowToast(firstError.ErrorMessage);
            }
        }