public void TestLogout_WithoutLoggedUser_ShouldThrowException()
        {
            this.user = null;
            this.usersController = new UsersController(this.db, this.user);

            this.usersController.Logout();
        }
Пример #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cookies.Clear();

        //FacebookClient fbapp = new FacebookClient();
        //ConnectSession sess = new ConnectSession(
        //    ConfigurationManager.AppSettings["APIKey"],
        //    ConfigurationManager.AppSettings["Secret"]);
        var fbWebContext = FacebookWebContext.Current;
        if (FacebookWebContext.Current.Session != null)
        {
            FacebookWebContext.Current.DeleteAuthCookie();
            //sess.Logout();
            // just to be sure...
            killFacebookCookies();
        }

        Session.RemoveAll();
        UsersController _controller = new UsersController();
        StateManager stateManager = StateManager.Instance;
        _controller.DeleteSessionDetails(Session.SessionID);
        stateManager.Remove("objSessionvalue", StateManager.State.Session);
        Session.Clear();
        Session.Abandon();
        //StateManager objStateManager = StateManager.Instance;
        //objStateManager.Add("LoginChk", null, StateManager.State.Session);
        //Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
        HttpCookie cookie = new HttpCookie("ASP.NET_SessionId", string.Empty);
        cookie.Domain = "." + WebConfig.TopLevelDomain;
        Response.Cookies.Add(cookie);
        //Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
        //Response.Cookies["ASP.NET_SessionId"].Domain = "." + WebConfig.TopLevelDomain;
        Response.Redirect("~/log_in.aspx");
        //Redirect.PageList.Inner2LoginPage.ToString()));
    }
        public void TestLogout_WithLoggedUser_ShouldPass()
        {
            this.user = new User("Pesho", "parola123", Roles.User);
            this.usersController = new UsersController(this.db, this.user);

            this.usersController.Logout();
        }
Пример #4
0
 public void MyTestInitialize()
 {
     _repositoryStub = MockRepository.GenerateStub<IUsersRepository>();
     _userMapperStub = MockRepository.GenerateStub<IMapper>();
     _sut = new UsersController(_repositoryStub, _userMapperStub);
     InitializeController(_sut);
 }
		public void RegisterHttpControllers(HttpService externalHttpService, HttpService internalHttpService, HttpSendService httpSendService, IPublisher mainQueue, IPublisher networkSendQueue)
		{
			var usersController = new UsersController(httpSendService, mainQueue, networkSendQueue);
			externalHttpService.SetupController(usersController);
            if(internalHttpService != null) {
			    internalHttpService.SetupController(usersController);
            }
		}
 public bool checkIfExist(string userName)
 {
     UsersController u = new UsersController();
     if (u.checkIfExist(userName))
         return true;
     else
         return false;
 }
        public void UsersLogout_SuccessfullyLogout_ShouldReturnView()
        {
            var currentUser = new User("NormalUser", "122343434", Roles.User);
            var testController = new UsersController(new HotelBookingSystemData(), currentUser);

            var resultView = testController.Logout();

            Assert.AreEqual(currentUser, resultView.Model);
        }
Пример #8
0
        public void Delete()
        {
            // Arrange
            UsersController controller = new UsersController();

            // Act
            controller.Delete(5);

            // Assert
        }
Пример #9
0
        public void Put()
        {
            // Arrange
            UsersController controller = new UsersController();

            // Act
            controller.Put(5, "value");

            // Assert
        }
Пример #10
0
        public void GetById()
        {
            // Arrange
            UsersController controller = new UsersController();

            // Act
            string result = controller.Get(5);

            // Assert
            Assert.AreEqual("value", result);
        }
Пример #11
0
    public void GetSessionKeyValues()
    {
        UsersController _controller1 = new UsersController();
        //List<SessionValue> _objSession = new List<SessionValue>();
        List<SessionValue> _objSession = _controller1.GetSessionValuesDetails(Session.SessionID);
        TributesPortal.Utilities.StateManager stateManager = TributesPortal.Utilities.StateManager.Instance;

        SessionValue objVal = new SessionValue();

        if (_objSession.Count > 0)
        {
            foreach (SessionValue obj in _objSession)
            {
                if (obj.SessionKey == "UserId")
                    objVal.UserId = Convert.ToInt32(obj.SessionValues);

                if (obj.SessionKey == "UserName")
                    objVal.UserName = obj.SessionValues;

                if (obj.SessionKey == "Email")
                    objVal.UserEmail = obj.SessionValues;

                if (obj.SessionKey == "FirstName")
                    objVal.FirstName = obj.SessionValues;

                if (obj.SessionKey == "LastName")
                    objVal.LastName = obj.SessionValues;

                if (obj.SessionKey == "UserType")
                    objVal.UserType = Convert.ToInt32(obj.SessionValues);

                if (obj.SessionKey == "UserTypeDescription")
                    objVal.UserTypeDescription = obj.SessionValues;

                if (obj.SessionKey == "IsUsernameVisiable")
                    objVal.IsUsernameVisiable = Convert.ToBoolean(obj.SessionValues);

                // Added by Rupendra to get User image

                if (obj.SessionKey == "UserImage")
                    objVal.UserImage = obj.SessionValues;

                // Added by Varun on 25 Jan 2013 for NoRedirection functionality
                if (obj.SessionKey == "NoRedirection")
                {
                    bool val;
                    objVal.NoRedirection = bool.TryParse(obj.SessionValues, out val);
                }
            }

            stateManager.Add("objSessionValue", objVal, StateManager.State.Session);
        }
    }
        public HttpActionInvokerTracerTest()
        {
            UsersController controller = new UsersController();
            _apiController = controller;

            Func<HttpResponseMessage> actionMethod = controller.Get;
            _actionContext = ContextUtil.CreateActionContext(
                ContextUtil.CreateControllerContext(instance: _apiController),
                new ReflectedHttpActionDescriptor { MethodInfo = actionMethod.Method });
            HttpRequestMessage request = new HttpRequestMessage();
            _actionContext.ControllerContext.Request = request;
        }
