public void TestAddPermissionWhenPermissionAlreadyExists()
        {
            #region Arrange
            Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { "" });
            ControllerRecordFakes.FakeRoles(5, RoleRepository);
            ControllerRecordFakes.FakeApplications(3, ApplicationRepository);
            ControllerRecordFakes.FakeUsers(3, UserRepository);
            var permissions = new List <Permission> {
                CreateValidEntities.Permission(1)
            };
            permissions[0].Application = ApplicationRepository.GetNullableById(3);
            permissions[0].User        = UserRepository.GetNullableById(3);
            permissions[0].Role        = RoleRepository.GetNullableById(2);

            ControllerRecordFakes.FakePermissions(1, PermissionRepository, permissions);

            UserService.Expect(a => a.CanUserManageGivenLogin("Name3", "UserName", "LoginId3")).Return(true).Repeat.Any();
            RoleService.Expect(a => a.GetVisibleByUser("Name3", "UserName")).Return(RoleRepository.Queryable).Repeat.Any();
            PermissionRepository.Expect(a => a.EnsurePersistent(Arg <Permission> .Is.Anything)).Repeat.Any();
            #endregion Arrange

            #region Act
            Controller.AddPermission("Name3", "LoginId3", 2);
            #endregion Act

            #region Assert
            UserService.AssertWasCalled(a => a.CanUserManageGivenLogin("Name3", "UserName", "LoginId3"));
            RoleService.AssertWasCalled(a => a.GetVisibleByUser("Name3", "UserName"));
            PermissionRepository.AssertWasNotCalled(a => a.EnsurePersistent(Arg <Permission> .Is.Anything));

            #endregion Assert
        }
    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
      try
      {
        var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

        var hashedTokenId = Helper.GetHash(context.Token);
        using (IRepository rep = new ApplicationRepository())
        {
          var refreshToken = await rep.RefreshTokens.FindAsync(hashedTokenId);

          if (refreshToken != null)
          {
            //Get protectedTicket from refreshToken class
            context.DeserializeTicket(refreshToken.ProtectedTicket);
            var result = await rep.RefreshTokens.RemoveAsync(hashedTokenId);
          }
        }

      }
      catch (Exception e)
      {
        
        throw e;
      }
    }
 public SettingsServiceBase(IServiceProvider sp)
 {
     _sp               = sp;
     _settingsCache    = _sp.GetRequiredService <ISettingsCache>();
     _tenantIdAccessor = _sp.GetRequiredService <ITenantIdAccessor>();
     _repo             = _sp.GetRequiredService <ApplicationRepository>();
 }
        public void TestCanCorrectlyMapApplicationRole2()
        {
            #region Arrange
            var id      = ApplicationRoleRepository.Queryable.Max(x => x.Id) + 1;
            var session = NHibernateSessionManager.Instance.GetSession();
            ApplicationRepository.DbContext.BeginTransaction();
            LoadApplications(1);
            ApplicationRepository.DbContext.CommitTransaction();
            RoleRepository.DbContext.BeginTransaction();
            LoadRoles(1);
            RoleRepository.DbContext.CommitTransaction();
            var application = ApplicationRepository.GetById(1);
            var role        = RoleRepository.GetById(1);
            Assert.IsNotNull(application);
            Assert.IsNotNull(role);
            #endregion Arrange

            #region Act/Assert
            new PersistenceSpecification <ApplicationRole>(session, new ApplicationRoleEqualityComparer())
            .CheckProperty(c => c.Id, id)
            .CheckProperty(c => c.Application, application)
            .CheckProperty(c => c.Role, role)
            .CheckProperty(c => c.Level, 7)
            .VerifyTheMappings();
            #endregion Act/Assert
        }
        public void TestAddUnitWhereUnitAssociationAlreadyExists()
        {
            #region Arrange
            Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { "" });
            ControllerRecordFakes.FakeApplications(3, ApplicationRepository);
            ControllerRecordFakes.FakeUnits(3, UnitRepository);
            ControllerRecordFakes.FakeUsers(3, UserRepository);
            var unitAssociations = new List <UnitAssociation>();
            unitAssociations.Add(CreateValidEntities.UnitAssociation(1));
            unitAssociations[0].Application = ApplicationRepository.GetNullableById(2);
            unitAssociations[0].User        = UserRepository.GetNullableById(1);
            unitAssociations[0].Unit        = UnitRepository.GetNullableById(3);
            ControllerRecordFakes.FakeUnitAssociations(1, UnitAssociationRepository, unitAssociations);

            UnitService.Expect(a => a.GetVisibleByUser("Name2", "UserName")).Return(UnitRepository.Queryable).Repeat.Any();
            UserService.Expect(a => a.CanUserManageGivenLogin("Name2", "UserName", "LoginId1")).Return(true).Repeat.Any();
            UnitAssociationRepository.Expect(a => a.EnsurePersistent(Arg <UnitAssociation> .Is.Anything)).Repeat.Any();
            #endregion Arrange

            #region Act
            Controller.AddUnit("Name2", "LoginId1", 3);
            #endregion Act

            #region Assert
            UserService.AssertWasCalled(a => a.CanUserManageGivenLogin("Name2", "UserName", "LoginId1"));
            UnitAssociationRepository.AssertWasNotCalled(a => a.EnsurePersistent(Arg <UnitAssociation> .Is.Anything));
            UnitService.AssertWasCalled(a => a.GetVisibleByUser("Name2", "UserName"));
            #endregion Assert
        }
        public static List <ApplicationModel> getAppGroups(int userId)
        {
            ApplicationRepository   apprepository  = new ApplicationRepository();
            List <ApplicationModel> applicationsgr = apprepository.getAppGroups(userId);

            return(applicationsgr);
        }
