コード例 #1
0
        public void TestMethod1()
        {
            var mock = new Mock <IUserAccountOrchestrator>();

            UserAccountController _UserAccountController = new UserAccountController(mock.Object);
            var result = _UserAccountController.Login("");
        }
コード例 #2
0
        public void AuthenticateValidCredentialsTest()
        {
            UserAccountController userController = CreateFakeUserAccountController();

            //Authenticate with valid credentials
            var response = userController.Authenticate(
                new ReceiveLoginUserModel(_users[0].Email, "password-u1")
                );

            Assert.IsType <OkObjectResult>(response.Result);

            //Validate return data from endpoint
            SendLoginUserModel sendLoginUserModel =
                (SendLoginUserModel)((OkObjectResult)response.Result).Value;

            Assert.Equal(_users[0].Id, sendLoginUserModel.Id);
            Assert.Equal(_users[0].Email, sendLoginUserModel.Email);

            TokenCreatorValidator tokenCreatorValidator = new TokenCreatorValidator(_testApiSecret);
            TokenValidationParams tokenValidationParams = tokenCreatorValidator.ValidateToken(sendLoginUserModel.Token);

            Assert.Equal(_users[0].Id, tokenValidationParams.UserId);

            User authenticatedUser = _usersService.GetById(_users[0].Id);

            Assert.Equal(
                Encoding.Default.GetString(authenticatedUser.AuthSalt),
                Encoding.Default.GetString(tokenValidationParams.SaltBytes)
                );
        }
コード例 #3
0
ファイル: Test04.cs プロジェクト: EmoKosov/BankingProject
        public void GetAccounts_ShouldReturnFirstAccountsInDatabase()
        {
            DateTime date = DateTime.UtcNow;
            var      data = new List <UserAccount>()
            {
                new UserAccount(1, "Georgi Georgiev", "11/06/2000", "0878444484", "bul Bulgaria 4", "Smolyan", "Smolyan", "Male", "married",
                                null, null, 7500, date.ToString()),
                new UserAccount(2, "Ivan Ivanov", "22/11/2001", "0878171711", "bul Bulgaria 3", "Smolyan", "Smolyan", "Male", "married",
                                null, null, 5000, date.ToString())
            }.AsQueryable();
            var mockSet = new Mock <DbSet <UserAccount> >();

            mockSet.As <IQueryable <UserAccount> >().Setup(m => m.Provider).Returns(data.Provider);
            mockSet.As <IQueryable <UserAccount> >().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As <IQueryable <UserAccount> >().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As <IQueryable <UserAccount> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
            var mockContext = new Mock <banking_dbContext>();

            mockContext.Setup(c => c.UserAccount).Returns(mockSet.Object);

            var service = new UserAccountController(mockContext.Object);

            data.ToList().ForEach(a => service.Add(a));
            var result = service.Get(1);

            Assert.AreEqual(7500, result.First().Balance);
        }
コード例 #4
0
        // GET: api/Cover

        //[TDABasicAuthenticationFilter(false)]
        public IEnumerable <Cover> Get()
        {
            var uIdentity              = Thread.CurrentPrincipal.Identity;
            UserAccountController uc   = new UserAccountController();
            UserAccount           user = uc.getUserFromUserName(uIdentity.Name.ToString());


            List <Cover>     coverList = new List <Cover>();
            DataTable        dt        = new DataTable();
            OracleDataReader dr        = null;
            OracleConnection con       = new OracleConnection(ConnectionString);
            //string sql = "SELECT T.ID,T.COVER_CODE,T.COVER  FROM mnbq_covers T " +
            //    "   WHERE T.COVER_CODE IN (SELECT ALLOWED_COVER_CODES FROM MNB_ALLOWED_COVERS WHERE COMPANY=:V_COMPANY) " +
            //    " order by t.COVER_CODE ";


            //string sql = "SELECT T.ID,T.COVER_CODE,T.COVER  FROM mnbq_covers T " +
            //        "   WHERE T.COVER_CODE IN ('chk4','chk5','chk7','chk8','chk11','chk12','chk13','chk17') " +
            //        " order by t.COVER_CODE ";


            string sql = "SELECT T.ID,ac.COVER_CODE,T.COVER " +
                         " FROM MNB_ALLOWED_COVERS ac " +
                         " inner join mnbq_covers T on t.cover_code = ac.cover_code " +
                         " WHERE ac.COMPANY = :V_COMPANY";



            OracleCommand command = new OracleCommand(sql, con);

            command.Parameters.Add(new OracleParameter("V_COMPANY", user.Company));


            try
            {
                con.Open();
                dr = command.ExecuteReader();
                dt.Load(dr);
                dr.Close();
                con.Close();
                coverList = (from DataRow drow in dt.Rows
                             select new Cover()
                {
                    CoverId = Convert.ToInt32(drow["ID"].ToString()),
                    CoverCode = drow["COVER_CODE"].ToString(),
                    CoverName = drow["COVER"].ToString()
                }).ToList();
            }
            catch (Exception exception)
            {
                if (dr != null || con.State == ConnectionState.Open)
                {
                    dr.Close();
                    con.Close();
                }
            }
            return(coverList);
        }