Пример #13
0
        public void Get_User_Data_For_Valid_NameIdentifier()
        {
            // Prepare
            IIdentity i = new System.Security.Principal.Fakes.StubIIdentity()
            {
                IsAuthenticatedGet = () => { return true; }
            };
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.NameIdentifier, "s0Me1De9Tf!Er$tRing"));
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(i, claims, string.Empty, ClaimTypes.NameIdentifier, string.Empty);
            ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity as IIdentity);
            User fakeUser = new User()
                {
                    UserId = 1,
                    NameIdentifier = "s0Me1De9Tf!Er$tRing",
                    FirstName = "SomeFirstName",
                    MiddleName = "SomeMiddleName",
                    LastName = "SomeLastName",
                    IdentityProvider = "Windows Live",
                    Organization = "SomeOrganization",
                    EmailId = "*****@*****.**",
                    CreatedOn = DateTime.Now,
                    ModifiedOn = DateTime.Now,
                    IsActive = true,
                    UserRoles = {
                                    new UserRole 
                                    {
                                        RoleId=2, 
                                        UserId=1, 
                                        Role = new Role(){ Name = "User" }
                                    }
                                }
                };
            IUserService userService = new Microsoft.Research.DataOnboarding.Services.UserService.Fakes.StubIUserService()
            {
                GetUserWithRolesByNameIdentifierString = (nameIdentifier) => { return fakeUser;}
            };
            System.Threading.Thread.CurrentPrincipal = principal;
            UsersController userController = new UsersController(userService);
            userController.Request = new HttpRequestMessage(HttpMethod.Get, string.Empty);
            userController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration();

            // Perform
            var message = userController.GetUsersByNameIdentifier();

            // Assert
            Assert.AreEqual(message.StatusCode, HttpStatusCode.OK);
            var result = message.Content.ReadAsAsync<User>().Result;
            Assert.IsNotNull(result);
            Assert.AreEqual(result.NameIdentifier, fakeUser.NameIdentifier);
        }
Пример #14
0
        public void Get()
        {
            // Arrange
            UsersController controller = new UsersController();

            // Act
            IEnumerable<string> result = controller.Get();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count());
            Assert.AreEqual("value1", result.ElementAt(0));
            Assert.AreEqual("value2", result.ElementAt(1));
        }
        public void Setup()
        {
            _controller = new UsersController
            {
                Request = new HttpRequestMessage(),
                Configuration = new HttpConfiguration()
            };

            Server singleton = Singleton.GetServer;

            System.Reflection.FieldInfo instance = typeof(Singleton).GetField("Instance.Server", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            _mockSingleton = new Mock<Server>();
                instance.SetValue(null, _mockSingleton.Object);
        }
        public void Post_LoginUser_InvalidAuthCode_AuthCodeTooShort()
        {
            FakeRepository<User> userFakeRepository = new FakeRepository<User>();
            UsersController usersController = new UsersController(userFakeRepository);
            SetupController(usersController);

            UserModel model = new UserModel()
            {
                AuthCode = "0123456789",
                Username = "******",
                Nickname = "TestNickname"
            };

            usersController.RegisterUser(model);
        }
Пример #17
0
        public void UsersLogoutValidUser_ShouldReturnCorrectResult()
        {
            // Arrange
            IHotelBookingSystemData data = new HotelBookingSystemData();
            User user = new User("test user", "password", Roles.User);
            UsersController controller = new UsersController(data, user);

            // Act
            controller.CurrentUser = user;
            IView view = controller.Logout();
            string result = view.Display();
            string expected = "The user test user has logged out.";

            // Assert
            Assert.AreEqual(expected, result);
        }
Пример #18
0
        public void GetUserProfile_Test()
        {
            // Arrange
            UsersController controller = new UsersController();

            // Act
            var userId = 1;

            // GET api/users/{userId}
            var result = controller.GetUserProfile(userId);

            // Assert
            Assert.IsNotNull(result);
            var castResult = result as OkNegotiatedContentResult<UserModel>;
            var actualResult = castResult.Content;

            Assert.AreEqual("Test", actualResult.FirstName);
        }
Пример #19
0
        public void GetUserMatches_Test()
        {
            // Arrange
            UsersController controller = new UsersController();

            // Act
            var userId = 1;

            // GET api/users/{userId}/matches
            var result = controller.GetUserMatches(userId);

            // Assert
            Assert.IsNotNull(result);
            var castResult = result as OkNegotiatedContentResult<List<int>>;
            var actualResult = castResult.Content;

            Assert.AreEqual(2, actualResult.Count);
        }
Пример #20
0
        public void can_get_data_one()
        {
            // Arrange - create the mock repository
              Mock<ICommonRepository<User>> mock = new Mock<ICommonRepository<User>>();

              mock.Setup(m => m.Data).Returns(new[]
              {
            new User {UserID = 1, Name = "P1"},
            new User {UserID = 2, Name = "P2"},
            new User {UserID = 3, Name = "P3"}
              });
              // Arrange - create a controller
              UsersController target = new UsersController(mock.Object);
              // Arrange - create a search tag
              int id = 2;
              // Action
              IHttpActionResult actionResult =  target.GetUser(id);
              // Assert
              Assert.IsInstanceOfType(actionResult, typeof(System.Web.Http.Results.OkNegotiatedContentResult<User>));
        }
Пример #21
0
        public void can_get_data()
        {
            // Arrange - create the mock repository
              Mock<ICommonRepository<User>> mock = new Mock<ICommonRepository<User>>();

              mock.Setup(m => m.Data).Returns(new[]
              {
            new User {UserID = 1, Name = "P1"},
            new User {UserID = 2, Name = "P2"},
            new User {UserID = 3, Name = "P3"}
              });
              // Arrange - create a controller
              UsersController target = new UsersController(mock.Object);
              // Action
              User[] result = target.GetUsers().ToArray();
              // Assert
              Assert.AreEqual(result.Length, 3);
              Assert.AreEqual("P1", result[0].Name);
              Assert.AreEqual("P2", result[1].Name);
              Assert.AreEqual("P3", result[2].Name);
        }
Пример #22
0
        public CameraPage()
        {
            InitializeComponent();

            _navigationHelper = new NavigationHelper(this);

            _sensor = KinectSensor.GetDefault();

            if (_sensor != null)
            {
                _sensor.Open();

                _reader = _sensor.OpenMultiSourceFrameReader(FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.Infrared | FrameSourceTypes.Body);
                _reader.MultiSourceFrameArrived += Reader_MultiSourceFrameArrived;

                _userReporter = new UsersController();
                _userReporter.BodyEntered += UserReporter_BodyEntered;
                _userReporter.BodyLeft += UserReporter_BodyLeft;
                _userReporter.Start();
            }
        }
Пример #23
0
        public async Task E_Possivel_Invocar_a_Controller_Get()
        {
            var serviceMock = new Mock <IUserService>();
            var nome        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Get(It.IsAny <Guid>())).ReturnsAsync(
                new UserDto {
                Id       = Guid.NewGuid(),
                Name     = nome,
                Email    = email,
                CreateAt = DateTime.UtcNow
            }
                );

            _controller = new UsersController(serviceMock.Object);
            _controller.ModelState.AddModelError("Id", "Formato Inválido");

            var result = await _controller.Get(Guid.NewGuid());

            Assert.True(result is BadRequestObjectResult);
        }