Beispiel #7
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            try
            {
                var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin") ?? "*";
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

                var hashedTokenId = Helper.GetHash(context.Token);
                using (IRepository rep = new ApplicationRepository())
                {
                    var refreshToken = await rep.RefreshTokens.FindAsync(hashedTokenId);

                    if (refreshToken != null)
                    {
                        //Get protectedTicket from refreshToken class
                        context.DeserializeTicket(refreshToken.ProtectedTicket);
                        var result = await rep.RefreshTokens.RemoveAsync(hashedTokenId);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #8
0
        protected void CreateUserAndApplication(IAdoNetUnitOfWork uow, out int accountId, out int applicationId)
        {
            var accountRepos = new AccountRepository(uow);
            var account      = new Account(TestUser.Username, TestUser.Password)
            {
                Email = TestUser.Email
            };

            account.Activate();
            accountRepos.Create(account);
            var userRepos = new UserRepository(uow);
            var user      = new User(account.Id, TestUser.Username)
            {
                EmailAddress = TestUser.Email
            };

            userRepos.CreateAsync(user).GetAwaiter().GetResult();

            var appRepos = new ApplicationRepository(uow);
            var app      = new Application(account.Id, "MyTestApp")
            {
                ApplicationType = TypeOfApplication.DesktopApplication
            };

            appRepos.CreateAsync(app).GetAwaiter().GetResult();
            var member = new ApplicationTeamMember(app.Id, account.Id, "Admin");

            appRepos.CreateAsync(member).GetAwaiter().GetResult();

            accountId     = user.AccountId;
            applicationId = app.Id;
        }
Beispiel #9
0
        public void CreateUser(TestUser testUser, int applicationId)
        {
            using (var uow = CreateUnitOfWork())
            {
                var accountRepos = new AccountRepository(uow);
                var account      = new Account(testUser.Username, testUser.Password)
                {
                    Email = testUser.Email
                };
                account.Activate();
                accountRepos.Create(account);
                var userRepos = new UserRepository(uow);
                var user      = new User(account.Id, testUser.Username)
                {
                    EmailAddress = testUser.Email
                };
                userRepos.CreateAsync(user).GetAwaiter().GetResult();

                var appRepos = new ApplicationRepository(uow);
                var member   = new ApplicationTeamMember(applicationId, account.Id, "Admin");
                appRepos.CreateAsync(member).GetAwaiter().GetResult();

                uow.SaveChanges();
            }
        }
        public void TestRoleServiceGetVisibleByUserReturnsExpectedResults3()
        {
            #region Arrange
            var applicationRoleRepository = FakeRepository <ApplicationRole>();
            RoleService = new RoleService(PermissionRepository, applicationRoleRepository);
            ControllerRecordFakes.FakeApplications(3, ApplicationRepository);
            ControllerRecordFakes.FakeUsers(3, UserRepository);
            ControllerRecordFakes.FakeRoles(10, RoleRepository);
            var permissions = new List <Permission>();
            for (int i = 0; i < 7; i++)
            {
                permissions.Add(CreateValidEntities.Permission(i + 1));
                permissions[i].Application = ApplicationRepository.Queryable.First();
                permissions[i].User        = UserRepository.GetNullableById(2);
                permissions[i].Role        = RoleRepository.GetNullableById(i + 1);
            }
            permissions[1].Application = ApplicationRepository.GetNullableById(2);
            permissions[2].User        = UserRepository.GetNullableById(1);
            ControllerRecordFakes.FakePermissions(0, PermissionRepository, permissions);

            applicationRoleRepository.Expect(a => a.Queryable).Return(new List <ApplicationRole>().AsQueryable()).Repeat.Any();

            #endregion Arrange

            #region Act
            var result = RoleService.GetVisibleByUser("Name2", "LoginId2");
            #endregion Act

            #region Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(IQueryable <Role>));
            Assert.AreEqual(1, result.Count());
            Assert.AreEqual("Name2", result.ElementAt(0).Name);
            #endregion Assert
        }
        public void TestCanUserManageGivenLogin5()
        {
            #region Arrange
            UserService = new UserService(UnitService, UnitAssociationRepository, PermissionRepository);
            ControllerRecordFakes.FakeUnits(6, UnitRepository);
            ControllerRecordFakes.FakeRoles(6, RoleRepository);
            ControllerRecordFakes.FakeApplications(3, ApplicationRepository);
            ControllerRecordFakes.FakeUsers(6, UserRepository);

            //These are the units that the current user has if he has the correct access
            UnitService.Expect(a => a.GetVisibleByUser("Name1", "UserName")).Return(UnitRepository.Queryable.Where(a => a.Id == 2 || a.Id == 4)).Repeat.Any();

            var unitAssociations = new List <UnitAssociation>();
            for (int i = 0; i < 5; i++)
            {
                unitAssociations.Add(CreateValidEntities.UnitAssociation(i + 1));
                unitAssociations[i].User        = UserRepository.GetNullableById(i + 1);
                unitAssociations[i].Application = ApplicationRepository.GetNullableById(2); //Different app
                unitAssociations[i].Unit        = UnitRepository.GetNullableById(2);
            }
            ControllerRecordFakes.FakeUnitAssociations(0, UnitAssociationRepository, unitAssociations);
            #endregion Arrange

            #region Act
            var result = UserService.CanUserManageGivenLogin("Name1", "UserName", "LoginId2");
            #endregion Act

            #region Assert
            Assert.IsFalse(result);
            #endregion Assert
        }
        public void TestRoleServiceGetVisibleByUserReturnsExpectedResults4()
        {
            #region Arrange
            var applicationRoleRepository = FakeRepository <ApplicationRole>();
            RoleService = new RoleService(PermissionRepository, applicationRoleRepository);
            ControllerRecordFakes.FakeApplications(3, ApplicationRepository);
            ControllerRecordFakes.FakeUsers(3, UserRepository);
            ControllerRecordFakes.FakeRoles(10, RoleRepository);
            var permissions = new List <Permission>();
            for (int i = 0; i < 10; i++)
            {
                permissions.Add(CreateValidEntities.Permission(i + 1));
                permissions[i].Application = ApplicationRepository.Queryable.First();
                permissions[i].User        = UserRepository.GetNullableById(3);
                permissions[i].Role        = RoleRepository.GetNullableById(i + 1);
            }
            permissions[4].User = UserRepository.GetNullableById(2);
            ControllerRecordFakes.FakePermissions(0, PermissionRepository, permissions);

            var applicationRoles = new List <ApplicationRole>();
            for (int i = 0; i < 10; i++)
            {
                applicationRoles.Add(CreateValidEntities.ApplicationRole(i + 1));
                applicationRoles[i].Role        = RoleRepository.GetNullableById(i + 1);
                applicationRoles[i].Application = ApplicationRepository.GetNullableById(1);
            }
            ControllerRecordFakes.FakeApplicationRoles(0, applicationRoleRepository, applicationRoles);

            #endregion Arrange

            #region Act
            //var manageableRoles = from ar in applicationRoleRepository.Queryable
            //                      where ar.Application.Name == "Name1" &&
            //                            ar.Level > (
            //                                           (from p in PermissionRepository.Queryable
            //                                            join a in applicationRoleRepository.Queryable on
            //                                                new { Role = p.Role.Id, App = p.Application.Id }
            //                                                equals new { Role = a.Role.Id, App = a.Application.Id }
            //                                            where p.Application.Name ==  "Name1" &&
            //                                                  p.User.LoginId == "LoginId2" &&
            //                                                  a.Level != null
            //                                            select a.Level).Max()
            //                                       )
            //                      select ar.Role;


            var result = RoleService.GetVisibleByUser("Name1", "LoginId2");
            #endregion Act

            #region Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(IQueryable <Role>));
            Assert.AreEqual(6, result.Count());
            for (int i = 1; i < 6; i++)
            {
                Assert.AreEqual(string.Format("Name{0}", (i + 4)), result.ElementAt(i).Name);
            }

            #endregion Assert
        }
Beispiel #13
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var refreshToken = Guid.NewGuid().ToString("n");
            var entities     = new ApplicationDbContext();

            var repo = new ApplicationRepository(entities);

            var rToken = new RefreshToken()
            {
                DateCreatedUtc    = DateTime.UtcNow,
                IssuedUtc         = DateTime.UtcNow,
                ExpirationDateUtc = DateTime.UtcNow.AddYears(1),
                IsActive          = true,
                Id = GetHash(refreshToken),
                ApplicationUserId = context.Ticket.Identity.GetUserId(),
            };

            context.Ticket.Properties.IssuedUtc  = rToken.DateCreatedUtc;
            context.Ticket.Properties.ExpiresUtc = rToken.ExpirationDateUtc;
            //rToken.ProtectedTicket = context.SerializeTicket();
            TicketSerializer serializer = new TicketSerializer();

            rToken.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));
            await repo.RefreshTokens.AddOrUpdateAndSaveAsync(rToken);

            context.SetToken(refreshToken);
        }
        public HttpResponseMessage GetPenaltyCategoryList(BaseViewModel model)
        {
            penaltyConfigData      configdata = new penaltyConfigData();
            IUnitOfWork            ouw        = new UnitOfWork();
            IApplicationRepository rep        = new ApplicationRepository(ouw);
            IApplicationService    service    = new ApplicationService(rep);

            try
            {
                if (this.ModelState.IsValid)
                {
                    configdata.PenaltyCategoryList = Utility.getItemCultureList(Utility.PenaltyCategoryList, model);
                    configdata.ApplicationList     = service.GetApplicationList(model);

                    return(Request.CreateResponse(HttpStatusCode.OK, configdata));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.InnerException.Message));
            }
        }
