public void GetAllAddressesByUserWithDataShouldReturnCorrectResults()
        {
            var addressRepository = new Mock <IRepository <Address> >();
            var userRepository    = new Mock <IRepository <ApplicationUser> >();
            var userStoreMock     = new Mock <IUserStore <ApplicationUser> >();
            var userManager       = new Mock <UserManager <ApplicationUser> >(userStoreMock.Object, null, null, null, null, null, null, null, null);

            userRepository.Setup(r => r.All()).Returns(this.DummyDataForUser().AsQueryable());
            var user = userRepository.Object.All().SingleOrDefault(x => x.FirstName == "root");

            addressRepository.Setup(r => r.All()).Returns(this.DummyDataAddresses(user.Id).AsQueryable());

            var service         = new ApplicationUserService(userRepository.Object, addressRepository.Object, userManager.Object);
            var actualResults   = service.GetAllAddresses <AddressViewModel>(user.Id).ToList();
            var expectedResults = this.DummyDataAddresses(user.Id).ToList();

            for (int i = 0; i < expectedResults.Count; i++)
            {
                var expectedEntry = expectedResults[i];
                var actualEntry   = actualResults[i];

                Assert.True(expectedEntry.City == actualEntry.City, "City does not match");
                Assert.True(expectedEntry.Description == actualEntry.Description, "Description does not match");
                Assert.True(expectedEntry.CityCode == actualEntry.CityCode, "CityCode does not match");
                Assert.True(expectedEntry.StreetAddress == actualEntry.StreetAddress, "StreetAddress does not match");
            }
        }
Пример #2
0
        protected void InitTasks()
        {
            var iRPCSDbAccessor       = (IRPCSDbAccessor) new RPCSSingletonDbAccessor(_rpcsContextOptions);
            var rPCSRepositoryFactory = (IRepositoryFactory) new RPCSRepositoryFactory(iRPCSDbAccessor);

            var userService = (IUserService) new UserService(rPCSRepositoryFactory, _httpContextAccessor);
            var tsAutoHoursRecordService  = (ITSAutoHoursRecordService) new TSAutoHoursRecordService(rPCSRepositoryFactory, userService);
            var vacationRecordService     = (IVacationRecordService) new VacationRecordService(rPCSRepositoryFactory, userService);
            var reportingPeriodService    = (IReportingPeriodService) new ReportingPeriodService(rPCSRepositoryFactory);
            var productionCalendarService = (IProductionCalendarService) new ProductionCalendarService(rPCSRepositoryFactory);
            var tsHoursRecordService      = (ITSHoursRecordService) new TSHoursRecordService(rPCSRepositoryFactory, userService, _tsHoursRecordServiceLogger);
            var projectService            = (IProjectService) new ProjectService(rPCSRepositoryFactory, userService);
            var departmemtService         = new DepartmentService(rPCSRepositoryFactory, userService);
            var employeeService           = (IEmployeeService) new EmployeeService(rPCSRepositoryFactory, departmemtService, userService);
            var projectMembershipService  = (IProjectMembershipService) new ProjectMembershipService(rPCSRepositoryFactory);
            var projectReportRecords      = new ProjectReportRecordService(rPCSRepositoryFactory);
            var employeeCategoryService   = new EmployeeCategoryService(rPCSRepositoryFactory);
            var applicationUserService    = new ApplicationUserService(rPCSRepositoryFactory, employeeService, userService, departmemtService,
                                                                       _httpContextAccessor, _memoryCache, projectService, _onlyofficeOptions);
            var appPropertyService = new AppPropertyService(rPCSRepositoryFactory, _adOptions, _bitrixOptions, _onlyofficeOptions, _timesheetOptions);
            var financeService     = new FinanceService(rPCSRepositoryFactory, iRPCSDbAccessor, applicationUserService, appPropertyService, _ooService);
            var timesheetService   = new TimesheetService(employeeService, employeeCategoryService, tsAutoHoursRecordService,
                                                          tsHoursRecordService, projectService, projectReportRecords, vacationRecordService, productionCalendarService, financeService, _timesheetOptions);
            var projectExternalWorkspaceService = new ProjectExternalWorkspaceService(rPCSRepositoryFactory);
            var jiraService = new JiraService(userService, _jiraOptions, projectExternalWorkspaceService, projectService);

            _taskTimesheetProcessing = new TimesheetProcessingTask(tsAutoHoursRecordService, vacationRecordService, reportingPeriodService,
                                                                   productionCalendarService, tsHoursRecordService, userService, projectService, employeeService, projectMembershipService,
                                                                   timesheetService, _timesheetOptions, _smtpOptions, _jiraOptions, jiraService, projectExternalWorkspaceService);
        }