Пример #24
0
        public async Task RefreshToken_should_be_fail()
        {
            var notValidAccessToken = "It is not a valid token";

            var userServiceMock = new Mock <IUserService>();

            userServiceMock.Setup(service => service.RefreshTokenAsync(notValidAccessToken))
            .ReturnsAsync(GetAuthenticateResponse_Fail());

            var controller = new UsersController(userServiceMock.Object);

            var actionResult = await controller.RefreshToken(new RefreshTokenRequest
            {
                Token = notValidAccessToken,
            });

            var result      = Assert.IsType <ObjectResult>(actionResult);
            var resultValue = Assert.IsType <AppResponse>(result.Value);

            Assert.NotNull(result.Value);
            Assert.False(resultValue.Status == System.Net.HttpStatusCode.OK);
        }
Пример #25
0
        public async void Task_Add_ValidData_MatchResult()
        {
            //Arrange
            mediator.Setup(m => m.Send(It.IsAny <CreateUserCommand>(), CancellationToken.None)).Returns(Task.FromResult(1));
            var controller = new UsersController(mediator.Object);

            var command = new CreateUserCommand()
            {
                FirstName = "aaaa", LastName = "bbbbb"
            };

            //Act
            var data = await controller.Create(command);

            //Assert
            Assert.IsType <OkObjectResult>(data);

            var okResult = data as OkObjectResult;


            Assert.Equal(1, okResult.Value);
        }
Пример #26
0
        public void DeleteWithIdTest()
        {
            // Arrange

            var moq = new Mock <Models.TestContext>();

            var data = new List <User>()
            {
                new User(1),
                new User(4)
            };

            moq.Setup(x => x.Users).Returns(GetDbSetMock(data).Object);

            var controller = new UsersController(moq.Object);

            // Act
            ViewResult result = controller.Delete(1) as ViewResult;

            // Assert
            Assert.IsTrue(((List <User>)result.Model).Count == 1);
        }
Пример #27
0
        public void DuplicateSignUpReturnsBadRequest()
        {
            var fakeUsersService = A.Fake <IUserService <ISTUsersRepo> >();

            var newUser = new User()
            {
                FirstName = "Bob",
                LastName  = "Smith",
                Password  = "******",
                Token     = "SecretToken!",
                Username  = "******"
            };

            var usersController = new UsersController(fakeUsersService);

            A.CallTo(() => fakeUsersService.SignUp(newUser)).Returns(newUser);
            usersController.SignUp(newUser);
            A.CallTo(() => fakeUsersService.SignUp(newUser)).Throws <SupportTicketUserAlreadyExistsException>();
            var result = usersController.SignUp(newUser);

            Assert.IsType <BadRequestObjectResult>(result);
        }
Пример #28
0
        public async Task PostUser_CorrectUserWithCorrectValuesAndIdNotSet_CreatedAtActionResult()
        {
            // Arrange
            InitializeInmemoryDatabase(out DbContextOptions <GameReviewsContext> options, GetFakeList());

            User userToCreate = new User()
            {
                Name             = "NewDevelope",
                RegistrationDate = DateTime.Parse("15-10-2020")
            };

            // Act
            using (var context = new GameReviewsContext(options))
            {
                UsersController usersController = new UsersController(context);
                var             result          = (await usersController.PostUser(userToCreate)).Result;

                // Assert
                Assert.True(context.Users.Contains(userToCreate));
                Assert.IsType <CreatedAtActionResult>(result);
            }
        }
