コード例 #1
0
        public JsonResult UserLogin(UserLoginViewModel model)
        {
            var validator        = new UserLoginValidator();
            var validationResult = validator.Validate(model);
            var result           = new LoginSuccessResult();

            if (validationResult.Valid)
            {
                var user = DataAccessLayer.Users.FirstOrDefault(u => u.Email.Equals(model.UserEmail));
                if (user != null)
                {
                    Session[SessionKeys.UserId] = user.Id;
                    result.Status  = HttpStatusCode.Accepted;
                    result.Message = "Login successful.";
                    result.UserId  = user.Id;

                    return(result);
                }
            }

            result.Status  = HttpStatusCode.NotAcceptable;
            result.Message = validationResult.Messages.ToString();

            return(result);
        }
コード例 #2
0
        public void Validate_WhenPasswordNotEntered_ReturnsInvalidResult()
        {
            //Given
            UserLoginValidator validator = new UserLoginValidator();
            UserLoginModel     model     = new UserLoginModel()
            {
                Username = "******"
            };
            //When
            ValidationResult result = validator.Validate(model);

            //Then
            Assert.False(result.IsValid);
        }
コード例 #3
0
        public void Validate_WhenUserNameAndPasswordArePresent_ReturnsValidResult()
        {
            //Given
            UserLoginValidator validator = new UserLoginValidator();
            UserLoginModel     model     = new UserLoginModel()
            {
                Username = "******",
                Password = "******"
            };
            //When
            ValidationResult result = validator.Validate(model);

            //Then
            Assert.True(result.IsValid);
        }
コード例 #4
0
        public IActionResult Login(UserLoginModel userLoginModel)
        {
            var validator = new UserLoginValidator();

            if (validator.Validate(userLoginModel).IsValid)
            {
                var accountBL = new AccountBL(_uow, _mapper);
                if (accountBL.Login(userLoginModel))
                {
                    return(RedirectToAction("AccountPage"));
                }
            }
            ModelState.AddModelError(nameof(userLoginModel.Email), "Invalid user or password");
            return(RedirectToAction("Login"));
        }
コード例 #5
0
        public IActionResult Login([FromBody] User currentUser)
        {
            UserLoginValidator validator = new UserLoginValidator();
            var result = validator.Validate(currentUser);

            if (result.IsValid)
            {
                var loggedInUser = _userService.Login(currentUser.Email, currentUser.Password);
                if (loggedInUser == null)
                {
                    return(Ok(this._sendIncorrectLoginMessage()));
                }
                //Use Session later when project is finished
                //HttpContext.Session.SetInt32("UserId", loggedInUser.Id);
                return(Ok(loggedInUser));
            }

            var errors = result.Errors;

            return(Ok(errors));
        }
コード例 #6
0
        public IActionResult Login([FromBody] UserLoginDTO userLoginDto)
        {
            User user = db.Users.Include(x => x.ProfilePhotos).FirstOrDefault(x => x.Email == userLoginDto.Email && x.IsDeleted == false);

            if (user == null)
            {
                return(Json(new { statusCode = ResponseStatus.ValidationError, responseMessage = ValidationMessages.IncorrectEmailOrPassword }));
            }
            UserLoginValidator validator = new UserLoginValidator(db, user);
            var result = validator.Validate(userLoginDto);

            if (!result.IsValid)
            {
                return(Json(new { statusCode = ResponseStatus.ValidationError, responseMessage = result.Errors }));
            }
            userData.SetUser(HttpContext, user);
            List <Actions> actions = db.RoleActions.Where(s => s.RoleId == user.RoleId).Select(s => s.Action).ToList();

            userData.SetActions(HttpContext, actions);
            return(Json(new { statusCode = ResponseStatus.Success }));
        }