Beispiel #15
0
        public IEnumerable <WeatherForecast> WeatherForecasts()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            var app1 = new Application()
            {
                Name = "app", CreatedOn = DateTime.Now, ModulesIds = new List <string>(), ExtraElement = new BsonDocument()
            };

            //  for (int i = 0; i < 1000000; i++)
            //{
            //  app1.ModulesIds.Add("he");
            // }88
            app1.ExtraElement.Add("age", 18);
            app1.ExtraElement.Add("address", "street");
            new ApplicationRepository(new MongoContext()).InsertOne(app1);

            sw.Stop();
            TimeSpan ts = sw.Elapsed;


            var app = new ApplicationRepository(new MongoContext()).All();

            var rng = new Random();

            return(app.Select(index => new WeatherForecast
            {
                DateFormatted = index.Name,
                TemperatureC = rng.Next(-20, 55),
                Summary = index.Id.ToString()
            }));
        }
Beispiel #16
0
 public DetailsEntriesController(
     ILogger <DetailsEntriesController> logger,
     IStringLocalizer <Strings> localizer,
     ApplicationRepository repo) : base(logger, localizer)
 {
     _repo = repo;
 }
        public static List <ApplicationModel> getLast3Apps(int userId)
        {
            ApplicationRepository   apprepository   = new ApplicationRepository();
            List <ApplicationModel> last3appliction = apprepository.getLast3App(userId);

            return(last3appliction);
        }
        public async Task LoadAsync(string applicationId)
        {
            _markets.Clear();

            var application = await ApplicationRepository.GetAsync(applicationId);

            if (application != null)
            {
                var worldwideMarket = ViewModelLocator.MarketUserControlViewModel;
                worldwideMarket.ApplicationId = applicationId;
                worldwideMarket.MarketId      = "ww";
                worldwideMarket.Name          = ResourceHelper.GetString("ww", ResourcesFileEnum.CountriesResources);
                worldwideMarket.ImageUrl      = $"ms-appx:///Assets/Flags/ww.png";
                worldwideMarket.AverageRating = application.Markets.Average(m => m.AverageRating);
                worldwideMarket.Ratings       = application.Markets.Sum(m => m.TotalRatingsCount);
                worldwideMarket.Reviews       = application.Markets.Sum(m => m.TotalReviewsCount);
                worldwideMarket.UnreadReviews = application.Markets.Sum(m => m.UnreadReviewsCount);

                _markets.Add(worldwideMarket);

                foreach (var market in application.Markets.Select(m => m.ToViewModel()))
                {
                    _markets.Add(market);
                }
            }
        }
