public void Initialize() {
            session.BeginTransaction();
            userRepository = new UserRepository();
            identityService = new IdentityService<User>(userRepository);

            password = "******";
            
            user = new User
            {
                Name = "John Doe",
                BirthDate = new DateTime(1982, 8, 1),
                Email = "*****@*****.**",
                Username = "******",
                Address = new Address { City = "São paulo", StreetName = "name", Number = "123B", State = "SP", ZipCode = "03423-234" }
            };

            user2 = new User
            {
                Name = "Fulano",
                BirthDate = DateTime.Now,
                Email = "*****@*****.**",
                Password = "******",
                Username = "******",
                Address = new Address { City = "São paulo", StreetName = "name", Number = "123B", State = "SP", ZipCode = "03423-234" }
            };
        }
 public void ValidLoginTest()
 {
     AccountUnitTests _account = new AccountUnitTests();
     _account.Create();
     try
     {
         IdentityService service = new IdentityService(Session);
         UserContext userContext = service.Login(_account.Instance.Name, _account.Instance.Password);
         Assert.AreEqual(userContext.AccountId, _account.Instance.Id);
         Assert.GreaterOrEqual(DateTime.UtcNow, userContext.TimeStamp);
     }
     finally
     {
         _account.Delete();
     }
 }
        public async Task Should_Error_Update_Data()
        {
            var validateMock = new Mock <IValidateService>();

            validateMock.Setup(s => s.Validate(It.IsAny <BankExpenditureNoteViewModel>())).Verifiable();
            IdentityService identityService = new IdentityService()
            {
                Token    = "Token",
                Username = "******"
            };
            var mockFacade = new Mock <IBankExpenditureNoteFacade>();

            mockFacade.Setup(x => x.Update(It.IsAny <int>(), It.IsAny <BankExpenditureNoteModel>(), It.IsAny <IdentityService>()))
            .ThrowsAsync(new Exception());

            var mockMapper = new Mock <IMapper>();

            var controller = GetController(mockFacade, validateMock, mockMapper);

            var response = await controller.Put(0, this.ViewModel);

            Assert.Equal((int)HttpStatusCode.InternalServerError, GetStatusCode(response));
        }
        public async Task Should_Return_Bad_Request_Update_Data()
        {
            var validateMock = new Mock <IValidateService>();

            validateMock.Setup(s => s.Validate(It.IsAny <BankExpenditureNoteViewModel>())).Throws(GetServiceValidationExeption());
            IdentityService identityService = new IdentityService()
            {
                Token    = "Token",
                Username = "******"
            };
            var mockFacade = new Mock <IBankExpenditureNoteFacade>();

            mockFacade.Setup(x => x.Update(It.IsAny <int>(), It.IsAny <BankExpenditureNoteModel>(), identityService))
            .ReturnsAsync(1);

            var mockMapper = new Mock <IMapper>();

            var controller = GetController(mockFacade, validateMock, mockMapper);

            var response = await controller.Put(0, ViewModel);

            Assert.Equal((int)HttpStatusCode.BadRequest, GetStatusCode(response));
        }
        public async Task Should_Success_Update()
        {
            var dbContext = DbContext(GetCurrentMethod());
            IIdentityService identityService = new IdentityService {
                Username = "******"
            };

            var dailyOperationBadOutputReasonsLogic = new DailyOperationBadOutputReasonsLogic(identityService, dbContext);
            var dailyOperationLogic = new DailyOperationLogic(dailyOperationBadOutputReasonsLogic, identityService, dbContext);

            var serviceProvider         = GetServiceProviderMock(dbContext).Object;
            DailyOperationFacade facade = Activator.CreateInstance(typeof(DailyOperationFacade), serviceProvider, dbContext) as DailyOperationFacade;
            var data = await DataUtil(facade, dbContext).GetTestData();

            var outputData = DataUtil(facade, dbContext).GetNewDataOut(data);

            await facade.CreateAsync(outputData);

            outputData.BadOutput = 10;
            await facade.UpdateAsync(outputData.Id, outputData);

            Assert.NotNull(data);
        }
        public async Task Should_Return_Not_Found_Delete_Data()
        {
            var validateMock = new Mock <IValidateService>();

            validateMock.Setup(s => s.Validate(It.IsAny <BankExpenditureNoteViewModel>())).Verifiable();
            IdentityService identityService = new IdentityService()
            {
                Token    = "Token",
                Username = "******"
            };
            var mockFacade = new Mock <IBankExpenditureNoteFacade>();

            mockFacade.Setup(x => x.Delete(It.IsAny <int>(), identityService))
            .ReturnsAsync(0);

            var mockMapper = new Mock <IMapper>();

            var controller = GetController(mockFacade, validateMock, mockMapper);

            var response = await controller.Delete(1);

            Assert.Equal((int)HttpStatusCode.NotFound, GetStatusCode(response));
        }