Пример #29
0
        public UsersControllerTests()
        {
            _appSettings        = new AppSettings();
            _appSettings.Secret = "THIS IS MY VERY LONG TESTING SECRET THAT NO ONE SHOULD KNOW";
            // Arrange testing service for all the testing class
            _appOptions = Options.Create(_appSettings);

            var mapperConfig = new MapperConfiguration(cfg => {
                cfg.AddProfile <UsersProfile>();
                cfg.AddProfile <AuthenticateProfile>();
            }); _mockMapper = mapperConfig.CreateMapper();

            _mockUserService = new Mock <IUserService>();
            _usersExample    = new List <User>
            {
                new User {
                    Id = 1, FirstName = "Test", LastName = "Test", Username = "******", Password = "******", PizzaLove = 1
                },
                new User {
                    Id = 2, FirstName = "User", LastName = "User", Username = "******", Password = "******", PizzaLove = 3
                }
            };
            _mockUserService.Setup(x => x.GetAllAsync()).ReturnsAsync(_usersExample);
            _mockUserService.Setup(x => x.GetByIdAsync(1)).ReturnsAsync(_usersExample[0]);
            _mockUserService.Setup(x => x.GetByIdAsync(3)).ReturnsAsync(_usersExample[0]);
            _mockUserService.Setup(x => x.AddNewUserAsync(It.IsAny <User>())).ReturnsAsync(_usersExample[1]);
            _mockUserService
            .Setup(x => x.AuthenticateAsync(It.Is <AuthenticateRequest>(i => i.Username == "userrrr")))
            .ReturnsAsync((AuthenticateResponse)null);
            _mockUserService
            .Setup(x => x.AuthenticateAsync(It.Is <AuthenticateRequest>(i => i.Password == "userrrr")))
            .ReturnsAsync((AuthenticateResponse)null);
            _mockUserService
            .Setup(x => x.AuthenticateAsync(It.Is <AuthenticateRequest>(i => i.Username == "user" && i.Password == "user")))
            .ReturnsAsync(new AuthenticateResponse());
            _mockUserService.Setup(x => x.GetTopTenPizzaLoveAsync()).ReturnsAsync(_usersExample);

            _userController = new UsersController(_appOptions, _mockUserService.Object, _mockMapper);
        }
        public async Task UserControllerGetByIdOrEmailTest()
        {
            void CheckExpectedResult(IActionResult result)
            {
                var okObjectResult = Assert.IsType <OkObjectResult>(result);
                var user           = Assert.IsType <TasklifyUser>(okObjectResult.Value);

                Assert.Equal(2, user.Id);
                Assert.Equal("*****@*****.**", user.Email);
                Assert.Equal("test2", user.Name);
            }

            var uDAL           = new DemoUsersDAL();
            var userController = new UsersController(uDAL);

            await userController.AddUser(new TasklifyUser(1, "*****@*****.**", "test"));

            await userController.AddUser(new TasklifyUser(2, "*****@*****.**", "test2"));

            await userController.AddUser(new TasklifyUser(3, "*****@*****.**", "test3"));

            var result = await userController.GetById(2);

            CheckExpectedResult(result);
            result = await userController.GetByEmail("*****@*****.**");

            CheckExpectedResult(result);

            result = await userController.GetById(5);

            var objectResult = Assert.IsType <StatusCodeResult>(result);

            Assert.Equal(403, objectResult.StatusCode);

            result = await userController.GetByEmail("*****@*****.**");

            objectResult = Assert.IsType <StatusCodeResult>(result);
            Assert.Equal(403, objectResult.StatusCode);
        }
Пример #31
0
        public void SignUpReturnsCorrectResultTypeWithUser()
        {
            var fakeUsersService = A.Fake <IUserService <ISTUsersRepo> >();

            var newUser = new User()
            {
                FirstName = "Bob",
                LastName  = "Smith",
                Password  = "******",
                Token     = "SecretToken!",
                Username  = "******"
            };

            A.CallTo(() => fakeUsersService.SignUp(newUser)).Returns(newUser);

            var usersController = new UsersController(fakeUsersService);

            var result = usersController.SignUp(newUser);

            Assert.IsType <CreatedAtRouteResult>(result);
            Assert.Equal(newUser, ((CreatedAtRouteResult)result).Value);
        }
Пример #32
0
        public async Task It_Is_Possible_To_Invoke_The_Controller_Get()
        {
            var serviceMock = new Mock <IUserService>();
            var name        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(s => s.Get(It.IsAny <Guid>())).ReturnsAsync(
                new UserDto
            {
                Id        = Guid.NewGuid(),
                Name      = name,
                Email     = email,
                CreatedAt = DateTime.Now
            });

            _controller = new UsersController(serviceMock.Object);
            _controller.ModelState.AddModelError("Id", "Formato inválido.");

            var result = await _controller.Get(Guid.NewGuid());

            Assert.True(result is BadRequestObjectResult);
        }
Пример #33
0
        public void Init()
        {
            _mockUserManager    = new Mock <UserManager>();
            _mockAutheniication = new Mock <Autheniication>();

            _usersController = new UsersController(_mockUserManager.Object, _mockAutheniication.Object);

            USER_NAME = "USER_NAME";
            USER_PSW  = "USER_PSW";

            USER = new User
            {
                UserName = USER_NAME,
                Password = USER_PSW
            };

            USERS = new List <User>
            {
                USER,
                USER
            };
        }
        public async Task PostCustomerTreatment_PostValidTreatment_TreatmentSavedAndDateTruncated()
        {
            using (var context = GetInitializedUsersContext())
            {
                var               usersService = new Services.UsersService(context, new QueueApiServiceMock());
                UsersController   controller   = new UsersController(usersService);
                CustomerTreatment treatment    = new CustomerTreatment
                {
                    CustomerId         = 10,
                    DateOfTreatment    = DateTime.Now,
                    TreatingEmployeeId = 3
                };

                IActionResult result = await controller.PostCustomerTreatment(treatment);

                Assert.IsInstanceOf <IActionResult>(result);
                Assert.IsInstanceOf <CreatedAtActionResult>(result);
                Assert.DoesNotThrow(() => context.Treatments.
                                    Where(t => t.CustomerId == treatment.CustomerId && t.TreatmentDate == DateTime.Today && t.EmployeeId == treatment.TreatingEmployeeId).
                                    Single());
            }
        }