コード例 #5
0
        public void SetUp()
        {
            //Create mock services
            _authenticationManager = new Mock <IAuthenticationManager>();
            _userAccountService    = new Mock <IUserAccountService>();

            //Create controller
            _controller = new UserAccountController(_authenticationManager.Object, _userAccountService.Object);
        }
コード例 #6
0
        public void Task_ForgetPasswodWrongEmail_Return_BadResult()
        {
            var controller = new UserAccountController(_userBusiness, _config);
            var data       = new ForgetPassword
            {
                Email = "21325344"
            };
            var expecteddata = controller.ForgetPassword(data);

            Assert.IsType <BadRequestObjectResult>(expecteddata);
        }
コード例 #7
0
        public void Task_ForgetPasswodEmailwithoutdot_Return_BadResult()
        {
            var controller = new UserAccountController(_userBusiness, _config);
            var data       = new ForgetPassword
            {
                Email = "jayusawakare14@gmailcom"
            };
            var expecteddata = controller.ForgetPassword(data);

            Assert.IsType <BadRequestObjectResult>(expecteddata);
        }
コード例 #8
0
        public void Task_ForgetPasswoed_Return_OkResult()
        {
            var controller = new UserAccountController(_userBusiness, _config);
            var data       = new ForgetPassword
            {
                Email = "*****@*****.**"
            };
            var expecteddata = controller.ForgetPassword(data);

            Assert.IsType <OkObjectResult>(expecteddata);
        }
コード例 #9
0
        public void Task_LoginEmailPassword_Return_BadResult()
        {
            var controller = new UserAccountController(_userBusiness, _config);
            var data       = new Login
            {
                Email    = "",
                Password = ""
            };
            var expecteddata = controller.Login(data);

            Assert.IsType <BadRequestObjectResult>(expecteddata);
        }
コード例 #10
0
        public void Task_LoginUser_Return_OkResult()
        {
            var controller = new UserAccountController(_userBusiness, _config);
            var data       = new Login
            {
                Email    = "*****@*****.**",
                Password = "******"
            };
            var expecteddata = controller.Login(data);

            Assert.IsType <OkObjectResult>(expecteddata);
        }
コード例 #11
0
        public void GetUserProfile_By_UserName_ForValidUserName()
        {
            //Arrange
            var objUserAccount = new UserAccountController(mockRepository.Object);

            mockRepository.Setup(u => u.GetUserProfile(It.IsAny <string>())).Returns(userProfile);

            //Act
            var result = objUserAccount.GetUserProfile("venkatesh");

            //Assert
            Assert.AreEqual(result.LastName, "pydi");
        }
コード例 #12
0
        public void LogoutTest()
        {
            UserAccountController userController = CreateFakeUserAccountController(_users[0]);

            //Load auth salt with some bytes and check null after logout
            _users[0].AuthSalt = new Byte[] { 88 };
            Assert.NotNull(_users[0].AuthSalt);

            var response = userController.Logout();

            Assert.IsType <OkResult>(response);
            Assert.Null(_users[0].AuthSalt);
        }
コード例 #13
0
        public void ValidateUser_forvalidentries()
        {
            ////Arange
            var objUserAccount = new UserAccountController(mockRepository.Object);

            mockRepository.Setup(u => u.ValidateUser(It.IsAny <string>(), It.IsAny <string>())).Returns(userProfile);
            string userName = "******", password = "******";
            //Act
            var result = objUserAccount.ValidateUser(userName, password);

            //Assert
            Assert.AreEqual(result.FirstName, "venkatesh");
        }
コード例 #14
0
        public void Task_Registration_Return_BadResult()
        {
            var controller = new UserAccountController(_userBusiness, _config);
            var data       = new Registratin
            {
                FirstName = "",
                LastName  = "",
                Email     = "",
                Password  = "",
                Type      = ""
            };
            var expecteddata = controller.Registration(data);

            Assert.IsType <BadRequestObjectResult>(expecteddata);
        }