Exemple #7
0
        public Server(IServiceProvider provider)
        {
            _provider = provider;
            _logger   = provider.GetService <ILoggerFactory>()?.CreateLogger("Chat.Server");

            _eventBus = provider.GetRequiredService <IEventBus>();

            var eventLogger = provider.GetService <ILoggerFactory>()?.CreateLogger("Chat.Server.Events");

            _eventBus.GetEventStream <DomainEvent>().Subscribe(e => eventLogger.LogInformation(
                                                                   e.GetType().Name + " " + JsonConvert.SerializeObject(e)));

            _userRepo     = provider.GetRequiredService <IUserRepository>();
            _chatroomRepo = provider.GetRequiredService <IChatroomRepository>();
            _messageRepo  = provider.GetRequiredService <IMessageRepository>();

            _identityService   = provider.GetRequiredService <IdentityService>();
            _chatroomService   = provider.GetRequiredService <ChatroomService>();
            _messageService    = provider.GetRequiredService <MessageService>();
            _userClientService = provider.GetRequiredService <UserClientService>();

            _chatroomService.EnsureGlobalChatroomCreated();
        }
Exemple #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setUpCdiProcessEngineTestCase() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void setUpCdiProcessEngineTestCase()
        {
            if (BpmPlatform.ProcessEngineService.DefaultProcessEngine == null)
            {
                org.camunda.bpm.container.RuntimeContainerDelegate_Fields.INSTANCE.get().registerProcessEngine(processEngineRule.ProcessEngine);
            }

            beanManager   = ProgrammaticBeanLookup.lookup(typeof(BeanManager));
            processEngine = processEngineRule.ProcessEngine;
            processEngineConfiguration = (ProcessEngineConfigurationImpl)processEngineRule.ProcessEngine.ProcessEngineConfiguration;
            formService          = processEngine.FormService;
            historyService       = processEngine.HistoryService;
            identityService      = processEngine.IdentityService;
            managementService    = processEngine.ManagementService;
            repositoryService    = processEngine.RepositoryService;
            runtimeService       = processEngine.RuntimeService;
            taskService          = processEngine.TaskService;
            authorizationService = processEngine.AuthorizationService;
            filterService        = processEngine.FilterService;
            externalTaskService  = processEngine.ExternalTaskService;
            caseService          = processEngine.CaseService;
            decisionService      = processEngine.DecisionService;
        }
        public ActionResult SilentLogin(string token)
        {
            var service  = new IdentityService();
            var response = service.SignIn(token);

            if (response.Status)
            {
                var cookie = HttpContext.Request.Cookies[GlobalSettings.Backoffices.MonthlySubscriptionCookieName];
                if (cookie != null)
                {
                    cookie         = new HttpCookie(GlobalSettings.Backoffices.MonthlySubscriptionCookieName);
                    cookie.Value   = "true";
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    HttpContext.Response.Cookies.Add(cookie);
                }
                //T.W. 6/1/2016 77187 This change ensures the correct landing page (when silent login to the back office) uses the filter 'BackofficeSubscriptionRequired'
                return(Redirect(response.LandingUrl));
            }
            else
            {
                return(RedirectToAction("Login"));
            }
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (!string.IsNullOrEmpty(Roles))
            {
                return;
            }

            var filters = FilterProviders.Providers.GetFilters(filterContext.Controller.ControllerContext, filterContext.ActionDescriptor).Where(o => o.Instance.GetType().Name == GetType().Name).ToList();

            if (filters.Count() > 1)
            {
                var filter = filters.FirstOrDefault(o => ReferenceEquals((SkAuthorizeAttribute)o.Instance, this));
                if (filter != null & filter.Scope == FilterScope.Controller)
                {
                    return;
                }
            }

            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName     = filterContext.ActionDescriptor.ActionName;
            var userName       = Thread.CurrentPrincipal.Identity.Name;
            var service        = new IdentityService();
            var hasPermission  = false;

            Task.Run(async() =>
            {
                var response  = await service.CheckUserForAction(userName, controllerName, actionName);
                hasPermission = response.Value;
            }).Wait();

            if (!hasPermission)
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
        protected override Mock <IServiceProvider> GetServiceProviderMock(SalesDbContext dbContext)
        {
            var serviceProviderMock = new Mock <IServiceProvider>();

            IIdentityService identityService = new IdentityService {
                Username = "******"
            };

            CostCalculationGarmentMaterialLogic costCalculationGarmentMaterialLogic = new CostCalculationGarmentMaterialLogic(serviceProviderMock.Object, identityService, dbContext);
            CostCalculationGarmentLogic         costCalculationGarmentLogic         = new CostCalculationGarmentLogic(costCalculationGarmentMaterialLogic, serviceProviderMock.Object, identityService, dbContext);

            GarmentPreSalesContractLogic garmentPreSalesContractLogic = new GarmentPreSalesContractLogic(identityService, dbContext);

            var azureImageFacadeMock = new Mock <IAzureImageFacade>();

            azureImageFacadeMock
            .Setup(s => s.DownloadImage(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync("");

            serviceProviderMock
            .Setup(x => x.GetService(typeof(IdentityService)))
            .Returns(identityService);
            serviceProviderMock
            .Setup(x => x.GetService(typeof(CostCalculationGarmentMaterialLogic)))
            .Returns(costCalculationGarmentMaterialLogic);
            serviceProviderMock
            .Setup(x => x.GetService(typeof(CostCalculationGarmentLogic)))
            .Returns(costCalculationGarmentLogic);
            serviceProviderMock
            .Setup(x => x.GetService(typeof(GarmentPreSalesContractLogic)))
            .Returns(garmentPreSalesContractLogic);
            serviceProviderMock
            .Setup(x => x.GetService(typeof(IAzureImageFacade)))
            .Returns(azureImageFacadeMock.Object);

            return(serviceProviderMock);
        }
Exemple #12
0
        public Mutation(IdentityService identityService)
        {
            Name = "Mutation";

            Field <LoginType>(
                "login",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "Email", Description = "User email."
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "Password", Description = "User password."
            }
                    ),
                resolve: context =>
            {
                string email    = context.GetArgument <string>("Email");
                string password = context.GetArgument <string>("Password");

                return(identityService.Authenticate(email, password).Result);
            });

            Field <LoginType>(
                "autoLogin",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "token"
            }
                    ),
                resolve: context =>
            {
                string email    = context.GetArgument <string>("Email");
                string password = context.GetArgument <string>("Password");

                return(identityService.Authenticate(email, password).Result);
            });
        }