Пример #35
0
        public async Task E_Possivel_Invocar_a_Controller_Create()
        {
            var serviceMock = new Mock <IUserService>();
            var nome        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(c => c.Post(It.IsAny <UserDTOCreate>())).ReturnsAsync(
                new UserDTOCreateResult
            {
                Id       = Guid.NewGuid(),
                Name     = nome,
                Email    = email,
                CreateAt = DateTime.UtcNow
            }
                );

            _controller = new UsersController(serviceMock.Object);

            Mock <IUrlHelper> url = new Mock <IUrlHelper>();

            url.Setup(x => x.Link(It.IsAny <string>(), It.IsAny <object>())).Returns("http://localhost:5000");
            _controller.Url = url.Object;

            var userDTOCreate = new UserDTOCreate
            {
                Name  = nome,
                Email = email
            };

            var result = await _controller.Post(userDTOCreate);

            Assert.True(result is CreatedResult);

            var resultValue = ((CreatedResult)result).Value as UserDTOCreateResult;

            Assert.NotNull(resultValue);
            Assert.Equal(userDTOCreate.Name, resultValue.Name);
            Assert.Equal(userDTOCreate.Email, resultValue.Email);
        }
Пример #36
0
    protected void btnAddRole_Click(object sender, DirectEventArgs e)
    {
        try
        {
            //check xem user này đã có trong bảng DOnvi_User chưa
            foreach (var selectedUsers in RowSelectionModel1.SelectedRows)
            {
                if (!new DM_DONVIController().UserIsInAnyDepartments(int.Parse(selectedUsers.RecordID)))
                {
                    X.MessageBox.Alert("Cảnh báo", "Người dùng có <b>mã tài khoản = " + selectedUsers.RecordID + "</b> không thể thiết lập quyền vì chưa nằm trong bộ phận nào !").Show();
                    return;
                }
            }
            // Xóa quyền cũ để thiết lập quyền mới
            foreach (var selectedUsers in RowSelectionModel1.SelectedRows)
            {
                UsersController.GetInstance().DeleteUserRoleByUserID(int.Parse(selectedUsers.RecordID));
            }

            string[] roleList = hdfSelectedNodeID.Text.Split(',');
            foreach (var item in roleList)
            {
                if (item.Length != 0)
                {
                    int roleId = int.Parse(item);
                    foreach (var selectedUsers in RowSelectionModel1.SelectedRows)
                    {
                        UsersController.GetInstance().SetRoles(int.Parse(selectedUsers.RecordID), roleId);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Dialog.ShowNotification(GlobalResourceManager.GetInstance().GetErrorMessageValue("DefaultErrorMessage"));
        }
        wdAssignRole.Hide();
        Dialog.ShowNotification("Thiết lập quyền thành công !");
    }
        public async Task PostEmployeeLogin_FirstValidLogin_LoginSuccessful()
        {
            using (var context = GetInitializedUsersContext())
            {
                var             usersService = new Services.UsersService(context, new QueueApiServiceMock());
                UsersController controller   = new UsersController(usersService);
                EmployeeLogin   login        = new EmployeeLogin
                {
                    Username      = "******",
                    Password      = "******",
                    ServiceType   = ServiceType.Pharmacist,
                    StationNumber = 1
                };

                ActionResult <EmployeeInfo> result = await controller.PostEmployeeLogin(login);

                Assert.IsInstanceOf <ActionResult <EmployeeInfo> >(result);
                Assert.IsInstanceOf <EmployeeInfo>(result.Value);
                bool isOnline = context.Employees.Where(e => e.Username == login.Username).Single().Online;
                Assert.IsTrue(isOnline);
            }
        }
        public async Task ChangeUserDetailsGet_ShouldReturnViewWithCorrectModelWhenValidUserId()
        {
            // Arrange
            Mock <UserManager <User> > userManager = this.GetAndSetUserManagerMock();

            UsersController controller = new UsersController(null, null, userManager.Object);

            // Act
            IActionResult actionResult = await controller.ChangeUserDetails(FirstUserId, 1, null);

            // Arrange
            actionResult.Should().BeOfType <ViewResult>();

            object model = actionResult.As <ViewResult>().Model;

            model.Should().BeOfType <ChangeUserDetailsFormModel>();

            ChangeUserDetailsFormModel returnedModel = model.As <ChangeUserDetailsFormModel>();

            returnedModel.Email.Should().Be(FirstUserEmail);
            returnedModel.Username.Should().Be(FirstUserUsername);
        }
Пример #39
0
        public async Task GetUser_ExistingId_TaskActionResultContainsUser()
        {
            // Arrange
            const int userId = 3;

            User expectedUser = GetFakeList().Where(d => d.ID == userId).FirstOrDefault();

            InitializeInmemoryDatabase(out DbContextOptions <GameReviewsContext> options, GetFakeList());

            // Act
            using (var context = new GameReviewsContext(options))
            {
                UsersController usersController = new UsersController(context);
                var             actionResult    = (await usersController.GetUser(userId));
                User            user            = actionResult.Value;
                ActionResult    result          = actionResult.Result;

                // Assert
                Assert.True(AreEqual(expectedUser, user));
                Assert.IsNotType <NotFoundResult>(result);
            }
        }
        public async Task ChangeUserDetailsPost_ShouldReturnRedirectToActionWhenValidUserId()
        {
            // Arrange
            string tempDataSuccessMessage = null;

            ChangeUserDetailsFormModel formModel = new ChangeUserDetailsFormModel()
            {
                Email    = "NewEmail",
                Username = "******"
            };

            Mock <UserManager <User> > userManager = this.GetAndSetUserManagerMock();

            userManager
            .Setup(um => um.SetEmailAsync(It.IsAny <User>(), It.IsAny <string>()))
            .ReturnsAsync(IdentityResult.Success);

            userManager
            .Setup(um => um.SetUserNameAsync(It.IsAny <User>(), It.IsAny <string>()))
            .ReturnsAsync(IdentityResult.Success);

            Mock <ITempDataDictionary> tempData = new Mock <ITempDataDictionary>();

            tempData.SetupSet(t => t[WebConstants.TempDataSuccessMessageKey]        = It.IsAny <string>())
            .Callback((string key, object successMessage) => tempDataSuccessMessage = successMessage as string);

            UsersController controller = new UsersController(null, null, userManager.Object);

            controller.TempData = tempData.Object;

            // Act
            IActionResult actionResult = await controller.ChangeUserDetails(FirstUserId, formModel);

            // Assert
            actionResult.Should().BeOfType <RedirectToActionResult>();
            actionResult.As <RedirectToActionResult>().ActionName.Should().Be("Index");

            tempDataSuccessMessage.Should().Be(MessageUpdated);
        }
Пример #41
0
        public void CallGetUser_WhenValidUser_CallsUpdatePassword()
        {
            var userId      = 1;
            var updatedUser = new UserUpdateDto
            {
                Password = "******"
            };

            var userHelper = A.Fake <IUserHelper>();

            A.CallTo(() => userHelper.GetUserId(A <HttpContext> .Ignored)).Returns(userId);
            A.CallTo(() => userHelper.MatchingUsers(A <HttpContext> .Ignored, userId)).Returns(true);

            var userRepository = A.Fake <IUserRepository>();

            var userController = new UsersController(userRepository, userHelper, null);

            var response = userController.UpdatePassword(updatedUser);

            A.CallTo(() => userRepository.UpdatePasswordHash(userId, A <string> .Ignored)).MustHaveHappened();
            A.CallTo(() => userRepository.GetUser(userId)).MustHaveHappened();
        }
Пример #42
0
        public void ReturnBadRequest_WhenExistingEmail_OnCallToUpdateEmail()
        {
            var updatedUser = new UserUpdateDto
            {
                Email = "*****@*****.**"
            };

            var userHelper = A.Fake <IUserHelper>();

            A.CallTo(() => userHelper.MatchingUsers(A <HttpContext> .Ignored, A <int> .Ignored)).Returns(true);

            var userRepository = A.Fake <IUserRepository>();

            A.CallTo(() => userRepository.UserExists(updatedUser.Email)).Returns(true);

            var userController = new UsersController(userRepository, userHelper, null);

            var response = userController.UpdateEmail(updatedUser);

            Assert.AreEqual((int)HttpStatusCode.BadRequest, ((BadRequestObjectResult)response.Result).StatusCode);
            Assert.AreEqual($"Email {updatedUser.Email} is already in use.", ((BadRequestObjectResult)response.Result).Value);
        }
Пример #43
0
        public async void Create_No_Errors()
        {
            UsersControllerMockFacade mock = new UsersControllerMockFacade();

            var mockResponse = new CreateResponse <ApiUsersResponseModel>(new FluentValidation.Results.ValidationResult());

            mockResponse.SetRecord(new ApiUsersResponseModel());
            mock.ServiceMock.Setup(x => x.Create(It.IsAny <ApiUsersRequestModel>())).Returns(Task.FromResult <CreateResponse <ApiUsersResponseModel> >(mockResponse));
            UsersController controller = new UsersController(mock.ApiSettingsMoc.Object, mock.LoggerMock.Object, mock.TransactionCoordinatorMock.Object, mock.ServiceMock.Object, mock.ModelMapperMock.Object);

            controller.ControllerContext             = new ControllerContext();
            controller.ControllerContext.HttpContext = new DefaultHttpContext();

            IActionResult response = await controller.Create(new ApiUsersRequestModel());

            response.Should().BeOfType <CreatedResult>();
            (response as CreatedResult).StatusCode.Should().Be((int)HttpStatusCode.Created);
            var createResponse = (response as CreatedResult).Value as CreateResponse <ApiUsersResponseModel>;

            createResponse.Record.Should().NotBeNull();
            mock.ServiceMock.Verify(x => x.Create(It.IsAny <ApiUsersRequestModel>()));
        }
        public async Task Request_Controller_Create()
        {
            var serviceMock = new Mock <IUserService>();
            var name        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Post(It.IsAny <UserDto>())).ReturnsAsync(
                new UserDtoCreateResult
            {
                Id       = Guid.NewGuid(),
                Name     = name,
                Email    = email,
                CreateAt = DateTime.UtcNow
            }
                );

            _controller = new UsersController(serviceMock.Object);

            Mock <IUrlHelper> url = new Mock <IUrlHelper>();

            url.Setup(u => u.Link(It.IsAny <string>(), It.IsAny <object>())).Returns(urlLocal);
            _controller.Url = url.Object;

            var userDto = new UserDto
            {
                Name  = name,
                Email = email
            };

            var result = await _controller.Post(userDto);

            Assert.True(result is CreatedResult);

            var returnCreatedUser = ((CreatedResult)result).Value as UserDtoCreateResult;

            Assert.NotNull(returnCreatedUser);
            Assert.Equal(userDto.Name, returnCreatedUser.Name);
            Assert.Equal(userDto.Email, returnCreatedUser.Email);
        }
Пример #45
0
        public async Task GetUser_AsNotAdmin_ReturnsSelf()
        {
            var dbContext = CreateInMemoryDbContext();
            var john      = dbContext.Users.Single(u => u.Email == JOHN_EMAIL);
            var httpContextAccessorStub = new Mock <IHttpContextAccessor>();

            httpContextAccessorStub.SetupGet(s => s.HttpContext.User).Returns(new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.Upn, JOHN_EMAIL)
            })));
            var emailServiceStub = new Mock <IEmailService>();
            var controller       = new UsersController(dbContext, httpContextAccessorStub.Object, emailServiceStub.Object);

            var result = await controller.GetUser(john.Id);

            var ok   = (OkObjectResult)result.Result;
            var user = (UserViewModel)ok.Value;

            Assert.IsType <ActionResult <UserViewModel> >(result);
            Assert.IsType <OkObjectResult>(result.Result);
            Assert.IsType <UserViewModel>(ok.Value);
            Assert.Equal(john.Id, user.Id);
        }