コード例 #7
0
ファイル: UserService.cs プロジェクト: bezotosnyi/Chat
        public OperationStatusInfo <UserDTO> Login(UserLoginDTO userLoginDto)
        {
            this.loggingService.Info($"Попытка входа пользователя {userLoginDto} в систему.");

            // валидация
            var validator        = new UserLoginValidator();
            var validationResult = validator.Validate(userLoginDto);

            // проверка валидации
            if (!validationResult.IsValid)
            {
                return(this.operationStatusService.HandleValidationError <UserDTO>(
                           $"Ошибка при валидации идентификационных данных: {userLoginDto}. Текст ошибки: {validationResult}",
                           null));
            }

            try
            {
                var loginUser = DTOService.ToEntity <UserLoginDTO, User>(userLoginDto);
                var user      = this.currentRepository.Get(
                    new List <Expression <Func <User, bool> > >
                {
                    u => u.Login == loginUser.Login && u.Password == loginUser.Password
                }).FirstOrDefault();

                // проверка существует ли пользователь
                return(user != null
                           ? this.operationStatusService.HandleSuccessOperation(
                           $"Пользователь {loginUser.Login} успешно идентифицирован.",
                           DTOService.ToDTO <User, UserDTO>(user))
                           : this.operationStatusService.HandleErrorOperation <UserDTO>(
                           $"Пользователя {loginUser.Login} не существует.", null));
            }
            catch (Exception exception)
            {
                return(this.operationStatusService.HandleException <UserDTO>(exception, null));
            }
        }
コード例 #8
0
        public ApiResponse Login(User info)
        {
            try
            {
                var validator = new UserLoginValidator();
                var result    = validator.Validate(info);

                if (result.IsValid)
                {
                    info.Password = StringCipher.Encrypt(info.Password, passPhrase);

                    User user = dacMgr.Select(info.Email);

                    if (user != null)
                    {
                        if (user.Status == NUserStatus.Active.GetStrValue())
                        {
                            if (info.Password == user.Password)
                            {
                                response.Success = true;
                                logMgr.Info(info.Email + " successfully login");
                            }
                            else
                            {
                                response.ErrorList.Add(new Error {
                                    Message = "Invalid email and password"
                                });
                                logMgr.Info(info.Email + " fails to login");
                            }
                        }
                        else if (user.Status == NUserStatus.ChangePassword.GetStrValue())
                        {
                            if (info.Password == user.Password)
                            {
                                info.UpdatedDate  = DateTime.UtcNow;
                                info.Password     = StringCipher.Encrypt(info.Password, passPhrase);
                                info.Status       = NUserStatus.Active.GetStrValue();
                                info.TempPassword = string.Empty;

                                dacMgr.Update(info);

                                response.Success = true;
                            }
                            else if (info.Password == user.TempPassword)
                            {
                                response.ErrorList.Add(new Error {
                                    Code = "Required_Password_Change"
                                });
                                response.Success = true;
                            }
                        }
                    }
                    else
                    {
                        response.ErrorList.Add(new Error {
                            Message = "Invalid email and password"
                        });
                    }
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        response.ErrorList.Add(new Error {
                            Message = error.PropertyName + error.ErrorMessage
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ErrorList.Add(new Error {
                    Message = "Internal Server Error Code:500"
                });

                logMgr.Error(ex);
            }

            return(response);
        }
コード例 #9
0
ファイル: UserMgr.cs プロジェクト: wjkong/OnlineStore.API
        public ApiResponse Login(User info)
        {
            try
            {
                var validator = new UserLoginValidator();
                var result = validator.Validate(info);

                if (result.IsValid)
                {
                    info.Password = StringCipher.Encrypt(info.Password, passPhrase);

                    User user = dacMgr.Select(info.Email);

                    if (user != null)
                    {
                        if (user.Status == NUserStatus.Active.GetStrValue())
                        {
                            if (info.Password == user.Password)
                            {
                                response.Success = true;
                                logMgr.Info(info.Email + " successfully login");
                            }
                            else
                            {
                                response.ErrorList.Add(new Error { Message = "Invalid email and password" });
                                logMgr.Info(info.Email + " fails to login");
                            }
                        }
                        else if (user.Status == NUserStatus.ChangePassword.GetStrValue())
                        {
                            if (info.Password == user.Password)
                            {
                                info.UpdatedDate = DateTime.UtcNow;
                                info.Password = StringCipher.Encrypt(info.Password, passPhrase);
                                info.Status = NUserStatus.Active.GetStrValue();
                                info.TempPassword = string.Empty;

                                dacMgr.Update(info);

                                response.Success = true;
                            }
                            else if (info.Password == user.TempPassword)
                            {
                                response.ErrorList.Add(new Error { Code = "Required_Password_Change" });
                                response.Success = true;
                            }
                        }
                    }
                    else
                    {
                        response.ErrorList.Add(new Error { Message = "Invalid email and password" });
                    }
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        response.ErrorList.Add(new Error { Message = error.PropertyName + error.ErrorMessage });
                    }
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ErrorList.Add(new Error { Message = "Internal Server Error Code:500" });

                logMgr.Error(ex);
            }

            return response;
        }