Exemple #13
0
        public async void GetUserProfileWithRightUsername()
        {
            // Arrange
            var mockedUserManager = GetUserManager();

            mockedUserManager.FindByNameAsync(Arg.Any <string>()).ReturnsForAnyArgs(new User {
                UserName = "******", Role = 0, Description = "description"
            });
            IdentityService service = new IdentityService(mockedUserManager, GetSignInManager(), GetSendgridService(), GetAppSettings(), GetRefreshTokenService(), GetImageService());

            // Act
            var result = await service.GetUserProfileByUsername("username");

            // Assert
            Assert.True(result.Succeeded);
            Assert.NotNull(result.Result);
            Assert.IsType <ProfileResponse>(result.Result);

            var response = result.Result as ProfileResponse;

            Assert.NotNull(response.Username);
            Assert.NotNull(response.Description);
            Assert.NotNull(response.RoleName);
        }
Exemple #14
0
        public async void SigninAsyncWithBannedUser()
        {
            // Arrange
            var expectedErrorMessage = "UserBanned"; // Message renvoyé par le serveur si l'utilisateur est banni
            var mockedUserManager    = GetUserManager();

            mockedUserManager.FindByEmailAsync(Arg.Any <string>())
            .ReturnsForAnyArgs(new User()
            {
                IsBanned = true
            });
            var mockedSigninManager = GetSignInManager();

            mockedSigninManager.PasswordSignInAsync(Arg.Any <User>(), Arg.Any <string>(), Arg.Any <bool>(), Arg.Any <bool>()).ReturnsForAnyArgs(SignInResult.Success);
            IdentityService service = new IdentityService(mockedUserManager, mockedSigninManager, GetSendgridService(), GetAppSettings(), GetRefreshTokenService(), GetImageService());

            // Act
            var result = await service.SignInUserAsync("email", "password");

            // Assert
            Assert.False(result.Succeeded);
            Assert.Null(result.Result);
            Assert.Equal(result.Messages[0], expectedErrorMessage);
        }