Пример #46
0
 public UserControllerTest()
 {
     AutoMapperConfiguration.Configure();
     _userService = new Mock <IUserService>();
     _mockAuth    = new Mock <IAuthenticationManager>();
     _roleService = new Mock <INamedService <RoleDTO, RoleDTOTranslate> >();
     _gameService = new Mock <IGameService>();
     _user        = new UserModel
     {
         Username = "******",
         IsBanned = false,
         Roles    =
             new List <UserRole>
         {
             UserRole.Administrator,
             UserRole.Guest,
             UserRole.Manager,
         }
     };
     _mockAuth.Setup(x => x.CurrentUser).Returns(new UserProvider(_user));
     _controller = new UsersController(_gameService.Object, _userService.Object, _roleService.Object, _mockAuth.Object);
 }
        public async Task GetDailyReports_RequestDailyReports_ReturnsCorrectReports()
        {
            using (var context = GetInitializedUsersContext())
            {
                var                 usersService  = new Services.UsersService(context, new QueueApiServiceMock());
                UsersController     controller    = new UsersController(usersService);
                DateTime            yesterday     = DateTime.Today.AddDays(-1);
                DailyEmployeeReport firstEmployee = new DailyEmployeeReport
                {
                    Date      = yesterday,
                    FirstName = "Shay",
                    LastName  = "Musachanov",
                    NumberOfPatientsTreated = 4
                };
                DailyEmployeeReport secondEmployee = new DailyEmployeeReport
                {
                    Date      = yesterday,
                    FirstName = "Daniel",
                    LastName  = "Szuster",
                    NumberOfPatientsTreated = 3
                };
                DailyEmployeeReport thirdEmployee = new DailyEmployeeReport
                {
                    Date      = yesterday,
                    FirstName = "David",
                    LastName  = "Fineboym",
                    NumberOfPatientsTreated = 2
                };

                ActionResult <List <DailyEmployeeReport> > result = await controller.GetDailyReports(yesterday);

                Assert.IsInstanceOf <ActionResult <List <DailyEmployeeReport> > >(result);
                Assert.IsInstanceOf <List <DailyEmployeeReport> >(result.Value);
                List <DailyEmployeeReport> reports = result.Value;
                Assert.AreEqual(firstEmployee, reports.Find(e => e.FirstName == firstEmployee.FirstName));
                Assert.AreEqual(secondEmployee, reports.Find(e => e.FirstName == secondEmployee.FirstName));
                Assert.AreEqual(thirdEmployee, reports.Find(e => e.FirstName == thirdEmployee.FirstName));
            }
        }
        public async Task UserControllerUpdateUserTest()
        {
            var uDAL           = new DemoUsersDAL();
            var userController = new UsersController(uDAL);

            var result = await userController.UpdateById(1, new TasklifyUser(1, "*****@*****.**", "test"));

            var objectResult = Assert.IsType <StatusCodeResult>(result);

            Assert.Equal(403, objectResult.StatusCode);

            await userController.AddUser(new TasklifyUser(1, "*****@*****.**", "test"));

            result = await userController.UpdateById(1, new TasklifyUser(1, "*****@*****.**", "test"));

            var okObjectResult = Assert.IsType <OkObjectResult>(result);
            var user           = Assert.IsType <TasklifyUser>(okObjectResult.Value);

            Assert.Equal(1, user.Id);
            Assert.Equal("*****@*****.**", user.Email);
            Assert.Equal("test", user.Name);
        }