Пример #3
0
        private async Task NextAsync()
        {
            try
            {
                await ButtonSpinner.SpinAsync(async() =>
                {
                    var user = await ApplicationUserService.GetUserByEmailAsync(UserEmailModel.Email);
                    if (user == null)
                    {
                        ValidationErrorMessage.DisplayError(nameof(UserEmailModel.Email), HESException.GetMessage(HESCode.UserNotFound));
                        return;
                    }

                    PasswordSignInModel.Email = UserEmailModel.Email;
                    HasSecurityKey            = (await Fido2Service.GetCredentialsByUserEmail(UserEmailModel.Email)).Count > 0;
                    AuthenticationStep        = AuthenticationStep.EnterPassword;
                });
            }
            catch (HESException ex)
            {
                ValidationErrorMessage.DisplayError(nameof(UserEmailModel.Email), ex.Message);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                SetErrorMessage(ex.Message);
            }
        }
Пример #4
0
        public void Get_All_Users_Equal_To_GetAll()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "Get_All_Users").Options;

            using (var ctx = new ApplicationDbContext(options))
            {
                ctx.ApplicationUsers.Add(new ApplicationUser
                {
                    Id       = "228",
                    UserName = "******"
                });

                ctx.ApplicationUsers.Add(new ApplicationUser
                {
                    Id       = "3332",
                    UserName = "******"
                });

                ctx.SaveChanges();
            }

            //Act
            using (var ctx = new ApplicationDbContext(options))
            {
                var appUserService = new ApplicationUserService(ctx);
                var users          = appUserService.GetAll();

                //Assert
                Assert.AreEqual(users.Count(), 2);
            }
        }
Пример #5
0
        private async Task InviteAdminAsync()
        {
            try
            {
                await ButtonSpinner.SpinAsync(async() =>
                {
                    var callBakcUrl = await ApplicationUserService.InviteAdministratorAsync(Invitation.Email, NavigationManager.BaseUri);
                    await EmailSenderService.SendUserInvitationAsync(Invitation.Email, callBakcUrl);
                    await ToastService.ShowToastAsync("Administrator invited.", ToastType.Success);
                    await SynchronizationService.UpdateAdministrators(ExceptPageId);
                    await ModalDialogService.CloseAsync();
                });
            }
            catch (AlreadyExistException ex)
            {
                ValidationErrorMessage.DisplayError(nameof(Invitation.Email), ex.Message);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                await ToastService.ShowToastAsync(ex.Message, ToastType.Error);

                await ModalDialogService.CancelAsync();
            }
        }
Пример #6
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            await SetInitialDataAsync();

            if (ModelState.IsValid)
            {
                ApplicationUserDTO applicationUserDTO = new ApplicationUserDTO
                {
                    Email    = model.Email,
                    Password = model.Password,
                    //Address = model.Address,
                    //Name = model.Name,
                    RolesID = { 1 }
                };

                OperationDetails operationDetails = await ApplicationUserService.Create(applicationUserDTO);

                if (operationDetails.Succedeed)
                {
                    return(View("SuccessRegister"));
                }
                else
                {
                    ModelState.AddModelError(operationDetails.Property, operationDetails.Message);
                }
            }
            return(View(model));
        }
