public UserAuthenticateResponseModel AuthenticateUser(UserAuthenticateRequestModel model)
        {
            // validation
            var results = _userValidator.Validate(model).ToArray();

            if (results.Length > 0)
            {
                throw new ValidationApiException(results);
            }

            // get the user from the repository / database
            var entity = _repo.GetUsers().SingleOrDefault(user => user.Email == model.Email && user.Password == model.Password);

            // throw unathorized exception if user doesn't exist
            if (entity == null)
            {
                throw new UnauthorizedApiException("Username or password is incorrect");
            }

            if (entity.Locked)
            {
                throw new UnauthorizedApiException("Account is locked");
            }

            // authentication successful so generate jwt token
            var token = GenerateJwtToken(entity.Id);

            //return the UserAuthenticateResponseModel to the controller
            return(_userMapper.AuthenticateMapper(entity, token));
        }
        public void Validate_InvalidUserName_ReturnsFailure(string userName)
        {
            UserModel model = DataHelper.CreateUserModel();

            model.UserName = userName;

            ValidationResult result = _userValidator.Validate(model);

            Assert.IsFalse(result.Success);
            Assert.AreEqual(1, result.Messages.Count);
            Assert.IsTrue(result.Messages[0].Contains("User name"));
        }
示例#3
0
        public async Task <UserView> Insert(UserDto dto)
        {
            var reg = new User();

            new UserMapper().Map(reg, dto);

            _userValidator.Validate(reg);

            await Context.Users.AddAsync(reg);

            await Context.SaveChangesAsync();

            return(UserView.New(reg));
        }
        public void Execute_ValidationFails_ThrowsException()
        {
            UserModel model = DataHelper.CreateUserModel();

            _userValidator.Validate(Arg.Any <UserModel>()).Returns(new ValidationResult("error"));

            // execute
            TestDelegate del = () => _createUserCommand.Execute(model.UserName, model.Password, model.Role);

            // assert
            Assert.Throws <ValidationException>(del);

            // we shouldn't have even tried to do the insert
            _dbContext.DidNotReceive().ExecuteNonQuery(Arg.Any <string>(), Arg.Any <object>());
            _passwordProvider.DidNotReceive().HashPassword(Arg.Any <string>(), Arg.Any <string>());
        }
        public void UpsertUser(string token, UserDto dto)
        {
            var userId = _auth.Authorize(token);

            if (userId == null)
            {
                throw new AuthException("Unauthorized");
            }

            try
            {
                // LSP demo
                var validResults = _validator.Validate(dto).ToList();
                validResults.ForEach(result => result.ThrowIfFail());
            }
            catch (ValidationException e)
            {
                _logger.Log($"Validation failed : {e.Message}");
                throw;
            }

            var user = dto.ToUser(userId);

            _storage.UpsetUser(user);
        }
示例#6
0
        protected override HttpRequestMessage OnHandle(HttpRequestMessage input)
        {
            var authorizationHeader = input.Headers.Authorization;

            if (authorizationHeader != null)
            {
                byte[] encodedDataAsBytes = Convert.FromBase64String(authorizationHeader.Parameter);
                string value    = Encoding.ASCII.GetString(encodedDataAsBytes);
                string username = value.Substring(0, value.IndexOf(':'));
                string password = value.Substring(value.IndexOf(':') + 1);

                if (validator.Validate(username, password))
                {
                    return(input);
                }
            }

            var unauthorizedResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);

            unauthorizedResponse.Headers.WwwAuthenticate.Add(new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", "realm=\"My Server\""));
            unauthorizedResponse.Content = new StringContent("401, please authenticate");

            // Get the client to prompt for credentials
            throw new HttpResponseException(unauthorizedResponse);
        }
示例#7
0
        public UserModel Execute(string userName, string password, string role)
        {
            UserModel user = new UserModel();

            user.UserName = userName;
            user.Password = password;
            user.Role     = role;

            // validate before we try to hash the password
            ValidationResult result = _userValidator.Validate(user);

            if (!result.Success)
            {
                throw new ValidationException(result.Messages);
            }

            // hash the password
            user.Password = _passwordProvider.HashPassword(password, _passwordProvider.GenerateSalt());

            // insert new record
            string sql = @"INSERT INTO Users (Id, UserName, Password, Role) VALUES (@Id, @UserName, @Password, @Role)";

            _dbContext.ExecuteNonQuery(sql, user);

            return(user);
        }