Пример #49
0
        public void CallUserServiceMethodGetUserById_OnlyOnce()
        {
            //Arrange
            var mockedUserService = new Mock <IUserService>();

            var userId = Guid.NewGuid();
            var lists  = new List <ToDoListModel>();
            var user   = new ApplicationUser()
            {
                Id = userId.ToString(), ToDoLists = lists
            };

            mockedUserService.Setup(x => x.GetUserById(userId.ToString())).Returns(user);

            var controller = new UsersController(mockedUserService.Object);

            //Act
            controller.Edit(userId.ToString());

            //Assert
            mockedUserService.Verify(u => u.GetUserById(userId.ToString()), Times.Once);
        }
Пример #50
0
        public async Task GetUsers_Void_TaskActionResultContainsIEnumerableOfUser()
        {
            // Arrange
            List <User> expectedData = GetFakeList();

            InitializeInmemoryDatabase(out DbContextOptions <GameReviewsContext> options, GetFakeList());

            // Act
            using (var context = new GameReviewsContext(options))
            {
                UsersController    usersController = new UsersController(context);
                IEnumerable <User> users           = (await usersController.GetUsers()).Value;

                // Assert
                Assert.Equal(expectedData.Count, users.Count());

                for (int i = 0; i < expectedData.Count; ++i)
                {
                    Assert.True(AreEqual(expectedData[i], users.ElementAt(i)));
                }
            }
        }
        public async Task PostEmployeeLogin_LoginWithWrongPassword_ReturnsUnauthorizedAndEmployeeIsOffline()
        {
            using (var context = GetInitializedUsersContext())
            {
                var             usersService = new Services.UsersService(context, new QueueApiServiceMock());
                UsersController controller   = new UsersController(usersService);
                EmployeeLogin   login        = new EmployeeLogin
                {
                    Username      = "******",
                    Password      = "******",
                    ServiceType   = ServiceType.Pharmacist,
                    StationNumber = 1
                };

                ActionResult <EmployeeInfo> result = await controller.PostEmployeeLogin(login);

                Assert.IsInstanceOf <ActionResult <EmployeeInfo> >(result);
                Assert.IsInstanceOf <UnauthorizedObjectResult>(result.Result);
                bool isOnline = context.Employees.Where(e => e.Username == login.Username).Single().Online;
                Assert.IsFalse(isOnline);
            }
        }