Beispiel #19
0
 public AgentsGenericController(
     ILogger <AgentsGenericController> logger,
     IStringLocalizer <Strings> localizer,
     ApplicationRepository repo) : base(logger, localizer)
 {
     _repo = repo;
 }
        public UnitOfWorkWebApi(ApplicationContext context) : base(context)
        {
            /*************Authorization************/
            Claims                 = new ClaimRepository(context);
            ClientApplications     = new ClientApplicationRepository(context);
            ClientApplicationUtils = new ClientApplicationUtilRepository(context);
            RoleClaims             = new RoleClaimRepository(context);
            RoleEntityClaims       = new RoleEntityClaimRepository(context);
            Roles            = new RoleRepository(context);
            UserClaims       = new UserClaimRepository(context);
            UserEntityClaims = new UserEntityClaimRepository(context);
            Users            = new UserRepository(context);
            UserRoles        = new UserRoleRepository(context);
            UserUtils        = new UserUtilRepository(context);
            Applications     = new ApplicationRepository(context);
            ApplicationUsers = new ApplicationUserRepository(context);
            /*************Authorization************/

            /*************Instances************/
            Matches = new MatchRepository(context);
            Teams   = new TeamRepository(context);
            Players = new PlayerRepository(context);
            Stats   = new StatRepository(context);
            /*********End of Instances*********/
        }
        public void TestApplicationRoleDeleteDoesNotCascadeToApplication()
        {
            #region Arrange
            ApplicationRepository.DbContext.BeginTransaction();
            LoadApplications(3);
            ApplicationRepository.DbContext.CommitTransaction();
            var applicationRole = GetValid(9);
            applicationRole.Application = ApplicationRepository.GetById(2);

            var applicationRoleCount = ApplicationRoleRepository.Queryable.Count();

            ApplicationRoleRepository.DbContext.BeginTransaction();
            ApplicationRoleRepository.EnsurePersistent(applicationRole);
            ApplicationRoleRepository.DbContext.CommitTransaction();

            Assert.IsNotNull(applicationRole.Application);
            Assert.IsFalse(applicationRole.IsTransient());
            Assert.IsTrue(applicationRole.IsValid());
            Assert.AreEqual(applicationRoleCount + 1, ApplicationRoleRepository.Queryable.Count());
            #endregion Arrange

            #region Act
            ApplicationRoleRepository.DbContext.BeginTransaction();
            ApplicationRoleRepository.Remove(applicationRole);
            ApplicationRoleRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(applicationRoleCount, ApplicationRoleRepository.Queryable.Count());
            Assert.AreEqual(3, ApplicationRepository.Queryable.Count());
            #endregion Assert
        }
        public void TestNameWithSpacesOnlyDoesNotSave()
        {
            Application application = null;

            try
            {
                #region Arrange
                application      = GetValid(9);
                application.Name = " ";
                #endregion Arrange

                #region Act
                ApplicationRepository.DbContext.BeginTransaction();
                ApplicationRepository.EnsurePersistent(application);
                ApplicationRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(application);
                var results = application.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Name: may not be null or empty");
                Assert.IsTrue(application.IsTransient());
                Assert.IsFalse(application.IsValid());
                throw;
            }
        }