Пример #7
0
        public void Return_User_Correctly_By_UserId()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "Get_Users_By_Id").Options;

            using (var ctx = new ApplicationDbContext(options))
            {
                ctx.ApplicationUsers.Add(new ApplicationUser
                {
                    Id       = "111",
                    UserName = "******"
                });

                ctx.ApplicationUsers.Add(new ApplicationUser
                {
                    Id       = "3332",
                    UserName = "******"
                });

                ctx.SaveChanges();
            }


            //Act
            using (var ctx = new ApplicationDbContext(options))
            {
                var appUserService = new ApplicationUserService(ctx);
                var user           = appUserService.GetById("111");

                //Assert
                Assert.AreEqual(user.UserName, "Leonard");
            }
        }
Пример #8
0
        /// <summary>
        /// Adds or updates the PushBullet Settings with the settings already encrypted.
        /// </summary>
        /// <param name="userId">ApplicationUser UserId</param>
        /// <param name="pushBulletSettings">Encrypted Settings</param>
        /// <returns></returns>
        public async Task <bool> AddOrUpdatePushBulletSettings(string userId, string pushBulletSettings)
        {
            try
            {
                var pushBulletService = await GetPushBulletServiceByUserId(userId);

                if (pushBulletService == null)
                {
                    pushBulletService = new ApplicationUserService()
                    {
                        ApplicationUserId    = userId,
                        ApplicationServiceId = Constants.Applications.PushBullet,
                        ApplicationSettings  = pushBulletSettings
                    };
                    _context.Add(pushBulletService);
                    await _context.SaveChangesAsync();

                    _logger.LogInformation("PushBulletService: Added settings for {UserId}", userId);
                }
                else
                {
                    pushBulletService.ApplicationSettings = pushBulletSettings;
                    await _context.SaveChangesAsync();

                    _logger.LogInformation("PushBulletService: Updated settings for {UserId}", userId);
                }

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "PushBulletService: Error updating for user {UserId}", userId);
                return(false);
            }
        }
Пример #9
0
 public TEntity Edit(TEntity entity)
 {
     entity.UpdatedDate           = DateTime.Now;
     entity.UpdatedByUser         = ApplicationUserService.GetUser().Id;
     _context.Entry(entity).State = EntityState.Modified;
     return(entity);
 }
Пример #10
0
        public ApplicationUserServiceTest()
        {
            this._applicationUserRepository = new MockApplicationUserRepository();
            this.Seed();

            this._applicationUserService = new ApplicationUserService(_applicationUserRepository);
        }
Пример #11
0
        protected override async Task OnInitializedAsync()
        {
            try
            {
                ApplicationUserService = ScopedServices.GetRequiredService <IApplicationUserService>();

                var email = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User.Identity.Name;
                User = await ApplicationUserService.GetUserByEmailAsync(email);

                UserProfileModel = new UserProfileModel
                {
                    UserId      = User.Id,
                    FullName    = User.FullName,
                    PhoneNumber = User.PhoneNumber
                };

                ChangeEmailModel = new ChangeEmailModel
                {
                    CurrentEmail = User.Email
                };

                SetInitialized();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                SetLoadFailed(ex.Message);
            }
        }
 public BasketAbstract(GlobalServeDbContext dbContext, ConfigurationService configurationService, ApplicationUserService userService)
 {
     _userService          = userService;
     _configurationService = configurationService;
     _dbContext            = dbContext;
     standardApiResponse   = new StandardApiResponse();
 }
Пример #13
0
        public async Task <ActionResult> Login(LoginViewModel model)
        {
            await SetInitialDataAsync();

            if (ModelState.IsValid)
            {
                ApplicationUserDTO applicationUserDTO = new ApplicationUserDTO {
                    Email = model.Email, Password = model.Password
                };
                ClaimsIdentity claim = await ApplicationUserService.Authenticate(applicationUserDTO);

                if (claim == null)
                {
                    ModelState.AddModelError("", "Неверный логин или пароль.");
                }
                else
                {
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = true
                    }, claim);
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View(model));
        }
