Esempio n. 1
0
        private async Task <bool> CreateUser(AppUser user)
        {
            if (DefaultUserRoleIds.Count < 1)
            {
                DefaultUserRoleIds = _userContext.Roles.Where(x => x.Name.Equals(Roles.Users) || x.Name.Equals(Roles.Developer))
                                     .Select(x => x.Id).ToList();
            }

            var tenantIds = tenantDb.Tenants.Select(x => x.Id).ToList();

            var result = await AppUserService.CreateUser(
                pvtTenant.Id,
                _userManager,
                _userContext,
                user,
                DefaultUserRoleIds,
                DefaultUserPermissions,
                tenantIds);

            if (result.Succeeded)
            {
                var sendResult = await SendActiveEmail(user);

                return(true);
            }

            AddErrors(result);

            return(false);
        }
Esempio n. 2
0
 public ArticleController()
 {
     _categoryService    = new CategoryService();
     _subCategoryService = new SubCategoryService();
     _appUserService     = new AppUserService();
     _articleService     = new ArticleService();
 }
        public async Task <List <Role_AppUserDTO> > SingleListAppUser([FromBody] Role_AppUserFilterDTO Role_AppUserFilterDTO)
        {
            AppUserFilter AppUserFilter = new AppUserFilter();

            AppUserFilter.Skip        = 0;
            AppUserFilter.Take        = 20;
            AppUserFilter.OrderBy     = AppUserOrder.Id;
            AppUserFilter.OrderType   = OrderType.ASC;
            AppUserFilter.Selects     = AppUserSelect.Id | AppUserSelect.Username | AppUserSelect.DisplayName | AppUserSelect.Email | AppUserSelect.Phone;
            AppUserFilter.Id          = Role_AppUserFilterDTO.Id;
            AppUserFilter.Username    = Role_AppUserFilterDTO.Username;
            AppUserFilter.DisplayName = Role_AppUserFilterDTO.DisplayName;
            AppUserFilter.Email       = Role_AppUserFilterDTO.Email;
            AppUserFilter.Phone       = Role_AppUserFilterDTO.Phone;
            AppUserFilter.StatusId    = new IdFilter {
                Equal = StatusEnum.ACTIVE.Id
            };

            //if (AppUserFilter.Id == null) AppUserFilter.Id = new IdFilter();
            //AppUserFilter.Id.In = await FilterAppUser(AppUserService, OrganizationService, CurrentContext);

            List <AppUser> AppUsers = await AppUserService.List(AppUserFilter);

            List <Role_AppUserDTO> Role_AppUserDTOs = AppUsers
                                                      .Select(x => new Role_AppUserDTO(x)).ToList();

            return(Role_AppUserDTOs);
        }
        public async Task DisableAppUser()
        {
            int id = 1;

            var fakeUsers = new AppUser[] {
                new AppUser()
                {
                    Id = 1
                },
                new AppUser()
                {
                    Id = 2
                }
            };

            var mockedDb = new Mock <AppUserContext>();

            mockedDb.Setup(a => a.AppUsers).ReturnsDbSet(fakeUsers);

            var service = new AppUserService(_mapper, mockedDb.Object, _jwtService, _logger);

            var result = await service.Disable(id);

            Assert.True(result);
        }
Esempio n. 5
0
        public IHttpActionResult GetAllAppUsers()
        {
            AppUserService appUserService = CreateAppUserService();
            var            users          = appUserService.GetAllUsers();

            return(Ok(users));
        }
Esempio n. 6
0
        public IHttpActionResult GetAppUserId(string id)
        {
            AppUserService appUserService = CreateAppUserService();
            var            appUserDetail  = appUserService.GetUserId(id);

            return(Ok(appUserDetail));
        }