Beispiel #23
0
        public Animal BuyRandomAnimal(string name, AnimalsStore store)
        {
            if (!this.state.IsStoreAccessible(store))
            {
                throw new Exception("This store is not yet aviable for your level. Middle level store is aviable on level 3, " +
                                    "Premium level store is aviable on level 10");
            }
            ApplicationRepository.GetMoneyFromrUser(user, store.GetAnimalCost());
            NotifyObservers(ActionType.MoneyChanged, user.Money);
            int    randomNumber = new Random().Next(0, 3);
            Animal animal;

            if (randomNumber == 0)
            {
                animal = store.GetBird(name, user);
            }
            else if (randomNumber == 1)
            {
                animal = store.GetMammal(name, user);
            }
            else
            {
                animal = store.GetFish(name, user);
            }
            animals.Add(animal);
            CheckLevel(animals.Count);
            return(animal);
        }
        public void TestLocationWithTooLongValueDoesNotSave()
        {
            Application application = null;

            try
            {
                #region Arrange
                application          = GetValid(9);
                application.Location = "x".RepeatTimes((256 + 1));
                #endregion Arrange

                #region Act
                ApplicationRepository.DbContext.BeginTransaction();
                ApplicationRepository.EnsurePersistent(application);
                ApplicationRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(application);
                Assert.AreEqual(256 + 1, application.Location.Length);
                var results = application.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Location: length must be between 0 and 256");
                Assert.IsTrue(application.IsTransient());
                Assert.IsFalse(application.IsValid());
                throw;
            }
        }
 public IList<ApplicationsDTO> GetApplicationByUserId(Guid userId)
 {
     using (ApplicationRepository appRepository = new ApplicationRepository())
     {
         return appRepository.GetByUserId(userId);
     }
 }
        public void TestInactiveIsTrueSaves()
        {
            #region Arrange

            var application = GetValid(9);
            application.Inactive = true;

            #endregion Arrange

            #region Act

            ApplicationRepository.DbContext.BeginTransaction();
            ApplicationRepository.EnsurePersistent(application);
            ApplicationRepository.DbContext.CommitTransaction();

            #endregion Act

            #region Assert

            Assert.IsTrue(application.Inactive);
            Assert.IsFalse(application.IsTransient());
            Assert.IsTrue(application.IsValid());

            #endregion Assert
        }
Beispiel #27
0
        public User GetUser(string userId)
        {
            MapperConfiguration config = new MapperConfiguration(k =>
                                                                 k.CreateMap <ApplicationUser, User>()
                                                                 .ForMember(m => m.ContentSourceName, m => m.MapFrom(mm => mm.ContentSource.ContentSourceName))
                                                                 .ForMember(m => m.ContentSourceUrl, m => m.MapFrom(mm => mm.ContentSource.LogoUrl))
                                                                 .ForMember(m => m.ContentSourceApproved, m => m.MapFrom(mm => mm.ContentSource.IsApproved == null ? false : mm.ContentSource.IsApproved))
                                                                 .ForMember(m => m.AthleteTeamId, m => m.MapFrom(mm => mm.Atheletes.Select(j => j.TeamId).FirstOrDefault()))
                                                                 .ForMember(m => m.AthleteProfileUrl, m => m.MapFrom(mm => mm.Atheletes.Select(j => j.Team.ProfilePublicUrl).FirstOrDefault()))
                                                                 .ForMember(m => m.AthleteSchool, m => m.MapFrom(mm => mm.Atheletes.Select(j => j.Team.School.Name).FirstOrDefault()))
                                                                 .ForMember(m => m.AthleteSport, m => m.MapFrom(mm => mm.Atheletes.Select(j => j.Team.Sport.Name).FirstOrDefault()))
                                                                 .ForMember(m => m.AthleteStartDateUtc, m => m.MapFrom(mm => mm.Atheletes.Select(j => j.StartUtc).FirstOrDefault()))
                                                                 .ForMember(m => m.AthleteEndDateUtc, m => m.MapFrom(mm => mm.Atheletes.Select(j => j.EndUtc).FirstOrDefault()))
                                                                 .ForMember(m => m.AthleteVerified, m => m.MapFrom(mm => mm.Atheletes.Select(j => j.Verified).FirstOrDefault() == null ? false : mm.Atheletes.Select(j => j.Verified).FirstOrDefault()))
                                                                 .ForMember(m => m.AdminTeams, m => m.MapFrom(mm => mm.TeamAdmins.Where(j => j.Team.IsActive && j.DateDeletedUtc == null && j.AdminStatus == AdminStatus.Approved).Select(j => new Poco.Models.TeamProfile()
            {
                Id = j.TeamId, SchoolName = j.Team.School.Name, SportName = j.Team.Sport.Name, ProfileUrl = j.Team.ProfilePublicUrl
            })))
                                                                 .ForMember(m => m.AdminSchools, m => m.MapFrom(mm => mm.SchoolAdmins.Where(j => j.School.IsActive && j.DateDeletedUtc == null && j.AdminStatus == AdminStatus.Approved).Select(j => new Poco.Models.SchoolProfile()
            {
                Id = j.SchoolId, Name = j.School.Name, ProfileUrl = j.School.ProfilePublicUrl
            }))));

            var repo = new ApplicationRepository(new ApplicationDbContext());
            var user = repo.Users.Where(m => m.Id == userId).ProjectTo <User>(config).FirstOrDefault();

            return(user);
        }
        public void TestApplicationCascadesAddToApplicationRoles()
        {
            #region Arrange
            RoleRepository.DbContext.BeginTransaction();
            LoadRoles(3);
            RoleRepository.DbContext.CommitTransaction();
            var applicationRoleCount = ApplicationRoleRepository.Queryable.Count();
            var application          = GetValid(9);
            application.ApplicationRoles.Add(CreateValidEntities.ApplicationRole(1));
            application.ApplicationRoles.Add(CreateValidEntities.ApplicationRole(2));
            application.ApplicationRoles.Add(CreateValidEntities.ApplicationRole(3));
            application.ApplicationRoles[0].Role = RoleRepository.GetById(1);
            application.ApplicationRoles[1].Role = RoleRepository.GetById(2);
            application.ApplicationRoles[2].Role = RoleRepository.GetById(3);
            #endregion Arrange

            #region Act
            ApplicationRepository.DbContext.BeginTransaction();
            ApplicationRepository.EnsurePersistent(application);
            ApplicationRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsNotNull(application.ApplicationRoles);
            Assert.AreEqual(3, application.ApplicationRoles.Count);
            Assert.IsFalse(application.IsTransient());
            Assert.IsTrue(application.IsValid());
            Assert.AreEqual(applicationRoleCount + 3, ApplicationRoleRepository.Queryable.Count());
            #endregion Assert
        }