Пример #14
0
        protected override async Task OnInitializedAsync()
        {
            try
            {
                ApplicationUserService = ScopedServices.GetRequiredService <IApplicationUserService>();
                FidoService            = ScopedServices.GetRequiredService <IFido2Service>();

                CurrentUser = await ApplicationUserService.GetUserByEmailAsync(await GetCurrentUserEmailAsync());

                // Password
                ChangePasswordModel = new ChangePasswordModel()
                {
                    UserId = CurrentUser.Id
                };

                // Security Key
                await LoadStoredCredentialsAsync();

                // 2FA
                await GetTwoFactorInfoAsync();

                SetInitialized();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                SetLoadFailed(ex.Message);
            }
        }
Пример #15
0
        public ActionResult DeleteConfirmed(int id)
        {
            ApplicationUserService applicationUserService = db.ApplicationUserServices.Where(s => s.Users_Id == UserId && s.Service_Id == id).FirstOrDefault();

            db.ApplicationUserServices.Remove(applicationUserService);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #16
0
 public AccountsController(IMapper mapper, ApplicationDbContext context,
                           ApplicationUserService applicationUserService, ApplicationRoleService applicationRoleService)
 {
     _mapper  = mapper;
     _context = context;
     _applicationUserService = applicationUserService;
     _applicationRoleService = applicationRoleService;
 }
Пример #17
0
 public Task <ApplicationUserOut> CreateUser(
     [CurrentUserGlobalState] CurrentUser user,
     [Service] ApplicationUserService service)
 => service.Create(new ApplicationUserOut {
     ExternalId = user.UserId,
     Username   = "******",
     Email      = "*****@*****.**"
 });
Пример #18
0
 public IndexModel(
     UserManager <ApplicationUser> userManager,
     ApplicationUserService applicationUserService,
     ILogger <IndexModel> logger)
 {
     _userManager            = userManager;
     _applicationUserService = applicationUserService;
     _logger = logger;
 }
Пример #19
0
        public new ActionResult Profile()
        {
            var currentUser = ApplicationUserService.GetUserId();

            ViewBag.hotels = _db.HotelReservations.Where(l => l.ApplicationUserId == currentUser).ToList();
            ViewBag.clubs  = _db.ClubReservationses.Where(l => l.ApplicationUserId == currentUser).ToList();
            ViewBag.rests  = _db.RestaurantReservationses.Where(l => l.ApplicationUserId == currentUser).ToList();
            return(View());
        }
Пример #20
0
        private void loadDataGroup()
        {
            objService = new ApplicationUserService();
            var data = objService.GetList();

            gridControlData.DataSource = data;
            gridControlData.Update();
            gridControlData.Refresh();
        }
Пример #21
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && _aplicationUserService != null)
            {
                _aplicationUserService.Dispose();
                _aplicationUserService = null;
            }

            base.Dispose(disposing);
        }
        public void ReturnPositiveNumber_IfPizzaWasFoundAndSuccessfullyRemoved_WhenCalled()
        {
            // Arrange
            Guid userId  = Guid.NewGuid();
            Guid pizzaId = Guid.NewGuid();

            var user = new ApplicationUser()
            {
                Cart = new List <BasePizza>()
                {
                    new BasePizza()
                    {
                        Id = pizzaId
                    }
                }
            };
            IEnumerable <ApplicationUser> users = new List <ApplicationUser>()
            {
                user
            };
            IEnumerable <Pizza>       pizzas       = Helper.GetPizzas();
            IEnumerable <CustomPizza> customPizzas = Helper.GetCustomPizzas();

            var pizzaContextMock = new Mock <IPizzaFactoryDbContext>();
            var orderContextMock = new Mock <IOrderDbContext>();
            var userContextMock  = new Mock <IIdentityDbContext>()
            {
                CallBase = true
            };
            var mapperMock    = new Mock <IMapper>();
            var validatorMock = new Mock <IValidator>();

            var pizzaDbSetMock       = QueryableDbSetMock.GetQueryableMockDbSet(pizzas);
            var customPizzaDbSetMock = QueryableDbSetMock.GetQueryableMockDbSet(customPizzas);
            var userDbSetMock        = QueryableDbSetMock.GetQueryableMockDbSet(users);

            userDbSetMock.Setup(u => u.Find(userId.ToString())).Returns(user);
            userContextMock.Setup(ctx => ctx.Users).Returns(userDbSetMock.Object);
            userContextMock.Setup(ctx => ctx.SaveChanges()).Returns(() => user.Cart.Count == 1 ? 0 : 1);
            pizzaContextMock.Setup(ctx => ctx.Pizzas).Returns(pizzaDbSetMock.Object);
            pizzaContextMock.Setup(ctx => ctx.CustomPizzas).Returns(customPizzaDbSetMock.Object);

            IApplicationUserService userService =
                new ApplicationUserService(userContextMock.Object,
                                           pizzaContextMock.Object,
                                           orderContextMock.Object,
                                           mapperMock.Object,
                                           validatorMock.Object);

            // Act
            int result = userService.RemoveFromCart(userId.ToString(), pizzaId);

            // Assert
            Assert.IsTrue(result > 0);
        }