Exemple #15
0
        private void mockServices(ProcessEngine engine)
        {
            RepositoryService   repoService         = mock(typeof(RepositoryService));
            IdentityService     identityService     = mock(typeof(IdentityService));
            TaskService         taskService         = mock(typeof(TaskService));
            RuntimeService      runtimeService      = mock(typeof(RuntimeService));
            FormService         formService         = mock(typeof(FormService));
            HistoryService      historyService      = mock(typeof(HistoryService));
            ManagementService   managementService   = mock(typeof(ManagementService));
            CaseService         caseService         = mock(typeof(CaseService));
            FilterService       filterService       = mock(typeof(FilterService));
            ExternalTaskService externalTaskService = mock(typeof(ExternalTaskService));

            when(engine.RepositoryService).thenReturn(repoService);
            when(engine.IdentityService).thenReturn(identityService);
            when(engine.TaskService).thenReturn(taskService);
            when(engine.RuntimeService).thenReturn(runtimeService);
            when(engine.FormService).thenReturn(formService);
            when(engine.HistoryService).thenReturn(historyService);
            when(engine.ManagementService).thenReturn(managementService);
            when(engine.CaseService).thenReturn(caseService);
            when(engine.FilterService).thenReturn(filterService);
            when(engine.ExternalTaskService).thenReturn(externalTaskService);
        }
        public async Task <JsonResult> Create(RegisterViewModel user)
        {
            try
            {
                var applicationUser = new ApplicationUser {
                    UserName = user.Email, Email = user.Email, RoleId = user.RoleId
                };
                var result = await HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>().CreateAsync(applicationUser, user.Password);

                if (result.Succeeded)
                {
                    using (IdentityService identityService = new IdentityService())
                    {
                        await identityService.CreateNewUser(user.Email, user.RoleId);
                    }
                }

                return(Json("Success", JsonRequestBehavior.AllowGet));
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
Exemple #17
0
        public void Should_Success_Create_Data()
        {
            var validateMock = new Mock <IValidateService>();

            validateMock.Setup(s => s.Validate(It.IsAny <BankExpenditureNoteViewModel>())).Verifiable();
            IdentityService identityService = new IdentityService()
            {
                Token    = "Token",
                Username = "******"
            };

            var mockFacade = new Mock <IBankExpenditureNoteFacade>();

            mockFacade.Setup(x => x.Create(It.IsAny <BankExpenditureNoteModel>(), identityService))
            .ReturnsAsync(1);

            var mockMapper = new Mock <IMapper>();

            var controller = GetController(mockFacade, validateMock, mockMapper);

            var response = controller.Post(this.ViewModel).Result;

            Assert.Equal((int)HttpStatusCode.Created, GetStatusCode(response));
        }
        private NavigationBreadCrumbVO GetLocationBreadCrumbs(string action, int?id)
        {
            var breadCrumb = new NavigationBreadCrumbVO();

            switch (action.ToLower())
            {
            case "clientlocations":
                breadCrumb = _navigationService.GetBreadCrumbs(_lookupService.GetClientById(id.Value));
                break;

            case "edit":
            case "details":
                var location = _lookupService.GetLocationByIdAndClientId(IdentityService.GetClientIdsFromClaim(User), id.Value);
                breadCrumb = _navigationService.GetBreadCrumbs(_lookupService.GetClientById(location.ClientId));
                breadCrumb.IncludeLowestTierLink = true;
                break;

            case "create":
                breadCrumb = _navigationService.GetBreadCrumbs(_lookupService.GetClientById(id.Value));
                breadCrumb.IncludeLowestTierLink = true;
                break;
            }
            return(breadCrumb);
        }
        public void Read_Return_Success()
        {
            string           testName        = GetCurrentMethod();
            var              dbContext       = _dbContext(testName);
            IIdentityService identityService = new IdentityService {
                Username = "******"
            };
            var model = new SalesInvoiceExportDetailModel()
            {
                Description = "Description"
            };

            dbContext.SalesInvoiceExportDetails.Add(model);
            dbContext.SaveChanges();
            SalesInvoiceExportDetailLogic unitUnderTest = new SalesInvoiceExportDetailLogic(GetServiceProvider(testName).Object, identityService, dbContext);

            var result = unitUnderTest.Read(1, 1, "{}", new List <string>()
            {
                ""
            }, null, "{}");

            Assert.True(0 < result.Data.Count);
            Assert.NotEmpty(result.Data);
        }
        public async Task InvokeAsync_UserAuthenticated_IAuthenticateUser()
        {
            // Arrange
            var authenticateUser = new AuthenticateUser <int>();

            var claimsIdentity = new ClaimsOption()
            {
                Email  = "email",
                IdUser = "******",
                Role   = "role",
                User   = "******"
            };

            var options = MEO.Options.Create(new EFCoreOption()
            {
                ClaimsIdentity = claimsIdentity
            });

            var httpContextAccessor = this.GetHttpContextAccesor(out HttpContext context, claimsIdentity);

            var identityService = new IdentityService <int>(options, httpContextAccessor, authenticateUser);

            var requestDelegate = Mock.Of <RequestDelegate>();

            var middleware = new IdentityServiceMiddleware <int>(requestDelegate);

            // Act
            await middleware.InvokeAsync(context, identityService);

            // Assert
            Assert.True(authenticateUser.IsAuthenticated);
            Assert.False(authenticateUser.IsApplication);
            Assert.Equal("TestUser", authenticateUser.Name);
            Assert.Equal("*****@*****.**", authenticateUser.Email);
            Assert.Equal(1, authenticateUser.IdUser);
        }
        protected override Mock <IServiceProvider> GetServiceProviderMock(SalesDbContext dbContext)
        {
            var serviceProviderMock = new Mock <IServiceProvider>();

            IIdentityService identityService = new IdentityService {
                Username = "******"
            };

            serviceProviderMock.Setup(s => s.GetService(typeof(IHttpClientService)))
            .Returns(new HttpClientTestService());

            serviceProviderMock
            .Setup(x => x.GetService(typeof(IdentityService)))
            .Returns(identityService);

            var salesInvoiceItemLogic = new SalesInvoiceItemLogic(serviceProviderMock.Object, identityService, dbContext);

            serviceProviderMock
            .Setup(x => x.GetService(typeof(SalesInvoiceItemLogic)))
            .Returns(salesInvoiceItemLogic);

            var salesInvoiceDetailLogic = new SalesInvoiceDetailLogic(serviceProviderMock.Object, identityService, dbContext);

            serviceProviderMock
            .Setup(x => x.GetService(typeof(SalesInvoiceDetailLogic)))
            .Returns(salesInvoiceDetailLogic);

            var salesInvoiceLogic = new SalesInvoiceLogic(serviceProviderMock.Object, identityService, dbContext);

            serviceProviderMock
            .Setup(x => x.GetService(typeof(SalesInvoiceLogic)))
            .Returns(salesInvoiceLogic);


            return(serviceProviderMock);
        }
Exemple #22
0
        /// <summary>
        /// Authenticates the credentials provided in <see cref="AuthenticationRequest"/> with the OpenStack Identity
        /// Service V2.
        /// </summary>
        /// <remarks>
        /// <para>This method caches the authentication result, and returns the cached result of a previous
        /// authentication request when possible to avoid unnecessary calls to the Identity API. If a cached
        /// authentication result is available but has either expired or will expire soon (see
        /// <see cref="ExpirationOverlap"/>), the cached result is discarded and the credentials are re-authenticated
        /// with the Identity Service.</para>
        /// </remarks>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
        /// <returns>
        /// A <see cref="Task"/> representing the asynchronous operation. When the task completes successfully, the
        /// <see cref="Task{TResult}.Result"/> property will contain an <see cref="Access"/> instance providing the
        /// authentication result.
        /// </returns>
        /// <exception cref="HttpWebException">
        /// If an error occurs during an HTTP request as part of authenticating with the Identity API.
        /// </exception>
        protected virtual Task <Access> AuthenticateAsync(CancellationToken cancellationToken)
        {
            Access access = Access;

            if (access != null && access.Token != null)
            {
                Token token = access.Token;
                // Note: this code uses lifting to null to cover the case where token.ExpiresAt is null
                DateTimeOffset?effectiveExpiration = token.ExpiresAt - ExpirationOverlap;
                if (effectiveExpiration > DateTimeOffset.Now)
                {
                    return(CompletedTask.FromResult(access));
                }
            }

            return
                (IdentityService.AuthenticateAsync(AuthenticationRequest, cancellationToken)
                 .Select(
                     task =>
            {
                _access = task.Result;
                return task.Result;
            }));
        }
        public void Read_With_EmptyKeyword_Return_Success()
        {
            string           testName        = GetCurrentMethod();
            var              dbContext       = _dbContext(testName);
            IIdentityService identityService = new IdentityService {
                Username = "******"
            };
            var model = new RO_Garment_SizeBreakdown()
            {
                Code = "Code"
            };

            dbContext.RO_Garment_SizeBreakdowns.Add(model);
            dbContext.SaveChanges();
            ROGarmentSizeBreakdownLogic unitUnderTest = new ROGarmentSizeBreakdownLogic(GetServiceProvider(testName).Object, identityService, dbContext);

            var result = unitUnderTest.Read(1, 1, "{}", new List <string>()
            {
                ""
            }, null, "{}");

            Assert.True(0 < result.Data.Count);
            Assert.NotEmpty(result.Data);
        }
 public GarmentPurchasingExpeditionService(IServiceProvider serviceProvider)
 {
     _dbContext       = serviceProvider.GetService <PurchasingDbContext>();
     _identityService = serviceProvider.GetService <IdentityService>();
 }
Exemple #25
0
 public MonitoringCentralBillReceptionController(IServiceProvider serviceProvider, IMonitoringCentralBillReceptionFacade facade)
 {
     this.serviceProvider = serviceProvider;
     this.facade          = facade;
     this.identityService = (IdentityService)serviceProvider.GetService(typeof(IdentityService));
 }
 public void Initialize() {
     session = ApplicationManager.SessionFactory.OpenSession();
     session.BeginTransaction();
     userRepository = new UserRepository();
     identityService = new IdentityService<User>(userRepository);
 }
Exemple #27
0
 public ExternalPurchaseOrderController(IMapper mapper, ExternalPurchaseOrderFacade facade, IdentityService identityService)
 {
     _mapper = mapper;
     _facade = facade;
     this.identityService = identityService;
 }
 public PurchasingDocumentAcceptanceController(PurchasingDocumentExpeditionFacade purchasingDocumentExpeditionFacade, IdentityService identityService)
 {
     this.purchasingDocumentExpeditionFacade = purchasingDocumentExpeditionFacade;
     this.identityService = identityService;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="IdentityPasswordValidator"/> class.
 /// </summary>
 /// <param name="identityService">
 /// The identity service.
 /// </param>
 public IdentityPasswordValidator(IdentityService identityService)
 {
     this._identityService = identityService;
 }
Exemple #30
0
 public MonitoringCorrectionNoteExpenditureController(IServiceProvider serviceProvider, IMonitoringCorrectionNoteExpenditureFacade facade)
 {
     this.serviceProvider = serviceProvider;
     this.facade          = facade;
     this.identityService = (IdentityService)serviceProvider.GetService(typeof(IdentityService));
 }
 public AuthController() : base()
 {
     DbContext       = FactoryService.GetContext();
     IdentityService = SingletonFactoryService.GetIdentityService();
     JWTService      = SingletonFactoryService.GetJWTService();
 }
Exemple #32
0
 public TraceableBeacukaiController(ITraceableBeacukaiFacade facade, IServiceProvider serviceProvider)
 {
     this._facade         = facade;
     this.serviceProvider = serviceProvider;
     identityService      = (IdentityService)serviceProvider.GetService(typeof(IdentityService));
 }
 public void InvalidLoginTest()
 {
     IdentityService service = new IdentityService(Session);
     service.Login(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
 }
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            GlobalSettings.Exigo.VerifyEnvironment(HttpContext.Current);
            if (Request.IsSecureConnection)
            {
                Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
            }

            // Get the route data
            var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));

            // Account for attribute routing and null routeData
            if (routeData != null && routeData.Values.ContainsKey("MS_DirectRouteMatches"))
            {
                routeData = ((List <RouteData>)routeData.Values["MS_DirectRouteMatches"]).First();
            }


            // If we have an identity and the current identity matches the web alias in the routes, stop here.
            var identity = HttpContext.Current.Items["OwnerWebIdentity"] as ReplicatedSiteIdentity;

            if (routeData == null ||
                routeData.Values["webalias"] == null ||
                (identity != null && identity.WebAlias.Equals(routeData.Values["webalias"].ToString(), StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }


            // Determine some web alias data
            var urlHelper       = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current))));
            var currentWebAlias = routeData.Values["webalias"].ToString();
            var defaultWebAlias = GlobalSettings.ReplicatedSites.DefaultWebAlias;
            var lastWebAlias    = GlobalUtilities.GetLastWebAlias(defaultWebAlias);
            var defaultPage     = urlHelper.Action(routeData.Values["action"].ToString(), routeData.Values["controller"].ToString(), new { webalias = lastWebAlias });


            // This ensures that if the page is redirected because of web alias switching, that athe querystring params are passed as well
            if (currentWebAlias.ToLower() == GlobalSettings.ReplicatedSites.DefaultWebAlias.ToLower())
            {
                // Create new route value dictionary
                var newList = new RouteValueDictionary();

                // Pull in all values that are not the controller,action or webalias
                foreach (var routeValue in routeData.Values.Where(c => c.Key != "action" && c.Key != "controller" && c.Key != "webalias"))
                {
                    // Add all values that arent empty to the route data.
                    if (routeValue.Value.ToString().IsNotNullOrEmpty())
                    {
                        newList.Add(routeValue.Key, routeValue.Value);
                    }
                }
                // Grab query in case there are any pieces being sent in with ?example=value
                var query = Request.Url.Query;

                //add webalias to the route values.
                newList.Add("webalias", lastWebAlias);

                // create new url using new route values and add the query at the end.
                defaultPage = urlHelper.Action(routeData.Values["action"].ToString(), routeData.Values["controller"].ToString(), newList) + query;
            }


            // If we are an orphan and we don't allow them, redirect to a capture page.
            if (!Settings.AllowOrphans && currentWebAlias.Equals(defaultWebAlias, StringComparison.InvariantCultureIgnoreCase))
            {
                HttpContext.Current.Response.Redirect(urlHelper.Action("webaliasrequired", "error"));
            }


            // If we are an orphan, try to redirect the user back to a previously-visited replicated site
            if (Settings.RememberLastWebAliasVisited &&
                currentWebAlias.Equals(defaultWebAlias, StringComparison.InvariantCultureIgnoreCase) &&
                !defaultWebAlias.Equals(lastWebAlias, StringComparison.InvariantCultureIgnoreCase))
            {
                HttpContext.Current.Response.Redirect(defaultPage);
            }


            // Attempt to authenticate the web alias
            var identityService = new IdentityService();

            HttpContext.Current.Items["OwnerWebIdentity"] = identityService.GetIdentity(currentWebAlias);
            if (HttpContext.Current.Items["OwnerWebIdentity"] != null)
            {
                if (Settings.RememberLastWebAliasVisited && currentWebAlias.ToLower() != GlobalSettings.ReplicatedSites.DefaultWebAlias.ToLower())
                {
                    GlobalUtilities.SetLastWebAlias(currentWebAlias);
                }
                else
                {
                    GlobalUtilities.DeleteLastWebAlias();
                }
            }
            else
            {
                if (Settings.RememberLastWebAliasVisited)
                {
                    GlobalUtilities.DeleteLastWebAlias();
                    lastWebAlias = defaultWebAlias;
                    HttpContext.Current.Response.Redirect(defaultPage);
                }
                else
                {
                    HttpContext.Current.Response.Redirect(urlHelper.Action("invalidwebalias", "error"));
                }
            }
        }
Exemple #35
0
 public MoveActivityController(IdentityService identityService, ValidateService validateService, DealFacade facade)
 {
     this.IdentityService = identityService;
     this.Facade          = facade;
 }
 public IdentityController(IdentityService<User> identityService)
 {
     this.identityService = identityService;
 }