Пример #52
0
        public async void All_Exists()
        {
            UsersControllerMockFacade mock = new UsersControllerMockFacade();
            var record  = new ApiUsersResponseModel();
            var records = new List <ApiUsersResponseModel>();

            records.Add(record);
            mock.ServiceMock.Setup(x => x.All(It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(records));
            UsersController controller = new UsersController(mock.ApiSettingsMoc.Object, mock.LoggerMock.Object, mock.TransactionCoordinatorMock.Object, mock.ServiceMock.Object, mock.ModelMapperMock.Object);

            controller.ControllerContext             = new ControllerContext();
            controller.ControllerContext.HttpContext = new DefaultHttpContext();

            IActionResult response = await controller.All(1000, 0);

            response.Should().BeOfType <OkObjectResult>();
            (response as OkObjectResult).StatusCode.Should().Be((int)HttpStatusCode.OK);
            var items = (response as OkObjectResult).Value as List <ApiUsersResponseModel>;

            items.Count.Should().Be(1);
            mock.ServiceMock.Verify(x => x.All(It.IsAny <int>(), It.IsAny <int>()));
        }
Пример #53
0
        public void UsersLogoutNoUserLogged_ShouldThrowExceptionWithCorrectMessage()
        {
            // Arrange
            IHotelBookingSystemData data = new HotelBookingSystemData();
            User user = new User("test user", "password", Roles.User);
            UsersController controller = new UsersController(data, user);

            // Act
            controller.CurrentUser = null;
            string result = string.Empty;
            try
            {
                IView view = controller.Logout();
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }

            string expected = "There is no currently logged in user.";

            // Assert
            Assert.AreEqual(expected, result);
        }
Пример #54
0
        public void AllTest()
        {
            UserRepositorySpy spy_repository = new UserRepositorySpy();
            CredentialsCheckerSpy_AlwaysPass spy_checker = new CredentialsCheckerSpy_AlwaysPass();
            UsersController target = new UsersController(spy_repository, spy_checker);
            List<User> expected = new List<User>();
            expected.Add(new User() { Email = "*****@*****.**", FirstName = "First name", Id = 1, LastName = "Last name", Login = "******", Photo = null });
            expected.Add(new User() { Email = "*****@*****.**", FirstName = "Ostap", Id = 2, LastName = "Bender", Login = "******", Photo = null });
            spy_repository.GetAllUsersResult = expected;

            /*
            var config = new HttpConfiguration();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/1.0/users/all");
            var route = config.Routes.MapHttpRoute("TestApi", "api/1.0/{controller}/{action}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "users" }, { "action", "all" } });
            target.ControllerContext = new HttpControllerContext(config, routeData, request);
            target.Request = request;
            target.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            */

            List<User> actual = target.All();

            Assert.AreEqual(expected, actual);
        }
        public void Post_LoginUser_InvalidLogin_NoUserWithSuchAuthCode()
        {
            FakeRepository<User> userFakeRepository = new FakeRepository<User>();
            UsersController usersController = new UsersController(userFakeRepository);
            SetupController(usersController);

            User user = new User()
            {
                AuthCode = "9876543210987654321098765432109876543210",
                Username = "******",
                Nickname = "TestNickname",
            };

            userFakeRepository.entities.Add(user);

            UserModel model = new UserModel()
            {
                AuthCode = "0123456789012345678901234567890123456789",
                Username = "******",
                Nickname = "TestNickname"
            };

            var response = usersController.LoginUser(model);
        }
 public void ControllerAuthorize_HasNoCurrentUser_ShouldThrowException()
 {
     var testController = new UsersController(new HotelBookingSystemData(), null);
     testController.Authorize(Roles.VenueAdmin);
 }
 public void ControllerAuthorize_IncorrectAuthorizationAccess_ShouldThrowException()
 {
     var testController = new UsersController(new HotelBookingSystemData(),
         new User("NormalUser", "122343434", Roles.User));
     testController.Authorize(Roles.VenueAdmin);
 }
Пример #58
0
    private void SaveSessionInDB()
    {
        SessionValue _objSessionValue = null;
        HttpContext.Current.Request.Path.ToString();
        TributesPortal.Utilities.StateManager stateManager = StateManager.Instance;
        _objSessionValue = (SessionValue)stateManager.Get("objSessionvalue", StateManager.State.Session);

        if (!Equals(_objSessionValue, null))
        {

            if (_objSessionValue.UserId > 0)
            {
                UsersController _controller = new UsersController();
                _controller.SessionStore(_objSessionValue, HttpContext.Current.Session.SessionID);

            }
        }
    }
        public void Initialize()
        {
            // Set up Automapper
            WebApiConfig.CreateMaps();

            // Set up repositories
            _userRepositoryMock = new Mock<IUserRepository>();
            _externalLoginRepositoryMock = new Mock<IExternalLoginRepository>();

            // Set data for external logins
            _externalLogins = new[]
            {
                new ExternalLogin
                {
                    ExternalLoginID = 1,
                    UserID = _userIDWithExternalLogins,
                    LoginProvider = "AAAA",
                    ProviderKey = "BBBBB"
                },
                               new ExternalLogin
                {
                    ExternalLoginID = 2,
                    UserID = _userIDWithExternalLogins,
                    LoginProvider = "AAAA",
                    ProviderKey = "CCCCC"
                }
            };

            // Set up users: first is authorized, second is unauthorized
            _users = new[]
            {
                new User {
                Id = _userIDAuthorized,
                Authorized = true,
                PasswordHash = "XXX",
                SecurityStamp = "YYY",
                UserName = "******"
                },
                 new User {
                Id = _userIDUnauthorized,
                Authorized = false,
                PasswordHash = "XXX",
                SecurityStamp = "YYY",
                UserName = "******"
                }
            };

            _userRepositoryMock.Setup(u => u.GetAll()).Returns(_users.AsQueryable());
            _userRepositoryMock.Setup(u => u.GetByID(_userIDAuthorized))
                                                    .Returns(_users[_userAuthorizedIndexInArray]);
            _userRepositoryMock.Setup(u => u.GetByID(_userIDUnauthorized))
                                         .Returns(_users[_userUnauthorizedIndexInArray]);

            // Set up unit of work and controller
            _unitOfWorkMock = new Mock<IUnitOfWork>();
            _controller = new UsersController(_externalLoginRepositoryMock.Object, _userRepositoryMock.Object,
                                                        _unitOfWorkMock.Object);
        }
 public void UsersLogout_NotLoggedInUser_ShouldThrowException()
 {
     var testController = new UsersController(new HotelBookingSystemData(), null);
     testController.Logout();
 }