Esempio n. 7
0
        public ActionResult GetCurrentUser()
        {
            var currentUserId = GetCurrentUserId();
            var appUser       = AppUserService.QueryAppUserById(Guid.Parse(currentUserId));

            return(Json(new { state = "success", appUser = appUser }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 8
0
        private AppUserService CreateAppUserService()
        {
            var id            = User.Identity.GetUserId();
            var appUserDetail = new AppUserService(id.ToString());

            return(appUserDetail);
        }
Esempio n. 9
0
 public UnitOfWork(TestDBContext context)
 {
     _context        = context;
     userService     = new AppUserService(_context);
     articleService  = new ArticleService(_context);
     categoryService = new CategoryService(_context);
 }
Esempio n. 10
0
        public async Task WhenGetMemberAsyncCalled_UserIsMappedToMemberDtoAsync()
        {
            /*
             *
             * UNIT TESTING WITH DEPENDENCY INJECTION & API
             *
             * **/

            // - - - ARRANGE - - -

            //create mock version of Interface (to fake dependency injection)
            var mockRepo = new Mock <IAppUserRepository>();


            //Fake the return value of a Mock Dependency
            mockRepo.Setup(x => x.GetUser(It.IsAny <int>())).ReturnsAsync(fakeUser);

            //Initialize AutoMapper for Unit Tests (not faked/mocked)
            var config = new MapperConfiguration(x => x.AddProfile <AutoMapperProfile>());

            //pass mocked interface to fake dependency injection
            var service = new AppUserService(mockRepo.Object, config.CreateMapper());


            // - - - ACT - - -

            MemberDTO result = await service.GetMemberAsync(1);

            // - - - ASSERT - - -

            Assert.NotNull(result);
            Assert.AreEqual("faketown", result.City);
        }
Esempio n. 11
0
        //[AuthenticationFilter]
        //[Authorize]
        //[ValidateAntiForgeryToken]
        public ActionResult Index()
        {
            AppUserService appUserService = new AppUserService();
            var            appUSer        = appUserService.GetAll();
            var            countUsers     = appUSer.Count();

            Session["countUsers"] = countUsers.ToString();//kullanıcı sayısı

            ProductService productService = new ProductService();
            var            product        = productService.GetAll();
            var            countProduct   = product.Count();

            Session["countProduct"] = countProduct;// urun sayısı

            var sonKullanici = appUserService.GetAll().OrderByDescending(x => x.CreatedDate).Take(3);

            TempData["sonKullanıcı"] = sonKullanici;

            var sonUrun = productService.GetAll().OrderByDescending(x => x.CreatedDate).Take(3);

            TempData["sonUrun"] = sonUrun;

            OrderDetailService orderDetailService = new OrderDetailService();
            var totalPrice = orderDetailService.GetAll().Sum(x => x.Quantity * x.Price * 1 - (x.Discount));

            Session["totalPrice"] = totalPrice;

            var orderDetail      = orderDetailService.GetAll();
            var countOrderDetail = orderDetail.Count();

            Session["countOrder"] = countOrderDetail;
            return(View());
        }
        public async Task AppUserCollectionShouldReturnInactiveRecordsIfSpecified()
        {
            var fakeUsers = new AppUser[] {
                new AppUser()
                {
                    IsActive = true
                },
                new AppUser()
                {
                    IsActive = true
                },
                new AppUser()
                {
                    IsActive = false
                }
            };

            var mockedDb = new Mock <AppUserContext>();

            mockedDb.Setup(a => a.AppUsers).ReturnsDbSet(fakeUsers);

            var filter = new AppUserFilter();

            filter.IsActive = false;

            var service = new AppUserService(_mapper, mockedDb.Object, _jwtService, _logger);

            var collection = await service.Collection(filter);

            var expectedCount = 1;
            var actualCount   = collection.Count;

            Assert.Equal(expectedCount, actualCount);
        }
Esempio n. 13
0
        public void UpdateFocusedSchoolYear_Should_FailSilentlyBecauseItJustDoes()
        {
            var announcements = new List <Announcement>();

            EntityFrameworkMocks.SetupMockDbSet(
                EntityFrameworkMocks.GetQueryableMockDbSet(announcements),
                ValidationPortalDbContextMock,
                x => x.Announcements,
                x => x.Announcements = It.IsAny <DbSet <Announcement> >(),
                announcements);

            var oldFocusedSchoolYear = 12345;
            var newFocusedSchoolYear = 23456;
            var appUserSessionId     = 123;

            var schoolYears = new List <SchoolYear>(new[]
            {
                new SchoolYear
                {
                    Id      = newFocusedSchoolYear,
                    Enabled = true
                }
            });

            EntityFrameworkMocks.SetupMockDbSet(
                EntityFrameworkMocks.GetQueryableMockDbSet(schoolYears),
                ValidationPortalDbContextMock,
                x => x.SchoolYears,
                x => x.SchoolYears = It.IsAny <DbSet <SchoolYear> >(),
                schoolYears);

            var userIdentity = new ValidationPortalIdentity();

            var appUserSession = new AppUserSession
            {
                Id = appUserSessionId.ToString(),
                FocusedSchoolYearId = oldFocusedSchoolYear,
                UserIdentity        = userIdentity
            };

            DbContextFactoryMock.Setup(x => x.Create()).Returns(ValidationPortalDbContextMock.Object);

            var httpContext = new HttpContext(
                new HttpRequest(string.Empty, "http://wearedoubleline.com", string.Empty),
                new HttpResponse(new StringWriter()));

            httpContext.Items[AppUserService.SessionItemName] = null;
            HttpContextProviderMock.SetupGet(x => x.CurrentHttpContext).Returns(httpContext);

            LoggingServiceMock.Setup(x => x.LogDebugMessage(It.IsAny <string>()));

            var appUserService = new AppUserService(
                DbContextFactoryMock.Object,
                HttpContextProviderMock.Object,
                LoggingServiceMock.Object);

            appUserService.UpdateFocusedSchoolYear(newFocusedSchoolYear);

            ValidationPortalDbContextMock.Verify(x => x.SaveChanges(), Times.Never);
        }
Esempio n. 14
0
        public void AppUserExistByNameFalse()
        {
            IAppUserService service  = new AppUserService();
            const string    userName = "******"; //Hardcoded user in DB //todo replace with a mock

            Assert.False(service.AppUserExist(userName));
        }
 public TweetController()
 {
     _commentService = new CommentService();
     _appUserService = new AppUserService();
     _likeService    = new LikeService();
     _tweetService   = new TweetService();
 }
Esempio n. 16
0
        public void CheckAppUserDetailsAreEqualLikeModel()
        {
            //Arrange
            AppUser appuser = new AppUser()
            {
                Id        = 6,
                FirstName = "test",
                LastName  = "unit",
                City      = "test"
            };

            var config = new MapperConfiguration(c =>
            {
                c.AddProfile(new MappingProfile());
            });
            var mapper = config.CreateMapper();

            var mock = new Mock <IAppUserRepository>();

            mock.Setup(s => s.GetAppUser(6)).Returns(appuser);

            var manager = new AppUserService(mapper, mock.Object);

            //Act
            var result = manager.GetAppUserDetails(6);

            //Assert
            result.Should().NotBeNull();
            result.Id.Should().Equals(appuser.Id);
            appuser.Id = 7;
            result.Id.Should().Equals(appuser.Id);
            result.FirstName.Should().Equals(appuser.FirstName);
            result.LastName.Should().Equals(appuser.LastName);
        }
Esempio n. 17
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool authorized = false;

            if (HttpContext.Current.Session["role"] == null)
            {
                AppUserService service = new AppUserService();
                AppUser        dbUser  = service.FindByUserName(HttpContext.Current.User.Identity.Name);
                HttpContext.Current.Session["role"] = dbUser;
            }

            var    user     = HttpContext.Current.Session["role"] as AppUser;
            string userRole = Enum.GetName(typeof(Role), user.Role);

            foreach (var role in this.UserProfilesRequired)
            {
                if (userRole == role)
                {
                    authorized = true;
                    break;
                }
            }

            if (!authorized)
            {
                var url      = new UrlHelper(filterContext.RequestContext);
                var logonUrl = url.Action("NotAuthorized", "Account", new { Id = 302, Area = "Admin" });
                filterContext.Result = new RedirectResult(logonUrl);

                return;
            }
        }
Esempio n. 18
0
        public void DeletedAppUserShoundNotExistInDatabase()
        {
            //Arrange
            NewAppUserVm appUserToAdd = new NewAppUserVm()
            {
                Id         = 1,
                FirstName  = "test",
                PositionId = 1
            };

            var options = new DbContextOptionsBuilder <Context>()
                          .UseInMemoryDatabase("UsersDirectoryMVC")
                          .Options;

            var config = new MapperConfiguration(c =>
            {
                c.AddProfile(new MappingProfile());
            });
            var mapper = config.CreateMapper();

            using (var context = new Context(options))
            {
                //Act
                var appUserService = new AppUserService(mapper, new AppUserRepository(context));
                var result         = appUserService.AddAppUser(appUserToAdd);
                appUserService.DeleteAppUser(1);
                var deletedAppUser = appUserService.GetAppUserDetails(1);

                //Assert
                deletedAppUser.Should().BeNull();
            }
        }
Esempio n. 19
0
        public void CheckEmployerIdExistAfterAdd()
        {
            //Arrange
            NewAppUserVm appUserToAdd = new NewAppUserVm()
            {
                Id        = 6,
                FirstName = "test",
                LastName  = "unit"
            };

            AppUser appUser = new AppUser()
            {
                Id        = 6,
                FirstName = "test",
                LastName  = "unit"
            };

            var config = new MapperConfiguration(c =>
            {
                c.AddProfile(new MappingProfile());
            });
            var mapper = config.CreateMapper();

            var mock = new Mock <IAppUserRepository>();

            mock.Setup(s => s.AddAppUser(appUser)).Returns(appUser.Id);

            var manager = new AppUserService(mapper, mock.Object);

            //Act
            var result = manager.AddAppUser(appUserToAdd);

            //Assert
            result.Should().Equals(appUser.Id);
        }
Esempio n. 20
0
 public CommentController()
 {
     _commentService = new CommentService();
     _appUserService = new AppUserService();
     _likeService    = new LikeService();
     _postService    = new PostService();
 }
Esempio n. 21
0
        public void CheckAppUserIfExistAfterAdd()
        {
            //Arrange
            NewAppUserVm appUserToAdd = new NewAppUserVm()
            {
                Id         = 1,
                FirstName  = "test",
                PositionId = 1
            };

            var options = new DbContextOptionsBuilder <Context>()
                          .UseInMemoryDatabase("UsersDirectoryMVC")
                          .Options;

            var config = new MapperConfiguration(c =>
            {
                c.AddProfile(new MappingProfile());
            });
            var mapper = config.CreateMapper();

            using (var context = new Context(options))
            {
                //Act
                var appUserService = new AppUserService(mapper, new AppUserRepository(context));
                var result         = appUserService.AddAppUser(appUserToAdd);

                //Assert
                context.AppUsers.FirstOrDefaultAsync(e => e.Id == result).Should().NotBeNull();
            }
        }
Esempio n. 22
0
        //Auth yapma aşamasında bu metot çalışacak
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool authorized = false;

            AppUserService service = new AppUserService();
            //FormsAuth içerisine atılan username httpcontext ile yakalanır.
            AppUser user = service.FindByUserName(HttpContext.Current.User.Identity.Name);

            //Kullanıcının rolü yakalanır.
            string userRole = Enum.GetName(typeof(Role), user.Role);

            //Kullanıcı belirtilen rollerden birine uyuyorsa devam edebilir.
            foreach (var role in this.UserProfilesRequired)
            {
                if (userRole == role)
                {
                    authorized = true;
                    break;
                }
            }

            //Eğer rol kabul edilen roller ile uyuşmuyorsa hata sayfasına yönlendir.
            if (!authorized)
            {
                var url      = new UrlHelper(filterContext.RequestContext);
                var logonUrl = url.Action("Http", "Error", new { Id = 401, Area = "" });
                filterContext.Result = new RedirectResult(logonUrl);
            }
        }
Esempio n. 23
0
        public void CheckPositionNameAreEqualLikePositionName()
        {
            //Arrange
            var positionName = "test";

            Position position = new Position()
            {
                Id   = 1,
                Name = "test"
            };

            var config = new MapperConfiguration(c =>
            {
                c.AddProfile(new MappingProfile());
            });
            var mapper = config.CreateMapper();

            var options = new DbContextOptionsBuilder <Context>()
                          .UseInMemoryDatabase("UsersDirectoryMVC")
                          .Options;


            using (var context = new Context(options))
            {
                //Act
                var appUserService = new AppUserService(mapper, new AppUserRepository(context));
                context.Positions.Add(position);
                context.SaveChanges();
                var result = appUserService.GetAppUserPositionName(1);

                //Assert
                result.Should().NotBeNull();
                result.Should().Equals(positionName);
            }
        }
Esempio n. 24
0
        public async Task <List <Tracking_AppUserDTO> > FilterListAppUser([FromBody] Tracking_AppUserFilterDTO Tracking_AppUserFilterDTO)
        {
            if (!ModelState.IsValid)
            {
                throw new BindException(ModelState);
            }

            AppUserFilter AppUserFilter = new AppUserFilter();

            AppUserFilter.Skip        = 0;
            AppUserFilter.Take        = 20;
            AppUserFilter.OrderBy     = AppUserOrder.Id;
            AppUserFilter.OrderType   = OrderType.ASC;
            AppUserFilter.Selects     = AppUserSelect.ALL;
            AppUserFilter.Id          = Tracking_AppUserFilterDTO.Id;
            AppUserFilter.Username    = Tracking_AppUserFilterDTO.Username;
            AppUserFilter.Password    = Tracking_AppUserFilterDTO.Password;
            AppUserFilter.DisplayName = Tracking_AppUserFilterDTO.DisplayName;
            AppUserFilter.Email       = Tracking_AppUserFilterDTO.Email;
            AppUserFilter.Phone       = Tracking_AppUserFilterDTO.Phone;

            List <AppUser> AppUsers = await AppUserService.List(AppUserFilter);

            List <Tracking_AppUserDTO> Tracking_AppUserDTOs = AppUsers
                                                              .Select(x => new Tracking_AppUserDTO(x)).ToList();

            return(Tracking_AppUserDTOs);
        }
Esempio n. 25
0
        public PartialViewResult MemberCount()
        {
            AppUserService _appUserService = new AppUserService();

            ViewBag.MemberCount = _appUserService.MemberCount();
            return(PartialView("_MemberCount"));
        }
        public async Task WhenGetMemberAsyncCalled_UserIsMappedToMemberDTOAsync()
        {
            //ARRANGE
            //mock a dependency
            //var mockRepo = new Mock<IAppUserRepository>();

            AppUser fakeUser = new AppUser
            {
                City            = "FakeTown",
                CountryOfOrigin = "FakeCountry",
                Gender          = "Fake",
                Interests       = "Fake it",
                Name            = "Faker McGee",
                DateOfBirth     = new System.DateTime(1969, 4, 20)
            };

            //Fake the return value of a mock dependency
            mockRepo.Setup(x => x.GetUserAsync(It.IsAny <int>())).ReturnsAsync(fakeUser);

            //initialize AutoMapper for Unit Tests
            //var config = new MapperConfiguration(x =>
            //x.AddProfile<AutoMapperProfile>());

            //inject fake dependencies and automapper
            var service = new AppUserService(mockRepo.Object, config.CreateMapper());

            //ACT
            var result = await service.GetMemberAsync(1);

            //ASSERT
            Assert.NotNull(result);
            Assert.AreEqual("FakeTown", result.City);
        }
        public void UpdateFocusedSchoolYear_WithInvalidYear_Should_LogError()
        {
            var newFocusedSchoolYear = 23456;
            var appUserSessionId     = 123;

            var appUserSession = new AppUserSession
            {
                Id           = appUserSessionId.ToString(),
                UserIdentity = null
            };

            DbContextFactoryMock.Setup(x => x.Create()).Returns(ValidationPortalDbContextMock.Object);

            var httpContext = new HttpContext(
                new HttpRequest(string.Empty, "http://wearedoubleline.com", string.Empty),
                new HttpResponse(new StringWriter()));

            httpContext.Items[AppUserService.SessionItemName] = appUserSession;
            HttpContextProviderMock.SetupGet(x => x.CurrentHttpContext).Returns(httpContext);

            LoggingServiceMock.Setup(x => x.LogDebugMessage(It.IsAny <string>()));
            LoggingServiceMock.Setup(x => x.LogErrorMessage(It.IsAny <string>()));

            var appUserService = new AppUserService(
                DbContextFactoryMock.Object,
                HttpContextProviderMock.Object,
                LoggingServiceMock.Object);

            appUserService.UpdateFocusedSchoolYear(newFocusedSchoolYear);

            ValidationPortalDbContextMock.Verify(x => x.SaveChanges(), Times.Never);
            LoggingServiceMock.Verify(x => x.LogErrorMessage(It.IsAny <string>()), Times.Once());
        }
Esempio n. 28
0
        public void AppUserExistByNameTrue()
        {
            IAppUserService service  = new AppUserService();
            const string    userName = "******"; //Hardcoded user in DB //todo replace with a mock

            Assert.True(service.AppUserExist(userName));
        }
Esempio n. 29
0
 public HomeController()
 {
     _articleService = new ArticleService();
     _appUserService = new AppUserService();
     _commentService = new CommentService();
     _likeService    = new LikeService();
 }
Esempio n. 30
0
        public void CheckAppUserToEditDetailsAreEqualLikeModel()
        {
            //Arrange
            NewAppUserVm appUser = new NewAppUserVm()
            {
                Id         = 1,
                FirstName  = "test2",
                PositionId = 1
            };

            var config = new MapperConfiguration(c =>
            {
                c.AddProfile(new MappingProfile());
            });
            var mapper = config.CreateMapper();

            var options = new DbContextOptionsBuilder <Context>()
                          .UseInMemoryDatabase("UsersDirectoryMVC")
                          .Options;


            using (var context = new Context(options))
            {
                //Act
                var appUserService = new AppUserService(mapper, new AppUserRepository(context));
                appUserService.AddAppUser(appUser);
                var result = appUserService.GetAppUserForEdit(1);

                //Assert
                result.Should().NotBeNull();
                result.Should().Equals(appUser);
                context.AppUsers.FirstOrDefaultAsync(e => e.Id == result.Id).Should().NotBeNull();
            }
        }
Esempio n. 31
0
		public void RegisterUser(string username) {
			AppUserService appUserService = new AppUserService();
			var appUser = appUserService.GetUserByUsername(username);

			if (appUser != null) {
				var connectionId = Context.ConnectionId;

				if (UsersNotifier.UsersConnections.ContainsKey(appUser.Id)) {
					UsersNotifier.UsersConnections[appUser.Id] = new UserFullDuplexConnection {ConnectionId = connectionId};
				} else {
					UsersNotifier.UsersConnections.Add(appUser.Id, new UserFullDuplexConnection {ConnectionId = connectionId});
				}
			}
		}
		public AuthRepository() {
			AppUserService appUserService = new AppUserService();
			UserStore<AppUser> userStore = new UserStore<AppUser>(appUserService.Collection);
			userManager = new UserManager<AppUser>(userStore);
		}