Esempio n. 1
0
        public void CheckUserAuthorizationTest()
        {
            //Arrange
            var userNotInDb = new UserWithPasswordModel
            {
                Email = "*****@*****.**",
                Password = "******"
            };
            var userInDb = new UserWithPasswordModel
            {
                Email = "*****@*****.**",
                Password = "******",
            };

            //Action
            Mock<IUserMapper> userMapper = new Mock<IUserMapper>();
            UserWithPasswordModel userModel = new UserWithPasswordModel();
            //UserService userService = new UserService(userMapper.Object);
            ////We need to get rid off dependency of DbManager to test correctly

            ////Remark:
            ////Now you must write your test, I got rid of dependency!!! azazaza (medyk)

            ////Assert
            //Assert.AreEqual(userService.CheckUserAuthorization(userInDb), true);
            //Assert.AreEqual(userService.CheckUserAuthorization(userNotInDb), true);
            //Assert.AreEqual(userInDb.Id, 1);
            //Assert.AreEqual(userInDb.Claim, new[] { "Teacher", "Student" });
        }
        public void MapToTokenModelTest()
        {
            const string email = "*****@*****.**";
            const int id = 1;
            const string hash = "HashToken";
            IEnumerable<string> roles = new[] {"Admin", "Student", "Teacher"};
            Mock<ITokenValidation> token = new Mock<ITokenValidation>();
            UserToTokenMapper mapper = new UserToTokenMapper(token.Object);

            var initial = new UserWithPasswordModel()
            {
                Email = email,
                Id = id,
                HashToken = hash,
                Roles = roles
            };
            var expected = new TokenModel()
            {
                EmailAndIdToken = email,
                RolesToken = roles.ToString(),
                HashToken = hash
            };

            token.Setup(x => x.EncodeEmailAndIdToken(id.ToString() + ' ' + email.ToLower()))
                .Returns(email);

            token.Setup(x => x.EncodeRoleToken(roles))
                .Returns(roles.ToString);

            var action = mapper.MapToTokenModel(initial);
            Assert.IsNotNull(action);
            Assert.AreEqual(action.EmailAndIdToken, expected.EmailAndIdToken);
            Assert.AreEqual(action.HashToken, expected.HashToken);
            Assert.AreEqual(action.RolesToken, expected.RolesToken);
        }
 public IHttpActionResult Post(UserWithPasswordModel userData)
 {
     if (_service.CheckUserAuthorization(userData))
     {
         return Ok(_mapUserToToken.MapToTokenModel(userData));
     }
     return Unauthorized();
 }
 public bool CheckUserAuthorization(UserWithPasswordModel userLoginApi)
 {
     using (var uow = _unitOfWorkFactory.GetUnitOfWork())
     {
         var user = uow.UserRepository.GetAll().FirstOrDefault(u => ((u.Email).ToLower() == (userLoginApi.Email).ToLower()));
         if ((user != null) && (VerifyPasswords(user.Password, userLoginApi.Password)))
         {
             userLoginApi.Id = user.Id;
             userLoginApi.Roles = user.Roles.Select(x => x.Name);
             user.HashedToken = _token.Sha256Hash(_token.RandomString(ConstContainer.HashLength));
             userLoginApi.HashToken = user.HashedToken;
             uow.UserRepository.AddOrUpdate(user);
             uow.Save();
             return true;
         }
         return false;
     }
 }
        public void LoginControllerPostMethodTest()
        {
            //Arrange
            var userNotInDb = new UserWithPasswordModel
            {
                Email = "*****@*****.**",
                Password = "******"
            };
            var userInDb = new UserWithPasswordModel
            {
                Email = "*****@*****.**",
                Password = "******",
                Roles = new[] { "Student", "Teacher" }
            };
            var userWithoutEmail = new UserWithPasswordModel
            {
                Email = null,
                Password = "******"
            };

            //Action
            Mock<IUserService> userService = new Mock<IUserService>();
            Mock<IUserToTokenMapper> tokenMaper = new Mock<IUserToTokenMapper>();
            GenericIdentity identity = new GenericIdentity("1");
            Thread.CurrentPrincipal =
                new GenericPrincipal(
                    identity,
                    new[] { "NoRoles" }
                    );
            LoginController loginController = new LoginController(userService.Object, tokenMaper.Object);

            userService
                .Setup(x => x.CheckUserAuthorization(userWithoutEmail))
                .Returns(false);

            IHttpActionResult unauthorizedResult = loginController.Post(userNotInDb);
            var actionUnauthorizedResult = unauthorizedResult as UnauthorizedResult;
            unauthorizedResult = loginController.Post(userWithoutEmail);
            var actionUnauthorizedRequestEmail = unauthorizedResult as UnauthorizedResult;

            userService
                .Setup(x => x.CheckUserAuthorization(userInDb))
                .Returns(true);

            tokenMaper
                .Setup(x => x.MapToTokenModel(userInDb))
                .Returns(new TokenModel()
                {
                    RolesToken = "Claim token",
                    EmailAndIdToken = "Email and password token"
                });

            IHttpActionResult authorizedResult = loginController.Post(userInDb);
            var actionAuthorizedResult = authorizedResult as OkNegotiatedContentResult<TokenModel>;

            IHttpActionResult badRequestResult = loginController.Post(null);
            var actionBadRequest = badRequestResult as BadRequestResult;

            //Assert
            Assert.IsNotNull(actionUnauthorizedRequestEmail);
            Assert.IsNotNull(actionBadRequest);
            Assert.IsNotNull(actionUnauthorizedResult);
            Assert.IsNotNull(actionAuthorizedResult);
            var authorizedContent = actionAuthorizedResult.Content;
            Assert.IsNotNull(actionAuthorizedResult.Content);
            Assert.AreEqual(authorizedContent.RolesToken, "Claim token");
        }
        [Test] //+
        public void CheckUserAuthorization_IsTrue_Test()
        {
            //Arrange
            UserWithPasswordModel userLoginApi = new UserWithPasswordModel();
            PasswordHasher passHesher = new PasswordHasher();

            User user = new User();
            user.Email = entity.Email;
            user.Id = 4;
            user.Roles = new List<Role> { new Role() { Name = "admin", Id = user.Id } };

            userLoginApi.Password = "******";
            userLoginApi.Email = user.Email;
            string userPassword = passHesher.HashPassword(userLoginApi.Password);
            user.Password = userPassword;

            IQueryable<User> Users = new List<User>
            {
                user
            }.AsQueryable<User>();

            worldOfWordsUow.Setup(t => t.UserRepository).Returns(userReposit.Object);
            userReposit.Setup(t => t.GetAll()).Returns(Users);
            userReposit.Setup(t => t.AddOrUpdate(It.IsAny<User>())).Verifiable("added or updated");
            worldOfWordsUow.Setup(t => t.Save()).Verifiable("Saved");

            //Act
            var result = usServ.CheckUserAuthorization(userLoginApi);

            //Assert
            uowFactory.Verify(f => f.GetUnitOfWork(), Times.Once);
            worldOfWordsUow.Verify(t => t.UserRepository, Times.Exactly(2));
            userReposit.Verify(t => t.AddOrUpdate(It.IsAny<User>()), Times.Once);
            worldOfWordsUow.VerifyAll();
            Assert.IsTrue(result);
        }
Esempio n. 7
0
 public bool CheckUserAuthorization(UserWithPasswordModel userLoginApi)
 {
     using (var context = new WorldOfWordsDatabaseContext())
     {
         var user = context.Users.FirstOrDefault(u => ((u.Email).ToLower() == (userLoginApi.Email).ToLower()));
         if ((user != null) && (VerifyPasswords(user.Password, userLoginApi.Password)))
         {
             userLoginApi.Id = user.Id;
             userLoginApi.Roles = user.Roles.Select(x => x.Name);
             user.HashedToken = _token.Sha256Hash(_token.RandomString(ConstContainer.HashLength));
             userLoginApi.HashToken = user.HashedToken;
             context.Users.AddOrUpdate(user);
             context.SaveChanges();
             return true;
         }
         return false;
     }
 }