Beispiel #29
0
        /// <summary>
        /// Connects to the database with the given Id, if the user is indeed a member of
        /// it and adds the database info into the companies concurrent bag parameter
        /// </summary>
        private async Task GetCompanyInfoAsync(int databaseId, ConcurrentBag <UserCompany> companies, CancellationToken cancellation)
        {
            try
            {
                using var appRepo = new ApplicationRepository(_serviceProvider); // new ApplicationRepository(_shardResolver, _externalUserAccessor, _clientInfoAccessor, null, _tenantIdAccessor, new DoNothingService());

                await appRepo.InitConnectionAsync(databaseId, setLastActive : false, cancellation);

                UserInfo userInfo = await appRepo.GetUserInfoAsync(cancellation);

                if (userInfo.UserId != null)
                {
                    TenantInfo tenantInfo = await appRepo.GetTenantInfoAsync(cancellation);

                    companies.Add(new UserCompany
                    {
                        Id    = databaseId,
                        Name  = tenantInfo.ShortCompanyName,
                        Name2 = string.IsNullOrWhiteSpace(tenantInfo.SecondaryLanguageId) ? null : tenantInfo.ShortCompanyName2,
                        Name3 = string.IsNullOrWhiteSpace(tenantInfo.TernaryLanguageId) ? null : tenantInfo.ShortCompanyName3
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Exception while loading user companies: DatabaseId: {databaseId}, User email: {_externalUserAccessor.GetUserEmail()}, {ex.GetType().Name}: {ex.Message}");
            }
        }
        public static List <ApplicationModel> getFavApps(int userId)
        {
            ApplicationRepository   apprepository = new ApplicationRepository();
            List <ApplicationModel> fav           = apprepository.getFavApps(userId);

            return(fav);
        }
Beispiel #31
0
 public LegacyTypesController(
     ILogger <LegacyTypesController> logger,
     IStringLocalizer <Strings> localizer,
     ApplicationRepository repo) : base(logger, localizer)
 {
     _repo = repo;
 }
Beispiel #32
0
        public void Load_NoApplication_Null()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.client, this.database);
            Application            application           = applicationRepository.Find(Guid.Empty);

            Assert.IsNull(application);
        }
        /// <summary>
        /// Validates a client thats tries to access the server.
        /// Exepts all clients, the api is the onlyclient available and do not allow adding additional clients
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;
            Client client = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null || context.ClientId == CustomRefreshTokenProvider.DUMMY_CLIENT)
            {
                //Remove the comments from the below line context.SetError, and invalidate context 
                //if you want to force sending clientId/secrects once obtain access tokens. 
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return;
            }

            using (IRepository repo = new ApplicationRepository())
            {
                client = await repo.Clients.FindAsync(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return;
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return;
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return;
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return;
            }

            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
        }
        public void Find_By_Name_Return_Object()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());
            applicationRepository.Save(application);

            Assert.IsNotNull(applicationRepository.Find(application.Name));
        }
        public void Save()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());
            applicationRepository.Save(application);

            Assert.IsNotNull(application.Id);
        }
        public void RemoveApplication(List<Domain.Context.Application> applicationList)
        {
            if (applicationList == null)
                throw new ArgumentNullException("applicationList");

            using (ApplicationRepository appRepository = new ApplicationRepository())
            {
                for (int i = 0; i < applicationList.Count; i++)
                {
                    appRepository.Remove(applicationList[i]);
                }
                appRepository.Commit();
            }
        }
        public void Remove_Platforms_From_Application()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());
            application.Platforms = iPlatformDAL.FindAll().ToList();
            applicationRepository.Save(application);

            Application applicationFound = applicationRepository.Find(application.Guid);
            applicationFound.Platforms = new List<Platform>();
            applicationRepository.Update(application);

            Application applicationRemovedPlatforms = applicationRepository.Find(application.Guid);
            Assert.IsTrue(applicationRemovedPlatforms.Platforms.Count == 0);
        }
        public void Get_All_Applications()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);

            Application application1 = new Application(Guid.NewGuid().ToString());
            applicationRepository.Save(application1);

            Application application2 = new Application(Guid.NewGuid().ToString());
            applicationRepository.Save(application2);

            Application application3 = new Application(Guid.NewGuid().ToString());
            applicationRepository.Save(application3);

            IEnumerable<Application> applications = applicationRepository.FindAll();

            Assert.IsNotNull(applications);
        }
        public void Search_Listing_7_7()
        {
            var repository = new ApplicationRepository();

            var lastNameCriteria = "P";

            var controller = new Controller(repository);

            var results = controller.Search(lastNameCriteria);

            foreach (var result in results)
            {
                Console.WriteLine("{0}, {1}",
                    result.LastName,
                    result.FirstName);
            }
        }
        public void CreateApplication(Domain.Context.Application application)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            using (UserRepository userRepository = new UserRepository())
            {
                var user = userRepository.Get(application.UserId);

                if (user != null)
                {
                    var achievement = user.Achievements.SingleOrDefault<Achievement>(a => a.Year == DateTime.Now.Year);
                    if (achievement != null)
                    {
                        //using (SpecialityEnrollPlanRepository enrollPlanRepository = new SpecialityEnrollPlanRepository())
                        //{
                        //    var enrollPlans = enrollPlanRepository.GetFiltered(e => e.SpecialityId == application.SpecialityId && e.Province == achievement.Province).SingleOrDefault<SpecialityEnrollPlan>();
                        //    if (enrollPlans != null)
                        //    {
                        using (ApplicationRepository appRepository = new ApplicationRepository())
                        {
                            var apps = appRepository.GetFiltered(app => app.Year == application.Year && app.Batch == application.Batch && app.ApplicationSequence == application.ApplicationSequence);
                            if (apps != null && apps.ToList<Domain.Context.Application>().Count > 0)
                            {
                                // throw existing application exception
                                throw new UniversityApplicationExistException(Resource.UserMessages.ex_UniversityApplicationExist);
                            }
                            appRepository.Add(application);
                            appRepository.Commit();
                        }
                        //}
                        //else
                        //{
                        //    // throw no enroll plan exception
                        //    throw new UniversityNoEnrollPlanException(Resource.ResourceMessage.ex_UnversityNoEnrollPlan);
                        //}
                        //}
                    }
                    else
                    {
                        throw new UniversityApplicationExistException(Resource.UserMessages.ex_AchievementNotExist);
                    }
                }
            }
        }
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
      if (!context.OwinContext.Environment.ContainsKey(IS_REFREHTOKEN_EXPIRED_NAME) || (bool)context.OwinContext.Environment[IS_REFREHTOKEN_EXPIRED_NAME])
      {
        bool result = false;
        var refreshTokenId = Guid.NewGuid().ToString("n");
        var clientId = context.Ticket.Properties.Dictionary.ContainsKey("as:client_id") ? context.Ticket.Properties.Dictionary["as:client_id"] : DUMMY_CLIENT;


        var refreshTokenLifetime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime") ?? "30";
        var token = new RefreshToken()
        {
          Id = Helper.GetHash(refreshTokenId),
          ClientId = clientId,
          Subject = context.Ticket.Identity.Name,
          IssuedUtc = DateTime.UtcNow,
          ExpiresUtc = DateTime.UtcNow.AddMinutes(Double.Parse(refreshTokenLifetime))
        };
        context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
        context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
        // Add current User Id
        //context.Ticket.Properties.Dictionary.Add("UserId", context.Ticket.Identity.GetUserId());

        if (!context.Ticket.Properties.Dictionary.ContainsKey("as:client_id"))
        {
          context.Ticket.Properties.Dictionary.Add("as:client_id", clientId);
        }
        else
        {
          context.Ticket.Properties.Dictionary["as:client_id"] = clientId;
        }
        

        token.ProtectedTicket = context.SerializeTicket();

        using (IRepository rep = new ApplicationRepository())
        {
          result = await rep.RefreshTokens.AddAsync(token);
        }
        if (result)
        {
          context.SetToken(refreshTokenId);
        }
      }
    }
        public void Load_FindApplication_Match()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.client, this.database);

            Application expected = new Application()
            {
                Guid = Guid.NewGuid(),
                Active = true,
                DateCreated = new DateTime(2013, 01, 01),
                DateModified = new DateTime(2013, 01, 01),
                Name = "Testing App",
                Platforms = new List<Platform>()
            };

            this.GetCollection<Application>().Insert(expected);

            Application actual = applicationRepository.Find(expected.Guid);

            expected.ShouldHave().AllProperties().EqualTo(actual);
        }
        public void Update_By_Guid()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());
            applicationRepository.Save(application);

            Application applicationLoad = applicationRepository.Find(application.Guid);

            applicationLoad.Active = false;
            applicationLoad.DateModified = DateTime.Now;
            applicationLoad.Name = Guid.NewGuid().ToString();

            applicationRepository.Update(applicationLoad);

            Application applicationUpdated = applicationRepository.Find(application.Guid);

            Assert.IsTrue(applicationUpdated.Active == applicationLoad.Active);
            Assert.IsTrue(applicationUpdated.Name == applicationLoad.Name);
        }
        public void CreateApplicationTest()
        {
            ApplicationService target = new ApplicationService();
            UniversityAppService universitySerivce = new UniversityAppService();

            ApplicationRepository appRepository = new ApplicationRepository();
            var app = appRepository.Get(new Guid("6079D394-C27A-4871-996A-AC9374097042"));
            if (app != null)
            {
                appRepository.Remove(app);
                appRepository.Commit();
                app = appRepository.Get(new Guid("6079D394-C27A-4871-996A-AC9374097042"));
                Assert.AreEqual(app, null);
            }
            GF.Domain.Context.Application application = new Domain.Context.Application(new Guid("D1111C18-A0BD-480B-99CA-AAF50B2D1818"), new Guid("408AD727-5E75-409C-A658-0AB0C6A9EFD2"), new Guid("6079D394-C27A-4871-996A-AC9374097042"));
            target.CreateApplication(application);
            app = appRepository.Get(new Guid("6079D394-C27A-4871-996A-AC9374097042"));
            Assert.AreNotEqual(app, null);
            Assert.AreEqual(app.Id, new Guid("6079D394-C27A-4871-996A-AC9374097042"));
        }
        public void UpdateApplication(List<Domain.Context.Application> applicationList)
        {
            if (applicationList == null)
                throw new ArgumentNullException("applicationList");

            ApplicationRepository appRepository = new ApplicationRepository();
            for (int i = 0; i < applicationList.Count; i++)
            {
                // TODO: check if exists, priority low
                appRepository.Modify(applicationList[i]);
            }
            appRepository.Commit();
        }
        public void CreateApplication(Domain.Context.Application application)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            AccountRepository accountRepository = new AccountRepository();
            var account = accountRepository.Get(application.UserId);

            if (account != null)
            {
                var achievement = account.Achievements.ToList<Achievement>().SingleOrDefault<Achievement>( a=> a.Year.Year == DateTime.Now.Year);
                if (achievement != null)
                {
                    EnrollPlanRepository enrollPlanRepository = new EnrollPlanRepository();
                    var enrollPlans = enrollPlanRepository.GetFiltered(e => e.SpecialityId == application.SpecialityId && e.Province == achievement.Province).SingleOrDefault<EnrollPlan>();
                    if (enrollPlans != null)
                    {
                        ApplicationRepository appRepository = new ApplicationRepository();

                        var apps = appRepository.GetFiltered(app => app.Year.Year == application.Year.Year && app.Batch == application.Batch && app.ApplicationSequence == application.ApplicationSequence);
                        if (apps != null && apps.ToList<Domain.Context.Application>().Count > 0)
                        {
                            // TODO: throw existing application exception
                        }

                        appRepository.Add(application);
                        appRepository.Commit();
                    }
                    else
                    {
                        // TODO: throw no enroll plan exception
                    }
                }
            }
        }
 public void Load_NoApplication_Null()
 {
     IApplicationRepository applicationRepository = new ApplicationRepository(this.client, this.database);
     Application application = applicationRepository.Find(Guid.Empty);
     Assert.IsNull(application);
 }
        public static Controller CreateController(int? id = null)
        {
            var repository = new ApplicationRepository();

            return new Controller(repository);
        }
        /// <summary>
        /// receiving the username and password from the request and validate them against our ASP.NET 2.1 Identity system
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //Allowing cross domain resources for external logins
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            //Search user by username and password
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            using (IRepository repo = new ApplicationRepository())
            {
                var oldtokens = (await repo.RefreshTokens.GetAllAsync()).Where(x => x.ExpiresUtc < DateTime.UtcNow || x.Subject.Equals(user.UserName)).ToList();
                foreach (var token in oldtokens)
                {
                    await repo.RefreshTokens.RemoveAsync(token);
                }
            }

            // Generate claim and JWT-Ticket 
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
            oAuthIdentity.AddClaim(new Claim("userId", oAuthIdentity.GetUserId()));

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            //Transfer this identity to an OAuth 2.0 Bearer access ticket
            context.Validated(ticket);

        }
        public void Save_Platforms_Against_An_Application()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());
            application.Platforms = iPlatformDAL.FindAll().ToList();
            applicationRepository.Save(application);

            Application applicationFound = applicationRepository.Find(application.Guid);
            Assert.IsNotNull(applicationFound.Platforms);
            Assert.IsTrue(applicationFound.Platforms.Count == application.Platforms.Count);
        }
 public void Find_By_Name_Return_Null()
 {
     IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);
     Assert.IsNull(applicationRepository.Find(Guid.NewGuid().ToString()));
 }