Пример #23
0
        /// <summary>
        /// Retrieves the encrypted PushBullet Settings
        /// </summary>
        /// <param name="pushBulletService"></param>
        /// <returns></returns>
        public PushBulletSettings GetPushBulletSettingsByApplication(ApplicationUserService pushBulletService)
        {
            var pushBulletSettings = pushBulletService != null
                ? JsonConvert.DeserializeObject <PushBulletSettings>(pushBulletService.ApplicationSettings)
                : new PushBulletSettings()
            {
                ApiKey = string.Empty, EncryptionKey = string.Empty
            };

            return(pushBulletSettings);
        }
Пример #24
0
        public ActionResult Register()
        {
            ApplicationUser user = ApplicationUserService.GetUser();

            if (user != null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            return(View());
        }
Пример #25
0
        public void ReturnCorrectCollectionCount_AsOutParameter_WhenCalled()
        {
            // Arrange
            Guid userId = Guid.NewGuid();

            var user = new ApplicationUser()
            {
                Cart = new List <BasePizza>()
            };
            IEnumerable <ApplicationUser> users = new List <ApplicationUser>()
            {
                user
            };
            IEnumerable <Pizza>       pizzas       = Helper.GetPizzas();
            IEnumerable <CustomPizza> customPizzas = Helper.GetCustomPizzas();
            IEnumerable <Order>       orders       = new List <Order>()
            {
                new Order()
            };

            var pizzaContextMock = new Mock <IPizzaFactoryDbContext>();
            var orderContextMock = new Mock <IOrderDbContext>();
            var userContextMock  = new Mock <IIdentityDbContext>()
            {
                CallBase = true
            };
            var mapperMock    = new Mock <IMapper>();
            var validatorMock = new Mock <IValidator>();

            var pizzaDbSetMock       = QueryableDbSetMock.GetQueryableMockDbSet(pizzas);
            var customPizzaDbSetMock = QueryableDbSetMock.GetQueryableMockDbSet(customPizzas);
            var userDbSetMock        = QueryableDbSetMock.GetQueryableMockDbSet(users);
            var orderDbSetMock       = QueryableDbSetMock.GetQueryableMockDbSet(orders);

            userDbSetMock.Setup(u => u.Find(userId.ToString())).Returns(user);
            userContextMock.Setup(ctx => ctx.Users).Returns(userDbSetMock.Object);
            pizzaContextMock.Setup(ctx => ctx.Pizzas).Returns(pizzaDbSetMock.Object);
            pizzaContextMock.Setup(ctx => ctx.CustomPizzas).Returns(customPizzaDbSetMock.Object);
            orderContextMock.Setup(ctx => ctx.Orders).Returns(orderDbSetMock.Object);

            IApplicationUserService userService =
                new ApplicationUserService(userContextMock.Object,
                                           pizzaContextMock.Object,
                                           orderContextMock.Object,
                                           mapperMock.Object,
                                           validatorMock.Object);
            int count = 0;

            // Act
            var result = userService.GetAllOrdersWithPaging(out count);

            // Assert
            Assert.AreEqual(1, count);
        }
Пример #26
0
        public async Task CreateWithoutPassword()
        {
            var username  = "******";
            var email     = "[email protected]";
            var firstName = "first";
            var lastName  = "name";
            var dbUserId  = await ApplicationUserService.Create(username, email, firstName, lastName);

            Assert.AreNotEqual(new Guid().ToString(), dbUserId);
            Assert.IsNullOrEmpty(dbUserId.PasswordHash);
        }
Пример #27
0
 /// <summary>
 /// Constructeur par défaut
 /// </summary>
 public AccountsController(SignInManager <ApplicationUser> signInManager,
                           AccountService accountService,
                           IMapper mapper,
                           ApplicationUserService applicationUserService,
                           IHostingEnvironment hostingEnvironment)
 {
     this.SignInManager          = signInManager;
     this.AccountService         = accountService;
     this.Mapper                 = mapper;
     this.ApplicationUserService = applicationUserService;
     this.HostingEnvironment     = hostingEnvironment;
 }
        public async Task GetUsersByRoleNameShouldReturnCorrectData()
        {
            var addressRepository = new Mock <IRepository <Address> >();
            var userRepository    = new Mock <IRepository <ApplicationUser> >();
            var userStoreMock     = new Mock <IUserStore <ApplicationUser> >();
            var userManager       = new Mock <UserManager <ApplicationUser> >(userStoreMock.Object, null, null, null, null, null, null, null, null);
            var service           = new ApplicationUserService(userRepository.Object, addressRepository.Object, userManager.Object);

            var result = await service.GetUsersByRoleName <AdminViewModel>(GlobalConstants.AdministratorRoleName);

            userManager.Verify(x => x.GetUsersInRoleAsync(GlobalConstants.AdministratorRoleName), Times.Once, "Getting Users by Role does not work properly.");
        }
        public void GetAllAddressesByUserWithOutDataShouldReturnEmptyCollection()
        {
            var addressRepository = new Mock <IRepository <Address> >();
            var userRepository    = new Mock <IRepository <ApplicationUser> >();
            var userStoreMock     = new Mock <IUserStore <ApplicationUser> >();
            var userManager       = new Mock <UserManager <ApplicationUser> >(userStoreMock.Object, null, null, null, null, null, null, null, null);
            var service           = new ApplicationUserService(userRepository.Object, addressRepository.Object, userManager.Object);

            var actualAddresses = service.GetAllAddresses <AddressViewModel>("1").ToList();

            Assert.True(actualAddresses.Count == 0, "Get All Addresses does not return empty collection without data.");
        }
Пример #30
0
        protected override async Task OnInitializedAsync()
        {
            try
            {
                ApplicationUserService = ScopedServices.GetRequiredService <IApplicationUserService>();

                var userId = NavigationManager.GetQueryValue("userId");
                var code   = NavigationManager.GetQueryValue("code");
                var email  = NavigationManager.GetQueryValue("email");

                if (userId == null || email == null || code == null)
                {
                    SetWrongParameters("Wrong code", "This code is not valid.");
                    SetInitialized();
                    return;
                }

                var user = await UserManager.FindByIdAsync(userId);

                if (user == null)
                {
                    SetWrongParameters("User not found", "Unable to load user.");
                    SetInitialized();
                    return;
                }

                code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
                try
                {
                    await ApplicationUserService.ConfirmEmailChangeAsync(new UserConfirmEmailChangeModel()
                    {
                        UserId = userId, Email = email, Code = code
                    });

                    await IdentityApiClient.LogoutAsync();
                }
                catch (Exception ex)
                {
                    SetWrongParameters("Error changing email", ex.Message);
                    SetInitialized();
                    return;
                }

                Success = true;
                SetInitialized();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                SetLoadFailed(ex.Message);
            }
        }