示例#8
0
    private static bool TryGetPrincipal(string authHeader,
                                        IUserValidator validator, out IPrincipal principal)
    {
        var protocolParts = authHeader.Split(' ');

        if (protocolParts.Length != 2)
        {
            principal = null;
            return(false);
        }
        else if (protocolParts[0] == "Basic")
        {
            var parameter = Encoding.UTF8.GetString(
                Convert.FromBase64String(protocolParts[1]));
            var parts = parameter.Split(':');

            if (parts.Length != 2)
            {
                principal = null;
                return(false);
            }
            var username = parts[0];
            var password = parts[1];
            principal = validator.Validate(username, password);
            return(principal != null);
        }
        else
        {
            principal = null;
            return(false);
        }
    }
        public bool Persist(IUserValidator validator)
        {
            bool bValid = validator.Validate(this);

            if(bValid) bValid = this.Gateway.Persist(this);

            return bValid;
        }
        public void Save_AuthTest()
        {
            // setup
            var currentUser = new UserIdentity()
            {
                Id = Guid.NewGuid(), UserName = "******"
            };
            var browser = new Browser((bootstrapper) =>
                                      bootstrapper.Module(new UserModule(_userStore, _userValidator, _passwordProvider))
                                      .RequestStartup((container, pipelines, context) => {
                context.CurrentUser = currentUser;
            })
                                      );

            _userStore.Users.Returns(new List <UserModel>()
            {
            });
            _userValidator.Validate(Arg.Any <UserModel>()).Returns(new ValidationResult());

            foreach (string claim in Claims.AllClaims)
            {
                currentUser.Claims = new string[] { claim };

                // execute
                var response = browser.Post(Actions.User.Save, (with) =>
                {
                    with.HttpRequest();
                    with.FormsAuth(currentUser.Id, new Nancy.Authentication.Forms.FormsAuthenticationConfiguration());
                    //with.FormValue("id", connectionId.ToString());
                });

                // assert
                if (claim == Claims.UserAdd)
                {
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                }
                else
                {
                    Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
                }
            }
        }
        public ServiceResult <bool> Create(TServiceUser user, string password)
        {
            ThrowIfDisposed();

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("password");
            }

            var errors = new List <string>();

            var userValidationResult = _userValidator.Validate(user);

            if (!userValidationResult.Valid)
            {
                errors.AddRange(userValidationResult.Errors);
            }

            var passwordValidation = _passwordValidator.Validate(password);

            if (!passwordValidation.Valid)
            {
                errors.AddRange(passwordValidation.Errors);
            }

            if (!string.IsNullOrWhiteSpace(user.Email) && _userRepository.Exists(u => u.Email.Trim().Equals(user.Email.Trim())))
            {
                errors.Add("Email address is already in use");
            }

            if (!string.IsNullOrWhiteSpace(user.UserName) && _userRepository.Exists(u => u.UserName.Trim().Equals(user.UserName.Trim())))
            {
                errors.Add("Username is already in use");
            }

            if (errors.Any())
            {
                return(ServiceResult <bool> .Error(errors.ToArray()));
            }

            var  repoUser = AutoMapper.Mapper.Map <TServiceUser, TRepositoryUser>(user);
            TKey id       = _userRepository.Create(repoUser);

            repoUser.Id = id;

            UpdatePasswordInternal(repoUser, password);
            return(new ServiceResult <bool> {
                Value = true, Succeeded = true
            });
        }
示例#12
0
        public void Delete_AuthTest()
        {
            // setup
            var currentUser = new UserIdentity()
            {
                Id = Guid.NewGuid(), UserName = "******"
            };
            var browser = new Browser((bootstrapper) =>
                                      bootstrapper.Module(new UserModule(_userRepo, _createUserCommand, _updateUserPasswordCommand, _deleteUserCommand))
                                      .RequestStartup((container, pipelines, context) => {
                context.CurrentUser = currentUser;
            })
                                      );

            _userRepo.GetAll().Returns(new List <UserModel>()
            {
            });
            _userValidator.Validate(Arg.Any <UserModel>()).Returns(new ValidationResult());

            TestHelper.ValidateAuth(currentUser, browser, Actions.User.Delete, HttpMethod.Post, Claims.UserDelete);
        }
示例#13
0
        public async Task <User> CreateUser(Registration registration)
        {
            _userValidator.ValidatePassword(registration.Password);

            var passwordHash = _passwordGuard.GeneratePasswordHash(registration.Password);

            var user = new User(
                UserLevel.User,
                registration.FirstName,
                registration.LastName,
                registration.Email.ToLower(),
                registration.BirthDate,
                DateTime.UtcNow,
                passwordHash);

            _userValidator.Validate(user);

            await _userRepository.Insert(user);

            return(user.WithoutPasswordHash());
        }
        public void TestRegistration(UserRequestDataModel userRequestMock, bool expectedResult, string expectedMessage)
        {
            //Arrange

            //Act
            var actualResult = _registerUserValidator.Validate(userRequestMock);

            //_output.WriteLine(JsonConvert.SerializeObject(actualResult));
            //Assert
            Assert.Equal(expectedResult, actualResult.IsValid);
            if (!string.IsNullOrEmpty(expectedMessage))
            {
                Assert.Contains(expectedMessage, actualResult.Errors.Select(x => x.ErrorMessage));
            }
        }
示例#15
0
 public override void Create(User pUser)
 {
     _userValidator.Validate(pUser);
     _userRepository.Create(pUser);
 }
 public ValidationResult Validate(UserRequestDataModel userRequest)
 {
     return(_validator.Validate(userRequest));
 }