コード例 #15
0
        public AuthenticationSteps(UserAccountController userAccountController,
                                   AuthenticationController authenticationController)
        {
            if (authenticationController == null)
            {
                throw new ArgumentNullException(nameof(authenticationController));
            }
            if (userAccountController == null)
            {
                throw new ArgumentNullException(nameof(userAccountController));
            }

            this.userAccountController    = userAccountController;
            this.authenticationController = authenticationController;
        }
コード例 #16
0
        public void AuthenticateInvalidCredentialsTest()
        {
            UserAccountController userController = CreateFakeUserAccountController();

            //Authenticate with invalid credentials
            var response = userController.Authenticate(
                new ReceiveLoginUserModel(_users[0].Email, "wrong-password")
                );

            Assert.IsType <BadRequestObjectResult>(response.Result);

            response = userController.Authenticate(
                new ReceiveLoginUserModel("wrong-email", "password-u1")
                );
            Assert.IsType <BadRequestObjectResult>(response.Result);
        }
コード例 #17
0
        public void TestInit()
        {
            var cryptoOptions = new Mock <IOptions <CryptoConfigs> >();

            cryptoOptions.Setup(x => x.Value).Returns(new CryptoConfigs {
                Salt = "salty salty"
            });

            var jwtOptions = new Mock <IOptions <JwtConfigs> >();

            jwtOptions.Setup(x => x.Value).Returns(new JwtConfigs {
                SymmetricKey = "symmetrytryemmys"
            });

            this.userAccountController = new UserAccountController(new MemoryDataContext(), cryptoOptions.Object, jwtOptions.Object);
        }
コード例 #18
0
            public void Index_ReturnsAViewResult_WithAUserAccountVM()
            {
                // Arrange
                var mockUserManager        = GetMockUserManager();
                var mockUserDataRepository = GetMockUserRepoStub();

                var controller = new UserAccountController(GetMockUserRepoStub().Object, GetMockUserManager().Object, null, null);

                // Act
                var result = controller.Index();

                // Assert
                var viewResult = Assert.IsType <ViewResult>(result);
                var model      = Assert.IsAssignableFrom <UserAccountViewModel>(
                    viewResult.ViewData.Model);
            }
コード例 #19
0
        private UserAccountController CreateFakeUserAccountController(User loggedUser = null)
        {
            //Create fake DBContext
            var context = new GlovoDbContext(ContextOptions);

            //Create fake HttpContextAccessor
            var httpContext         = new DefaultHttpContext();
            var httpContextAccessor = new HttpContextAccessor {
                HttpContext = httpContext
            };

            //Add logged user to HttpContextAccessor in case it is needed
            if (loggedUser != null)
            {
                httpContextAccessor.HttpContext.Items["User"] = loggedUser;
            }

            //Create RestApiUsersService instance with fake DBContext and HttpContextAccessor
            _usersService = new RestApiUsersService(context, httpContextAccessor);

            //Create mapper with UsersProfile
            var mapper = new MapperConfiguration(cfg => {
                cfg.AddProfile <LocationsProfile>();
                cfg.AddProfile <OrdersProductsProfile>();
                cfg.AddProfile <OrdersProfile>();
                cfg.AddProfile <ProductsProfile>();
                cfg.AddProfile <RestaurantsProfile>();
                cfg.AddProfile <UsersProfile>();
            }).CreateMapper();

            //Create AppConfiguration options using fake secret string
            _testApiSecret = RandomString(1024);
            IOptions <AppConfiguration> appConfigOptions = new OptionsWrapper <AppConfiguration>(
                new AppConfiguration {
                Secret = _testApiSecret
            }
                );

            //Create UsersController instance with the RestApiUsersService instance, the mapper and the
            //fake AppConfiguration
            var usersController = new UserAccountController(_usersService, mapper, appConfigOptions)
            {
                ControllerContext = { HttpContext = httpContext }
            };

            return(usersController);
        }
コード例 #20
0
        public void RegisterTest()
        {
            UserAccountController userController = CreateFakeUserAccountController();

            //Register user correctly
            var response = userController.Register(new RegisterUserModel(
                                                       "reg-user-name", "reg-user-email", "reg-user-password"
                                                       ));

            Assert.IsType <OkResult>(response);

            User registeredUser = _usersService.GetByEmail("reg-user-email");

            Assert.Equal("reg-user-name", registeredUser.Name);
            Assert.Equal("reg-user-email", registeredUser.Email);
            Assert.True(PasswordVerifier.VerifyPasswordHash("reg-user-password", registeredUser.PasswordHash, registeredUser.PasswordSalt));
        }
コード例 #21
0
ファイル: Test02.cs プロジェクト: EmoKosov/BankingProject
        public void CreateAccount_saves_an_account_via_context()
        {
            string date = DateTime.UtcNow.ToString();

            var mockSet = new Mock <DbSet <UserAccount> >();

            var mockContext = new Mock <banking_dbContext>();

            mockContext.Setup(m => m.UserAccount).Returns(mockSet.Object);

            var service = new UserAccountController(mockContext.Object);

            service.Add(new UserAccount(1, "Georgi Georgiev", "11/06/2000", "0878444484", "bul Bulgaria 4", "Smolyan", "Smolyan", "Male", "married",
                                        null, null, 7500, date.ToString()));

            mockSet.Verify(m => m.Add(It.IsAny <UserAccount>()), Times.Once());
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
        }
コード例 #22
0
        public async Task GetUserAccounts_Should_Return_ApplicationUserList()
        {
            //arrange
            var             userManager       = RepositoryMocks.GetUserManager().Object;
            var             roleManager       = RepositoryMocks.GetRoleManager().Object;
            var             passwordHasher    = RepositoryMocks.GetIPasswordHasher().Object;
            var             logger            = RepositoryMocks.GetLogger <AccountService>().Object;
            var             patientRepository = RepositoryMocks.GetPatientRepository().Object;
            IConfiguration  configuration     = TestHelper.GetApplicationConfiguration() as IConfiguration;
            IAccountService userService       = new AccountService(userManager, roleManager, passwordHasher, configuration, logger, patientRepository);

            UserAccountController accountController = new UserAccountController(userService);

            //act
            var userAccounts = await accountController.GetUserAccounts();

            //assert
            Assert.NotNull(userAccounts);
        }
コード例 #23
0
        public HttpResponseMessage AddQuotationCoverDetails(PostQuotationCoverRequest postQuotationCoverRequest)
        {
            // api/QuotationCover/AddQuotationCoverDetails?jobId=54163&RevisionId=0

            var uIdentity              = Thread.CurrentPrincipal.Identity;
            UserAccountController uc   = new UserAccountController();
            UserAccount           user = uc.getUserFromUserName(uIdentity.Name.ToString());


            QuotationMainTakafulController quotationMainController = new QuotationMainTakafulController();

            QuotationMainTakaful quotationMain;


            CoverController coverController = new CoverController();


            List <Cover> allowedCoverList = coverController.GetAllowedCovers(user.Company);


            DeleteCovers(Convert.ToInt32(postQuotationCoverRequest.JobId), Convert.ToInt32(postQuotationCoverRequest.RevisionId));

            foreach (QuotationCover cover in postQuotationCoverRequest.QuotationCovers)
            {
                if (cover.Cover == "chk4" || cover.Cover == "chk5" || cover.Cover == "chk8")
                {
                    if (!validateCoverAmount(cover.Cover, cover.Amount))
                    {
                        var       message = string.Format("Amount of cover {0} not in the allowed range", cover.Cover);
                        HttpError err     = new HttpError(message);
                        return(Request.CreateResponse(HttpStatusCode.NotAcceptable, err));
                    }
                }

                //To validate the allowed covers
                var item = allowedCoverList.Find(x => x.CoverCode == cover.Cover);

                if (item == null)
                {
                    continue;
                }
                ///////////

                OracleConnection con = new OracleConnection(ConnectionString);
                try
                {
                    con.Open();
                    OracleCommand cmd = null;

                    cmd = new OracleCommand("MNB_T_INSERT_MTR_COVER_DETAILS");

                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection  = con;

                    cmd.Parameters.Add("jobid", OracleType.Int32).Value         = cover.JobId;
                    cmd.Parameters.Add("revision_id", OracleType.VarChar).Value = cover.RevisionId;
                    cmd.Parameters.Add("cover", OracleType.VarChar).Value       = cover.Cover;
                    cmd.Parameters.Add("pol_type", OracleType.VarChar).Value    = cover.Type;
                    cmd.Parameters.Add("amount", OracleType.VarChar).Value      = cover.Amount;



                    cmd.ExecuteNonQuery();
                    con.Close();



                    //saveDefaultCovers(postQuotationCoverRequest.JobId, user);
                }
                catch (Exception ex)
                {
                    con.Close();
                    return(Request.CreateResponse(HttpStatusCode.ExpectationFailed));
                }
            }



            return(Request.CreateResponse(HttpStatusCode.OK));
        }
 public UserAccountControllerTest()
 {
     _mockUserAccountProvider = new Mock <IUserAccountProvider>();
     _mockLogger = new Mock <ILogger <UserAccountController> >();
     _controller = new UserAccountController(_mockLogger.Object, _mockUserAccountProvider.Object);
 }