Inheritance: IAuthenticationService
        public void IsValidTest_只有驗證Authentication合法或非法()
        {
            //arrange
            //IProfile profile = MockRepository.GenerateStub<IProfile>();
            //profile.Stub(x => x.GetPassword("Joey")).Return("91");

            IProfile profile = Substitute.For<IProfile>();
            profile.GetPassword("Joey").Returns("91");

            //IToken token = MockRepository.GenerateStub<IToken>();
            //token.Stub(x => x.GetRandom("Joey")).Return("abc");
            IToken token = Substitute.For<IToken>();
            token.GetRandom("Joey").Returns("abc");

            //ILog log = MockRepository.GenerateStub<ILog>();
            ILog log = Substitute.For<ILog>();

            AuthenticationService target = new AuthenticationService(profile, token, log);
            string account = "Joey";
            string password = "******";
            // 正確的 password 應為 "91abc"

            //act
            bool actual;
            actual = target.IsValid(account, password);

            // assert
            Assert.IsFalse(actual);
        }
 public UpdateCommentTransactionScript(
     AuthenticationService authenticationService,
     CommentToCommentDTOMapper commentToCommentDtoMapper)
 {
     _authenticationService = authenticationService;
     _commentToCommentDtoMapper = commentToCommentDtoMapper;
 }
Esempio n. 3
0
        public void Create_New_User_Test()
        {
            var user = new User()
            {
                FirstName = "Joe",
                LastName = "Henss",
                UserName = "******",
                Password = Hasher.Hash("password"),
                PasswordSecurityQuestion = "Mother's maiden name",
                PasswordSecurityAnswer = "Hamilton"
            };

            var authenticationProvider = new AuthenticationService();
            var saveUserRequest = new SaveUserRequest() { User = user };

            var saveUserResponse = authenticationProvider.SaveUser(saveUserRequest);

            Assert.IsNotNull(saveUserResponse);
            Assert.AreEqual(ResponseStatus.Success, saveUserResponse.Status);

            var authenticateUserRequest = new AuthenticationRequest()
            {
                UserName = user.UserName,
                Password = user.Password
            };

            var authenticationResponse = authenticationProvider.AuthenticateUser(authenticateUserRequest);

            Assert.IsNotNull(authenticationResponse);
            Assert.AreEqual(ResponseStatus.Success, authenticationResponse.Status);
        }
 public CreatePostTransactionScript(
     AuthenticationService authenticationService,
     PostToPostDTOMapper postToPostDtoMapper)
 {
     _authenticationService = authenticationService;
     _postToPostDtoMapper = postToPostDtoMapper;
 }
        public void wrong_email_address_cannot_log_in()
        {
            _authService = new AuthenticationService(Session, _passwordHasher);
            var result = _authService.Login("invalidAddress", "SomePassword");

            Assert.AreEqual(LoginResult.unsuccessful, result);
        }
        public void OneTimeSetup()
        {
            _passwordHasher = Substitute.For<IPasswordHasher>();
            _passwordHasher.ComputeHash("somestring", new byte[4]).ReturnsForAnyArgs("hashedPassword");

            _authService = new AuthenticationService(Session, _passwordHasher);
        }
        public AuthenticationRegistry(IAuthenticationProvider facebookProvider,
                                      IAuthenticationProvider googleProvider,
                                      IAuthenticationProvider twitterProvider)
        {
            var authenticationService = new AuthenticationService();

            if (facebookProvider != null)
            {
                authenticationService.AddProvider(facebookProvider);
            }

            if (googleProvider != null)
            {
                authenticationService.AddProvider(googleProvider);
            }

            if (twitterProvider != null)
            {
                authenticationService.AddProvider(twitterProvider);
            }

            For<IAuthenticationService>()
                .Use(authenticationService)
                .Named("Authentication Service.");
        }
 public LoginController(
     UserAccountService userService, 
     AuthenticationService authSvc)
 {
     this.userAccountService = userService;
     this.authSvc = authSvc;
 }
 public void should_add_and_successfully_authenticate_the_first_user()
 {
     var userRepository = new MemoryRepository<User>();
     var authenticationService = new AuthenticationService(userRepository, new UserCreateService(userRepository));
     authenticationService.Authenticate(Username, Password);
     userRepository.Count().ShouldEqual(1);
 }
 public GetPostsTransactionScript(
     AuthenticationService authenticationService,
     PostToBriefPostDTOMapper postToBriefPostDtoMapper)
 {
     _authenticationService = authenticationService;
     _postToBriefPostDtoMapper = postToBriefPostDtoMapper;
 }
Esempio n. 11
0
 public SessionService(AuthenticationService authenticationService,
     IGitterApiService gitterApiService,
     IPasswordStorageService passwordStorageService)
 {
     _authenticationService = authenticationService;
     _gitterApiService = gitterApiService;
     _passwordStorageService = passwordStorageService;
 }
Esempio n. 12
0
 public ServiceAdapter()
 {
     authServ = new AuthenticationService();
     proServ = new ProfileService();
     dbcServ = new DaybookClientService();
     authServ.CookieContainer = new System.Net.CookieContainer();
     Instance = this;
 }
Esempio n. 13
0
        public void LogIn()
        {
            AuthenticationService authenticationService = new AuthenticationService(new UserRepository());

            var result = authenticationService.LogIn("rodrigo.cruz", "1234");

            Assert.AreEqual(false, result);
        }
 protected SecuredRemoteServiceBase(
     Configuration configuration,
     ConfigurationService configurationService,
     AuthenticationService authenticationService)
     : base(configuration, configurationService)
 {
     AuthenticationService = authenticationService;
 }
 public void should_successfully_authenticate_with_correct_credentials()
 {
     var authenticationService = new AuthenticationService(_userRepository, new UserCreateService(_userRepository));
     var result = authenticationService.Authenticate(Username, Password);
     result.ShouldNotBeNull();
     result.Username.ToString().ShouldEqual(Username);
     result.IsAdministrator.ShouldBeTrue();
 }
 public GetUserDetailsTransactionScript(
     AuthenticationService authenticationService,
     PostToBriefPostDTOMapper postToBriefPostDtoMapper,
     CommentToCommentDTOMapper commentToCommentDtoMapper)
 {
     _authenticationService = authenticationService;
     _postToBriefPostDtoMapper = postToBriefPostDtoMapper;
     _commentToCommentDtoMapper = commentToCommentDtoMapper;
 }
        public void TestAuthentication()
        {
            AuthenticationService service = new AuthenticationService();
            bool result = service.validate("guest", Encrypt("123456"));
            Assert.IsTrue(result);

            result = service.validate("guest", Encrypt("34545"));
            Assert.IsFalse(result);
        }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         this.authSvc.TryDispose();
         this.authSvc = null;
     }
     base.Dispose(disposing);
 }
Esempio n. 19
0
 public void RetrieveAuthenticateUserByUserIdAsync()
 {
     AuthenticationService authentication = new AuthenticationService();
     AuthenticateDetail userAccount = new AuthenticateDetail();
     userAccount.UserId = "0112";
     userAccount.Password = "******";
     var task = authentication.RetrieveAuthenticateUserByUserIdAsync(userAccount);
     Console.WriteLine("completed");
 }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.authenticationService.TryDispose();
                this.authenticationService = null;
            }

            base.Dispose(disposing);
        }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         this.userAccountService.TryDispose();
         this.userAccountService = null;
         this.authSvc.TryDispose();
         this.authSvc = null;
     }
     base.Dispose(disposing);
 }
        public void IsAdmin_WhenIdentityIsNull_IsAdminIsFalse()
        {
            //Arrange
            var service = new AuthenticationService();
            var applicationContext = Mock.Create<IApplicationContextService>();
            Mock.Arrange(() => applicationContext.Identity).Returns(() => null);
            service.ApplicationContextService = applicationContext;

            //Assert
            Assert.IsFalse(service.IsAdmin);
        }
            public void GivenAnInvalidProviderKey_RedirectToAuthenticationProvider_ThrowsAnException()
            {
                // Arrange.
                const string providerKey = "aaa";
                var authenticationService = new AuthenticationService();

                // Act and Assert.
                var result = Assert.Throws<AuthenticationException>(
                    () => authenticationService.RedirectToAuthenticationProvider(providerKey));

                Assert.NotNull(result);
                Assert.Equal("No 'aaa' provider has been added.", result.Message);
            }
Esempio n. 24
0
        private static string authenticate()
        {
            var authenticationService = new AuthenticationService();
            authenticationService.Url = ConfigurationManager.AppSettings["CheckboxRoot"] + "/Services/AuthenticationService.svc/soap";
            var callRes = authenticationService.Login(ConfigurationManager.AppSettings["User"], ConfigurationManager.AppSettings["Password"]);

            if (callRes.CallSuccess)
            {
                return callRes.ResultData;
            }
            else
                throw new Exception(callRes.FailureMessage);
        }
            public void GivenAValidProviderKeyWithNoState_RedirectToAuthenticate_ReturnsAUri()
            {
                // Arrange.
                var authenticationService = new AuthenticationService();
                authenticationService.AddProvider(new FacebookProvider("aa", "bb", new Uri("http://www.whatever.com")));

                // Act.
                var result = authenticationService.RedirectToAuthenticationProvider("Facebook");

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("https://www.facebook.com/dialog/oauth?client_id=aa&scope=email&redirect_uri=http://www.whatever.com/", result.AbsoluteUri);
            }
            public void GivenANullIAuthenticationServiceSettings_CheckCallback_ThrowsAnException()
            {
                // Arrange.
                var querystringParams = new NameValueCollection {{"a", "b"}};
                var authenticationService = new AuthenticationService();

                // Act and Assert.
                var result = Assert.Throws<ArgumentNullException>(
                    () => authenticationService.GetAuthenticatedClient(null, querystringParams));

                Assert.NotNull(result);
                Assert.Equal("Value cannot be null.\r\nParameter name: authenticationServiceSettings", result.Message);
            }
        /// <summary>
        /// Initializes a new instance of the <see cref="WebContextBase"/> class.
        /// </summary>
        /// <exception cref="InvalidOperationException"> is thrown if the constructor is invoked
        /// when <see cref="WebContextBase.Current"/> is valid and <paramref name="setAsCurrent"/>
        /// is <c>true</c>.
        /// </exception>
        /// <param name="setAsCurrent">Whether to use this context as the current instance</param>
        internal WebContextBase(bool setAsCurrent)
        {
            if (setAsCurrent)
            {
                if (WebContextBase.current != null)
                {
                    throw new InvalidOperationException(Resources.WebContext_OnlyOne);
                }
                WebContextBase.current = this;
            }

            this._authentication = new DefaultAuthentication();
        }
            public void GivenANewProvider_AddProvider_AddsTheProviderToTheProviderCollection()
            {
                // Arrange.
                var authenticationService = new AuthenticationService();

                // Act.
                authenticationService.AddProvider(new FacebookProvider("a", "b", new Uri("http://www.google.com")));

                // Assert.
                var providers = authenticationService.AuthenticationProviders;
                Assert.NotNull(providers);
                Assert.Equal(1, providers.Count);
                Assert.NotNull(providers["facebook"]);
            }
            public void GivenAnExistingProvider_AddProvider_ThrowsAnException()
            {
                // Arrange.
                var authenticationService = new AuthenticationService();
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"));
                // Act.
                authenticationService.AddProvider(facebookProvider);
                var result = Assert.Throws<AuthenticationException>( 
                    () => authenticationService.AddProvider(facebookProvider));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Trying to add a facebook provider, but one already exists.", result.Message);
            }
            public void GiveAMissingProviderKeyQuerystringValue_CheckCallback_ThrowsAnException()
            {
                // Arrange.
                var authenticationService = new AuthenticationService();

                // Act.
                var result =
                    Assert.Throws<ArgumentNullException>(
                        () => authenticationService.GetAuthenticatedClient(null, null, null));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Value cannot be null.\r\nParameter name: providerKey", result.Message);
            }
 public ConfigController(ConfigurationService config, AuthenticationService auth)
 {
     _config = config;
     _auth   = auth;
 }
Esempio n. 32
0
 public LoginController(AuthenticationService service)
 {
     authenticationService = service;
 }
Esempio n. 33
0
 public OutbreakController(MerlinReadStore readStore, MerlinReadContext readContext, OutbreakRules rules, OutbreakService service, LayoutRepository layoutRepository, AuthenticationService authenticationService, IConfiguration config, EpicomRepository epicomRepository, OutbreakRepository outbreakEventsRepository)
 {
     this.readStore             = readStore;
     this.readContext           = readContext;
     this.rules                 = rules;
     this.service               = service;
     this.layoutRepository      = layoutRepository;
     this.authenticationService = authenticationService;
     this.config                = config;
     this.epicomRepository      = epicomRepository;
     this.outbreakRepository    = outbreakEventsRepository;
 }
 public void Initialize()
 {
     _authenticationService = new AuthenticationService();
     _settingsService       = new SettingsService(new TestStorageService(), new EncryptionService(), _authenticationService);
 }
Esempio n. 35
0
 /// <summary>
 /// Default constructor for the Venue service
 /// </summary>
 /// <param name="context"></param>
 public VenueServiceApi(ApiContext context) : base(context, VenueHost)
 {
     context.AuthenticationMethod = AuthenticationMethod.JWT;
     AuthenticationService        = new AuthenticationService(context, VenueHost, "login");
 }
        public RedirectResult RedirectToProvider(RedirectToProviderInputModel inputModel)
        {
            if (!ModelState.IsValid)
            {
                throw new ArgumentException(
                          "Some binding errors occured. This means at least one Request value (eg. form post or querystring parameter) provided is invalid. Generally, we need a ProviderName as a string.");
            }

            if (string.IsNullOrEmpty(inputModel.ProviderKey))
            {
                throw new ArgumentException(
                          "ProviderKey value missing. You need to supply a valid provider key so we know where to redirect the user Eg. google.");
            }

            // Grab the required Provider settings.
            var settings = AuthenticationService.GetAuthenticateServiceSettings(inputModel.ProviderKey,
                                                                                Request.Url,
                                                                                Url.CallbackFromOAuthProvider());

            // An OpenId specific settings provided?
            if (!string.IsNullOrEmpty(inputModel.Identifier) &&
                settings is IOpenIdAuthenticationServiceSettings)
            {
                Uri identifier;
                if (!Uri.TryCreate(inputModel.Identifier, UriKind.RelativeOrAbsolute, out identifier))
                {
                    throw new ArgumentException(
                              "Indentifier value was not in the correct Uri format. Eg. http://myopenid.com or https://yourname.myopenid.com");
                }
                ((IOpenIdAuthenticationServiceSettings)settings).Identifier = identifier;
            }

            // Our convention is to remember some redirect url once we are finished in the callback.
            // NOTE: If no redirectUrl data has been provided, then default to the Referrer, if one exists.
            string extraData = null;

            if (RedirectUrl != null &&
                !string.IsNullOrEmpty(RedirectUrl.AbsoluteUri))
            {
                // We have extra state information we will need to retrieve.
                extraData = RedirectUrl.AbsoluteUri;
            }
            else if (Request != null &&
                     Request.UrlReferrer != null &&
                     !string.IsNullOrEmpty(Request.UrlReferrer.AbsoluteUri))
            {
                extraData = Request.UrlReferrer.AbsoluteUri;
            }

            // Generate a token pair.
            var token = AntiForgery.CreateToken(extraData);

            // Put the "ToSend" value in the state parameter to send along to the OAuth Provider.
            settings.State = token.ToSend;

            // Serialize the ToKeep value in the cookie.
            SerializeToken(Response, token.ToKeep);

            // Determine the provider's end point Url we need to redirect to.
            var uri = AuthenticationService.RedirectToAuthenticationProvider(settings);

            // Kthxgo!
            return(Redirect(uri.AbsoluteUri));
        }
Esempio n. 37
0
        private string GetLoggedInUserName(string authToken)
        {
            AuthenticationService authSvc = new AuthenticationService();

            return(authSvc.GetLoggedInUser(authToken));
        }
Esempio n. 38
0
 /// <summary>Initialize the identity aspects of brainCloud.</summary>
 /// <param name="profileId">The profile id</param>
 /// <param name="anonymousId">The anonymous id</param>
 public void InitializeIdentity(string profileId, string anonymousId)
 {
     AuthenticationService.Initialize(profileId, anonymousId);
 }
        public async void SignInResult_NotSucceded_ReturnFailed()
        {
            var mockLoggerSignInManager           = Mock.Of <ILogger <SignInManager <User> > >();
            var mockHttpContextAccessor           = Mock.Of <IHttpContextAccessor>();
            var mockUserStore                     = Mock.Of <IUserStore <User> >();
            var mockClaimsFactory                 = Mock.Of <IUserClaimsPrincipalFactory <User> >();
            var mockIOptions                      = Mock.Of <IOptions <IdentityOptions> >();
            var mockIUserConfirmation             = Mock.Of <IUserConfirmation <User> >();
            var mockIAuthenticationSchemeProvider =
                Mock.Of <Microsoft.AspNetCore.Authentication.IAuthenticationSchemeProvider>();
            var mockUserManager =
                new Mock <UserManager <User> >(mockUserStore, null, null, null, null, null, null, null, null);

            var mockSignInManager =
                new Mock <SignInManager <User> >(
                    mockUserManager.Object,
                    mockHttpContextAccessor,
                    mockClaimsFactory,
                    mockIOptions,
                    mockLoggerSignInManager,
                    mockIAuthenticationSchemeProvider,
                    mockIUserConfirmation
                    );

            var mockHttpContextAccessor1 = new Mock <IHttpContextAccessor>();

            var mockLogger             = Mock.Of <ILogger <AuthenticationService> >();
            var mockInteractionService = Mock.Of <IIdentityServerInteractionService>();

            mockHttpContextAccessor1
            .Setup(hca => hca.HttpContext.User)
            .Returns(() => null);

            mockSignInManager
            .Setup(sim => sim.IsSignedIn(It.IsAny <ClaimsPrincipal>()))
            .Returns(false);

            mockSignInManager
            .Setup(sim => sim.PasswordSignInAsync(
                       It.IsAny <string>(),
                       It.IsAny <string>(),
                       It.IsAny <bool>(),
                       It.IsAny <bool>()
                       ))
            .Returns(Task.Run(() => SignInResult.Failed));     // <-- NOT SUCEEDED

            var authenticationService =
                new AuthenticationService(mockSignInManager.Object,
                                          mockLogger,
                                          mockHttpContextAccessor1.Object,
                                          mockInteractionService
                                          );

            var mockLoginData = new LoginData {
                Username = "******",
                Password = "******",
            };

            var result = await authenticationService.Authenticate(mockLoginData);

            Assert.IsType <SignInResult>(result);

            Assert.False(result.Succeeded);

            mockSignInManager
            .Verify(sim => sim.IsSignedIn(It.IsAny <ClaimsPrincipal>()), Times.Once);

            mockSignInManager
            .Verify(sim => sim.PasswordSignInAsync(
                        It.IsAny <string>(),
                        It.IsAny <string>(),
                        It.IsAny <bool>(),
                        It.IsAny <bool>()
                        ), Times.Once);
        }
Esempio n. 40
0
 private void LoadSettings()
 {
     AuthenticationService.StartService(SimpleIoc.Default.GetInstance <IApplicationSettingsService>());
     ContactService.Current.StartService().ConfigureAwait(false);
     Settings.DownloadDisplayPictures = SimpleIoc.Default.GetInstance <IApplicationSettingsService>().Get(Constants.Settings.DownloadDisplayPictures, true);
 }
    private async Task <LoginResponse> LoginAsync()
    {
        AuthenticationService authenticationService = new AuthenticationService(tcpNetworkConnector, monoClientMessageProcessor);

        return(await authenticationService.LoginAsync(usernameInputField.text, passwordInputField.text));
    }
        public static async Task <int> ExecuteAsync(Arguments arguments)
        {
            Log.Info("Event statistics analysis begin");

            // validate arguments

            var input  = arguments.Source;
            var config = arguments.Config.ToFileInfo();

            if (!input.Exists)
            {
                throw new FileNotFoundException("Cannot find source file", input.FullName);
            }

            // try an automatically find the config file
            if (config == null)
            {
                throw new FileNotFoundException("No config file argument provided");
            }
            else if (!config.Exists)
            {
                Log.Warn($"Config file {config.FullName} not found... attempting to resolve config file");

                // we use  the original input string - Using FileInfo fullname always produces an
                // absolute path wrt to pwd... we don't want to prematurely make assumptions:
                // e.g. We require a missing absolute path to fail... that wouldn't work with .Name
                // e.g. We require a relative path to try and resolve, using .FullName would fail the first absolute
                //    check inside ResolveConfigFile
                config = ConfigFile.Resolve(arguments.Config, Directory.GetCurrentDirectory().ToDirectoryInfo());
            }

            // if a temp dir is not given, use output dir as temp dir
            if (arguments.TempDir == null)
            {
                Log.Warn("No temporary directory provided, using backup directory");
            }

            // Remote: create an instance of our API helpers
            IApi api = arguments.WorkbenchApi.IsNullOrEmpty() ? Api.Default : Api.Parse(arguments.WorkbenchApi);

            // log some helpful messages
            Log.Info("Events file:         " + input);
            Log.Info("Configuration file:  " + config);
            Log.Info("Output folder:       " + arguments.Output);
            Log.Info("Temp File Directory: " + arguments.TempDir);
            Log.Info("Api:                 " + api);

            // Remote: Test we can log in to the workbench
            var auth = new AuthenticationService(api);
            Task <IAuthenticatedApi> task;

            if (arguments.AuthenticationToken.IsNotWhitespace())
            {
                Log.Debug("Using token for authentication");
                task = auth.CheckLogin(arguments.AuthenticationToken);
            }
            else
            {
                var username = LoggedConsole.Prompt("Enter your username or email for the acoustic workbench:");
                var password = LoggedConsole.Prompt("Enter your password for the acoustic workbench:", forPassword: true);
                task = auth.Login(username, password);

                //task = auth.Login("*****@*****.**", "tsettest");
            }

            LoggedConsole.WriteWaitingLine(task, "Logging into workbench...");

            var authenticatedApi = await task.TimeoutAfter(Service.ClientTimeout).ConfigureAwait(false);

            Log.Info("Login success" + authenticatedApi);

            // read events/annotation file
            Log.Info("Now reading input data");

            // Read events from provided CSV file.
            // Also tag them with an order index to allow sorting in the same order as they were provided to us.
            var events = Csv
                         .ReadFromCsv <ImportedEvent>(input, throwOnMissingField: false)
                         .Select(
                (x, i) =>
            {
                x.Order = i;
                return(x);
            })
                         .ToArray();

            if (events.Length == 0)
            {
                Log.Warn("No events imported - source file empty. Exiting");
                return(ExceptionLookup.NoData);
            }

            Log.Info($"Events read, {events.Length} read.");

            // need to validate the events
            var invalidEvents = events.Where(e => !e.IsValid()).ToArray();

            if (invalidEvents.Length > 0)
            {
                throw new InvalidOperationException(
                          "Invalid event detected."
                          + $" {invalidEvents.Length} events are not valid. The first invalid event is {invalidEvents[0]}");
            }

            // next gather meta data for all events
            // and transform list of events into list of segments
            // NOTE: to save on I/O sometimes if events share the same audio block, then multiple events will be
            // bundled into the same analysis segment.
            var resolver = new EventMetadataResolver(
                authenticatedApi,
                PaddingFunction,
                arguments.Parallel ? 25 : 1);
            var metadataTask = resolver.GetRemoteMetadata(events);

            // wait for 1 second per event - this should be an order of magnitude greater than what is needed
            ISegment <AudioRecording>[] segments = await metadataTask.TimeoutAfter(events.Length);

            Log.Info($"Metadata collected, preparing to start analysis");

            // finally time to start preparing jobs
            ISourcePreparer preparer = new RemoteSourcePreparer(authenticatedApi, allowSegmentcutting: false);

            AnalysisCoordinator coordinator = new AnalysisCoordinator(
                preparer,
                SaveBehavior.Never,
                uniqueDirectoryPerSegment: false,
                isParallel: arguments.Parallel);

            // instantiate the Analysis
            EventStatisticsAnalysis analysis = new EventStatisticsAnalysis();

            // derserialize the config file
            var configuration = analysis.ParseConfig(config);

            AnalysisSettings settings = analysis.DefaultSettings;

            settings.AnalysisOutputDirectory = arguments.Output;
            settings.AnalysisTempDirectory   = arguments.TempDir;
            settings.Configuration           = configuration;

            var results = coordinator.Run(segments, analysis, settings);

            var allEvents = results.SelectMany(es => es.Events).ToArray();

            var eventsWithErrors = allEvents.Count(x => ((EventStatistics)x).Error);

            if (eventsWithErrors > 0)
            {
                Log.Warn($"Errors occurred when calculating statistics for {eventsWithErrors} events.");
            }

            Log.Trace("Sorting event statistics results");
            Array.Sort(allEvents);

            Log.Info("Executing summary");

            // TODO: implement if needed
            analysis.SummariseResults(settings, null, allEvents, null, null, results);

            Log.Debug("Summary complete");

            var instanceOutputDirectory =
                AnalysisCoordinator.GetNamedDirectory(settings.AnalysisOutputDirectory, analysis);

            var resultName = FilenameHelpers.AnalysisResultPath(
                instanceOutputDirectory,
                input,
                analysis.Identifier,
                "csv");

            // NOTE: we are only saving event files
            Log.Info($"Writing results to {resultName}");
            analysis.WriteEventsFile(resultName.ToFileInfo(), allEvents.AsEnumerable());
            Log.Debug("Writing events completed");

            var summaryStats = new
            {
                numberEvents           = allEvents.Length,
                durationEvents         = allEvents.Sum(x => ((EventStatistics)x).EventDurationSeconds),
                numberRecordings       = allEvents.Select(x => ((EventStatistics)x).AudioRecordingId).Distinct().Count(),
                durationAudioProcessed = results.Sum(x => x.SegmentAudioDuration.TotalSeconds),
                remoteAudioDownloaded  = (preparer as RemoteSourcePreparer)?.TotalBytesRecieved,
            };

            Log.Info("Summary statistics:\n" + Json.SerializeToString(summaryStats));

            Log.Success("Event statistics analysis complete!");

            return(ExceptionLookup.Ok);
        }
Esempio n. 43
0
 public EmailController(UserRepository userRepository, AuthenticationService authenticationService)
 {
     this.userRepository        = userRepository;
     this.authenticationService = authenticationService;
 }
Esempio n. 44
0
 public UserController(AuthenticationService authService, UserService userService, HttpContextExtensible httpContext)
 {
     _authService = authService;
     _userService = userService;
     _httpContext = httpContext;
 }
Esempio n. 45
0
        public async Task Init()
        {
            IDataGateway                   dataGateway      = new SQLServerGateway();
            IConnectionStringData          connectionString = new ConnectionStringData();
            IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString);

            IUserChannelsRepo userChannelsRepo = new UserChannelsRepo(dataGateway, connectionString);
            var userChannels = await userChannelsRepo.GetAllUserChannelsAsync();

            foreach (var userChannel in userChannels)
            {
                await userChannelsRepo.DeleteUserChannelsByIdAsync(userChannel.Id);
            }

            await DataAccessTestHelper.ReseedAsync("UserChannels", 0, connectionString, dataGateway);


            IMessagesRepo messagesRepo = new MessagesRepo(dataGateway, connectionString);
            var           messages     = await messagesRepo.GetAllMessagesAsync();

            foreach (var message in messages)
            {
                await messagesRepo.DeleteMessageByIdAsync(message.Id);
            }

            await DataAccessTestHelper.ReseedAsync("Messages", 0, connectionString, dataGateway);


            IChannelsRepo channelsRepo = new ChannelsRepo(dataGateway, connectionString);
            var           channels     = await channelsRepo.GetAllChannelsAsync();

            foreach (var channel in channels)
            {
                await channelsRepo.DeleteChannelbyIdAsync(channel.Id);
            }

            await DataAccessTestHelper.ReseedAsync("Channels", 0, connectionString, dataGateway);



            var settings = await userAccountSettingsRepository.GetAllSettings();

            foreach (var setting in settings)
            {
                await userAccountSettingsRepository.DeleteUserAccountSettingsByUserId(setting.UserId);
            }

            await DataAccessTestHelper.ReseedAsync("UserAccountSettings", 0, connectionString, dataGateway);

            IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString);
            var accounts = await userAccountRepository.GetAllAccounts();

            foreach (var account in accounts)
            {
                await userAccountRepository.DeleteAccountById(account.Id);
            }

            await DataAccessTestHelper.ReseedAsync("UserAccount", 0, connectionString, dataGateway);



            int i = 1;
            UserAccountModel userAccountModel = new UserAccountModel();

            userAccountModel.Id            = i;
            userAccountModel.Username      = "******" + i;
            userAccountModel.Password      = "" + i;
            userAccountModel.Salt          = "" + i;
            userAccountModel.EmailAddress  = "TestEmailAddress" + i;
            userAccountModel.AccountType   = "TestAccountType" + i;
            userAccountModel.AccountStatus = "TestAccountStatus" + i;
            userAccountModel.CreationDate  = DateTimeOffset.UtcNow;
            userAccountModel.UpdationDate  = DateTimeOffset.UtcNow;

            await userAccountRepository.CreateAccount(userAccountModel);

            UserAccountRepository userAccountRepo     = new UserAccountRepository(new SQLServerGateway(), new ConnectionStringData());
            ICryptographyService  cryptographyService = new CryptographyService(userAccountRepo);

            await cryptographyService.newPasswordEncryptAsync("Password", 1);

            UserAccountSettingsModel userAccountSettingsModel = new UserAccountSettingsModel();

            userAccountSettingsModel.Id         = 0;
            userAccountSettingsModel.UserId     = 1;
            userAccountSettingsModel.FontSize   = 12;
            userAccountSettingsModel.FontStyle  = "Time New Roman";
            userAccountSettingsModel.ThemeColor = "White";


            IAuthenticationService  authenticationService      = new AuthenticationService(userAccountRepository);
            IAccountSettingsService userAccountSettingsManager = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService);


            await userAccountSettingsManager.CreateUserAccountSettingsAsync(userAccountSettingsModel);


            i = 2;
            userAccountModel.Id            = i;
            userAccountModel.Username      = "******" + i;
            userAccountModel.Password      = "" + i;
            userAccountModel.Salt          = "" + i;
            userAccountModel.EmailAddress  = "TestEmailAddress" + i;
            userAccountModel.AccountType   = "TestAccountType" + i;
            userAccountModel.AccountStatus = "TestAccountStatus" + i;
            userAccountModel.CreationDate  = DateTimeOffset.UtcNow;
            userAccountModel.UpdationDate  = DateTimeOffset.UtcNow;

            await userAccountRepository.CreateAccount(userAccountModel);


            await cryptographyService.newPasswordEncryptAsync("Password", 1);

            userAccountSettingsModel.Id         = 0;
            userAccountSettingsModel.UserId     = 1;
            userAccountSettingsModel.FontSize   = 12;
            userAccountSettingsModel.FontStyle  = "Time New Roman";
            userAccountSettingsModel.ThemeColor = "White";



            await userAccountSettingsManager.CreateUserAccountSettingsAsync(userAccountSettingsModel);
        }
Esempio n. 46
0
 public ChangeUsernameController(AuthenticationService authSvc)
 {
     this.userAccountService = authSvc.UserAccountService;
     this.authSvc            = authSvc;
 }
Esempio n. 47
0
        public virtual ActionResult Index(LoginViewModel model, string returnUrl)
        {
            try
            {
                bool         userflag = false;
                tbl_UserData currentUserData;

                if (!ModelState.IsValid)
                {
                    return(View(model));
                }
                model.UserTypes = new List <UserType>
                {
                    new UserType {
                        ID = "1", Type = "Internal"
                    },
                    new UserType {
                        ID = "2", Type = "External"
                    }
                };

                //  model.roleID = model.GetRoleID(model.ID);

                //model.UserTypeId = "1";

                if (model.UserTypeId == "1")
                {
                    model.UserTypeId       = "1";
                    ViewData["UserTypeID"] = 1;

                    // usually this will be injected via DI. but creating this manually now for brevity
                    IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
                    currentUserData = model.CheckUser(model.Username);

                    Session["CurrentLoggedInUserDetails"] = currentUserData;


                    if (currentUserData != null)
                    {
                        userflag = true;
                    }

                    if (userflag)
                    {
                        if (currentUserData.Active == "1")
                        {
                            var authService = new AuthenticationService(authenticationManager);

                            var authenticationResult = authService.SignIn(model.Username, model.Password);



                            if (authenticationResult.IsSuccess)
                            {
                                return(RedirectToLocal(returnUrl));
                            }

                            ModelState.AddModelError("", authenticationResult.ErrorMessage);
                        }
                        else
                        {
                            ViewBag.Message = "User is Inactive..please contact your administrator";
                            return(View(loginViewModel));
                        }
                    }
                    else
                    {
                        ViewBag.Message = "User does not exist..please contact your administrator";
                        return(View(loginViewModel));
                        //return View("Error");
                    }
                }
                else
                {
                    model.UserTypeId       = "2";
                    ViewData["UserTypeID"] = 2;


                    //getting the role id of the person who logs in
                    var roleId = loginViewModel.GetRoleID(model.Username, model.Password);

                    model.lstActionType = loginViewModel.GetMappedScreenRoles(roleId);


                    //Form Authentication
                    IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;

                    currentUserData = model.CheckUser(model.Username, model.Password);

                    Session["CurrentLoggedInUserDetails"] = currentUserData;

                    if (currentUserData != null)
                    {
                        userflag = true;
                    }

                    //if (model.CheckUser().Any(a => a.userName == model.Username && a.password == model.Password))// && a.Status == true))
                    if (userflag)
                    {
                        if (currentUserData.Active == "1")
                        {
                            var authService = new AuthenticationService(authenticationManager);
                            authService.SignInExternalUser(model.Username, model.Password);

                            return(RedirectToLocal(returnUrl));
                        }
                        else
                        {
                            ViewBag.Message = "User is Inactive..please contact your administrator";
                            return(View(loginViewModel));
                        }
                    }
                    else
                    {
                        ViewBag.Message = "Invalid login attempt.";
                        return(View(loginViewModel));
                        //ModelState.AddModelError("", "Invalid login attempt.");
                    }
                }


                return(View(model));
            }
            catch (Exception ex)
            {
                errorlogviewmodel = new ErrorLogViewModel();
                errorlogviewmodel.LogError(ex);
                return(View("Error"));
            }
        }
Esempio n. 48
0
        public bool CheckIsAdmin(int ServiceType = 9)
        {
            bool IsAdmin    = false;
            int? MemberType = 0;

            MemberType = LogonMemberType != 0 ? LogonMemberType : GetMemberType();


            if (Request.Cookies.Count <= 0)
            {
                #region Get Cookie
                AuthenticationService svAuthentication = new AuthenticationService();
                Hashtable             htCookieInfo     = svAuthentication.GetCookieAuthentication();
                if (htCookieInfo.Count > 0)
                {
                    HttpCookie ck = new HttpCookie("MemberID");
                    ck.Value   = Convert.ToString(htCookieInfo["MemberID"]);
                    ck.Expires = DateTime.Now.AddDays(1);
                    Request.Cookies.Add(ck);
                }
                else
                {
                    IsAdmin = false;
                }
                #endregion
                if (MemberType == 2)
                {
                    IsAdmin = true;
                }
            }
            else
            {
                if (MemberType == 2)
                {
                    IsAdmin = true;
                }
            }

            if (LogonServiceType == 9)
            {
                IsAdmin = true;
            }
            else if (ServiceType == 9)
            {
                if (LogonServiceType == 9)
                {
                    IsAdmin = true;
                }
                else
                {
                    IsAdmin = false;
                }
            }
            else if (LogonServiceType == ServiceType)
            {
                IsAdmin = true;
            }
            else
            {
                IsAdmin = false;
            }
            return(IsAdmin);
        }
 public AuthenticationController(AuthenticationService securityService)
 {
     _AuthenticationService = securityService;
 }
Esempio n. 50
0
        private static async Task RenewAsync(Overrides overrides, ILogger log, CancellationToken cancellationToken,
                                             ExecutionContext executionContext)
        {
            // internal storage (used for letsencrypt account metadata)
            IStorageProvider storageProvider = new AzureBlobStorageProvider(Environment.GetEnvironmentVariable("AzureWebJobsStorage"), "letsencrypt");

            IConfigurationProcessor processor = new ConfigurationProcessor();
            var configurations = await LoadConfigFilesAsync(storageProvider, processor, log, cancellationToken, executionContext);

            IAuthenticationService authenticationService = new AuthenticationService(storageProvider);
            var az = new AzureHelper();

            var tokenProvider  = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback));
            var storageFactory = new StorageFactory(az);

            var renewalOptionsParser = new RenewalOptionParser(az, keyVaultClient, storageFactory, log);
            var certificateBuilder   = new CertificateBuilder();

            IRenewalService renewalService = new RenewalService(authenticationService, renewalOptionsParser, certificateBuilder, log);
            var             stopwatch      = new Stopwatch();
            // TODO: with lots of certificate renewals this could run into function timeout (10mins)
            // with 30 days to expiry (default setting) this isn't a big problem as next day all finished certs are skipped
            // user will only get email <= 14 days before expiry so acceptable for now
            var errors = new List <Exception>();

            foreach ((var name, var config) in configurations)
            {
                using (log.BeginScope($"Working on certificates from {name}"))
                {
                    foreach (var cert in config.Certificates)
                    {
                        stopwatch.Restart();
                        var hostNames = string.Join(";", cert.HostNames);
                        cert.Overrides = overrides ?? Overrides.None;
                        try
                        {
                            var result = await renewalService.RenewCertificateAsync(config.Acme, cert, cancellationToken);

                            switch (result)
                            {
                            case RenewalResult.NoChange:
                                log.LogInformation($"Certificate renewal skipped for: {hostNames} (no change required yet)");
                                break;

                            case RenewalResult.Success:
                                log.LogInformation($"Certificate renewal succeeded for: {hostNames}");
                                break;

                            default:
                                throw new ArgumentOutOfRangeException(result.ToString());
                            }
                        }
                        catch (Exception e)
                        {
                            log.LogError(e, $"Certificate renewal failed for: {hostNames}!");
                            errors.Add(e);
                        }
                        log.LogInformation($"Renewing certificates for {hostNames} took: {stopwatch.Elapsed}");
                    }
                }
            }
            if (!configurations.Any())
            {
                log.LogWarning("No configurations where processed, refere to the sample on how to set up configs!");
            }
            if (errors.Any())
            {
                throw new AggregateException("Failed to process all certificates", errors);
            }
        }
Esempio n. 51
0
        public ActionResult UserCompanyCode()
        {
            IMembershipService     membershipService;
            IAuthenticationService authenticationService;

            membershipService     = new MembershipService(Membership.Provider);
            authenticationService = new AuthenticationService(membershipService, new FormsAuthenticationService());

            MembershipUser user        = membershipService.GetUser(User.Identity.Name);
            var            userId      = user == null ? Guid.Empty : (Guid)(user.ProviderUserKey ?? Guid.Empty);
            var            isCorporate = User.IsInRole("Corporate");
            string         username    = user.UserName;

            int[] assignedFranchises;

            var DefaultCompamyName = default(String);
            var DefaultCompanyID   = default(int);

            DefaultCompamyName = (from g in memberShipContext.UserFranchise
                                  where g.FranchiseID == 56 && g.UserId == userId
                                  select g.Franchise.FranchiseNumber).FirstOrDefault();
            if (DefaultCompamyName == null)
            {
                DefaultCompamyName = (from g in memberShipContext.UserFranchise
                                      where g.UserId == userId
                                      select g.Franchise.FranchiseNumber).FirstOrDefault();
            }

            DefaultCompanyID = (from g in memberShipContext.UserFranchise
                                where g.FranchiseID == 56 && g.UserId == userId
                                select g.Franchise.FranchiseID).FirstOrDefault();
            if (DefaultCompanyID == 0)
            {
                DefaultCompanyID = (from g in memberShipContext.UserFranchise
                                    where g.UserId == userId
                                    select g.Franchise.FranchiseID).FirstOrDefault();
            }


            if (RouteData.Values["id"] != null)
            {
                int companyCodeID = int.Parse(Convert.ToString(RouteData.Values["id"]));
                DefaultCompamyName = (from g in memberShipContext.UserFranchise
                                      where g.FranchiseID == companyCodeID && g.UserId == userId
                                      select g.Franchise.FranchiseNumber).FirstOrDefault();
                DefaultCompanyID = (from g in memberShipContext.UserFranchise
                                    where g.FranchiseID == companyCodeID && g.UserId == userId
                                    select g.Franchise.FranchiseID).FirstOrDefault();
            }

            using (var ctx = new MembershipConnection())
            {
                assignedFranchises = ctx.UserFranchise
                                     .Where(uf => uf.UserId == userId)
                                     .Select(f => f.FranchiseID)
                                     .ToArray();
            }

            var model = new GrantCompaniesToUser
            {
                UserName           = username,
                GrantedCompanyCode =
                    memberShipContext.MembershipFranchise
                    .Where(f => assignedFranchises.Contains(f.FranchiseID))
                    .OrderBy(f => f.FranchiseNumber)
                    .Select(d => new SelectListItem
                {
                    Text  = d.FranchiseNumber,
                    Value = System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)d.FranchiseID)
                })
                    .ToList(),
                defaultCompanyName = DefaultCompamyName,
                defaultCompanyID   = DefaultCompanyID
            };

            return(PartialView("CompanyCodeUser", model));
        }
Esempio n. 52
0
 public GoogleController(AuthenticationService service, UserRepository userRepo)
 {
     this.authenticationService = service;
     this.userRepository        = userRepo;
 }
Esempio n. 53
0
 public AuthenticationController(IUsersRepository usersRepository, AuthenticationService authenticationService)
 {
     this.authenticationService = authenticationService;
     this.usersRepository       = usersRepository;
 }
Esempio n. 54
0
 protected void Page_Load(object sender, EventArgs e)
 {
     MyAuthenticationService = new AuthenticationService();
 }
 public HomeController(
     UserAccountService userAccountService, AuthenticationService authSvc)
 {
     this.userAccountService = userAccountService;
     this.authSvc            = authSvc;
 }
 public ChangeUsernameController(
     UserAccountService <CustomUserAccount> userAccountService, AuthenticationService <CustomUserAccount> authSvc)
 {
     this.userAccountService = userAccountService;
     this.authSvc            = authSvc;
 }
Esempio n. 57
0
    public List <LogVO> LoadLogEntries(int min, int max)
    {
        List <LogVO> result = null;

        try
        {
            AuthenticationService.CheckIfUSerIsAuthenticated();
            LogService.Log("LogService", "LoadLogs", String.Format("Min:{0}; Max: {1}", min, max));

            LogTableAdapter adapter = new LogTableAdapter();
            result = new List <LogVO>();

            ONyRDataSet.LogDataTable table = adapter.GetDataByRowNumber(min, max);
            for (int i = 0; i < table.Count; ++i)
            {
                DateTime date;
                try
                {
                    date = table[i].Date;
                }
                catch (Exception)
                {
                    date = DateTime.MinValue;
                }
                String sparams;
                try
                {
                    sparams = table[i].Params;
                }
                catch (Exception)
                {
                    sparams = "";
                }
                String userName;
                try
                {
                    userName = table[i].UserName;
                }
                catch (Exception)
                {
                    userName = "";
                }

                result.Add(new LogVO(table[i].ID, table[i].ServiceName, table[i].OperationName, sparams, userName, date));
            }

            adapter.Dispose();
        }
        catch (ONyRException e)
        {
            LogService.LogError(e.ErrorCode, e.StackTrace);
            throw new FaultException <ONyRFaultException>(new ONyRFaultException((int)e.ErrorCode));
        }
        catch (Exception e)
        {
            LogService.LogError(ErrorCode.UnknownError, e.StackTrace, e.Message);
            throw new FaultException <ONyRFaultException>(new ONyRFaultException((int)ErrorCode.UnknownError));
        }

        return(result);
    }
Esempio n. 58
0
        protected override void OnInvoke(RtmpConnection connection, RtmpChannel channel, RtmpHeader header, Notify invoke)
        {
            IServiceCall serviceCall = invoke.ServiceCall;

            // If it's a callback for server remote call then pass it over to callbacks handler
            // and return
            if (serviceCall.ServiceMethodName.Equals("_result") || serviceCall.ServiceMethodName.Equals("_error"))
            {
                HandlePendingCallResult(connection, invoke);
                return;
            }

            bool   disconnectOnReturn = false;
            string action             = null;

            if (serviceCall.ServiceName == null)
            {
                action = serviceCall.ServiceMethodName;
                switch (action)
                {
                case ACTION_CONNECT:
                {
                    if (!connection.IsConnected)
                    {
                        IDictionary parameters = invoke.ConnectionParameters;
                        string      host       = null;
                        if (parameters.Contains("tcUrl"))
                        {
                            host = GetHostname(parameters["tcUrl"] as string);
                        }
                        if (host != null && host.IndexOf(":") != -1)
                        {
                            // Remove default port from connection string
                            host = host.Substring(0, host.IndexOf(":"));
                        }
                        string app  = parameters["app"] as string;
                        string path = parameters["app"] as string;
                        // App name as path, but without query string if there is one
                        if (path != null && path.IndexOf("?") != -1)
                        {
                            int idx = path.IndexOf("?");
                            parameters["queryString"] = path.Substring(idx);
                            path = path.Substring(0, idx);
                        }
                        parameters["path"] = path;

                        connection.Setup(host, path, parameters);
                        try
                        {
                            //IGlobalScope global = this.Endpoint.LookupGlobal(host, path);
                            IGlobalScope global = this.Endpoint.GetMessageBroker().GlobalScope;
                            if (global == null)
                            {
                                serviceCall.Status = Call.STATUS_SERVICE_NOT_FOUND;
                                if (serviceCall is IPendingServiceCall)
                                {
                                    StatusASO status = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_INVALID_APPLICATION, connection.ObjectEncoding);
                                    status.description = "No global scope on this server.";
                                    (serviceCall as IPendingServiceCall).Result = status;
                                }
                                log.Info(string.Format("No application scope found for {0} on host {1}. Misspelled or missing application folder?", path, host));
                                disconnectOnReturn = true;
                            }
                            else
                            {
                                IScopeContext context = global.Context;
                                IScope        scope   = null;
                                try
                                {
                                    scope = context.ResolveScope(global, path);
                                }
                                catch (ScopeNotFoundException /*exception*/)
                                {
                                    if (log.IsErrorEnabled)
                                    {
                                        log.Error(__Res.GetString(__Res.Scope_NotFound, path));
                                    }

                                    serviceCall.Status = Call.STATUS_SERVICE_NOT_FOUND;
                                    if (serviceCall is IPendingServiceCall)
                                    {
                                        StatusASO status = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_REJECTED, connection.ObjectEncoding);
                                        status.description = "No scope \"" + path + "\" on this server.";
                                        (serviceCall as IPendingServiceCall).Result = status;
                                    }
                                    disconnectOnReturn = true;
                                }
                                catch (ScopeShuttingDownException)
                                {
                                    serviceCall.Status = Call.STATUS_APP_SHUTTING_DOWN;
                                    if (serviceCall is IPendingServiceCall)
                                    {
                                        StatusASO status = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_APPSHUTDOWN, connection.ObjectEncoding);
                                        status.description = "Application at \"" + path + "\" is currently shutting down.";
                                        (serviceCall as IPendingServiceCall).Result = status;
                                    }
                                    log.Info(string.Format("Application at {0} currently shutting down on {1}", path, host));
                                    disconnectOnReturn = true;
                                }
                                if (scope != null)
                                {
                                    if (log.IsInfoEnabled)
                                    {
                                        log.Info(__Res.GetString(__Res.Scope_Connect, scope.Name));
                                    }
                                    bool okayToConnect;
                                    try
                                    {
                                        //The only way to differentiate NetConnection.connect() and Consumer.subscribe() seems to be the app name
                                        if (app == string.Empty)
                                        {
                                            connection.SetIsFlexClient(true);
                                            okayToConnect = connection.Connect(scope, serviceCall.Arguments);
                                            if (okayToConnect)
                                            {
                                                if (serviceCall.Arguments != null && serviceCall.Arguments.Length >= 3)
                                                {
                                                    string credentials = serviceCall.Arguments[2] as string;
                                                    if (credentials != null && credentials != string.Empty)
                                                    {
                                                        MessageBroker         messageBroker         = this.Endpoint.GetMessageBroker();
                                                        AuthenticationService authenticationService = messageBroker.GetService(AuthenticationService.ServiceId) as AuthenticationService;
                                                        authenticationService.Authenticate(credentials);
                                                    }
                                                }
                                                //FDS 2.0.1 fds.swc
                                                if (serviceCall.Arguments != null && serviceCall.Arguments.Length == 1)
                                                {
                                                    string credentials = serviceCall.Arguments[0] as string;
                                                    if (credentials != null && credentials != string.Empty)
                                                    {
                                                        MessageBroker         messageBroker         = this.Endpoint.GetMessageBroker();
                                                        AuthenticationService authenticationService = messageBroker.GetService(AuthenticationService.ServiceId) as AuthenticationService;
                                                        authenticationService.Authenticate(credentials);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            connection.SetIsFlexClient(false);
                                            okayToConnect = connection.Connect(scope, serviceCall.Arguments);
                                        }
                                        if (okayToConnect)
                                        {
                                            if (log.IsDebugEnabled)
                                            {
                                                log.Debug("Connected RtmpClient: " + connection.Client.Id);
                                            }
                                            serviceCall.Status = Call.STATUS_SUCCESS_RESULT;
                                            if (serviceCall is IPendingServiceCall)
                                            {
                                                StatusASO statusASO = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_SUCCESS, connection.ObjectEncoding);
                                                statusASO.Add("id", connection.Client.Id);
                                                (serviceCall as IPendingServiceCall).Result = statusASO;
                                            }
                                            // Measure initial roundtrip time after connecting
                                            connection.GetChannel((byte)2).Write(new Ping(Ping.StreamBegin, 0, -1));
                                            connection.StartRoundTripMeasurement();
                                        }
                                        else
                                        {
                                            if (log.IsDebugEnabled)
                                            {
                                                log.Debug("Connect failed");
                                            }
                                            serviceCall.Status = Call.STATUS_ACCESS_DENIED;
                                            if (serviceCall is IPendingServiceCall)
                                            {
                                                (serviceCall as IPendingServiceCall).Result = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_REJECTED, connection.ObjectEncoding);
                                            }
                                            disconnectOnReturn = true;
                                        }
                                    }
                                    catch (ClientRejectedException rejected)
                                    {
                                        if (log.IsDebugEnabled)
                                        {
                                            log.Debug("Connect rejected");
                                        }
                                        serviceCall.Status = Call.STATUS_ACCESS_DENIED;
                                        if (serviceCall is IPendingServiceCall)
                                        {
                                            StatusASO statusASO = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_REJECTED, connection.ObjectEncoding);
                                            statusASO.Application = rejected.Reason;
                                            (serviceCall as IPendingServiceCall).Result = statusASO;
                                        }
                                        disconnectOnReturn = true;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (log.IsErrorEnabled)
                            {
                                log.Error("Error connecting", ex);
                            }

                            serviceCall.Status = Call.STATUS_GENERAL_EXCEPTION;
                            if (serviceCall is IPendingServiceCall)
                            {
                                (serviceCall as IPendingServiceCall).Result = StatusASO.GetStatusObject(StatusASO.NC_CONNECT_FAILED, connection.ObjectEncoding);
                            }
                            disconnectOnReturn = true;
                        }
                    }
                    else
                    {
                        // Service calls, must be connected.
                        InvokeCall(connection, serviceCall);
                    }
                }
                break;

                case ACTION_DISCONNECT:
                    connection.Close();
                    break;

                case ACTION_CREATE_STREAM:
                case ACTION_DELETE_STREAM:
                case ACTION_RELEASE_STREAM:
                case ACTION_PUBLISH:
                case ACTION_PLAY:
                case ACTION_SEEK:
                case ACTION_PAUSE:
                case ACTION_CLOSE_STREAM:
                case ACTION_RECEIVE_VIDEO:
                case ACTION_RECEIVE_AUDIO:
                {
                    IStreamService streamService = ScopeUtils.GetScopeService(connection.Scope, typeof(IStreamService)) as IStreamService;
                    StatusASO      status        = null;
                    try
                    {
                        if (!InvokeCall(connection, serviceCall, streamService))
                        {
                            status             = StatusASO.GetStatusObject(StatusASO.NS_INVALID_ARGUMENT, connection.ObjectEncoding);
                            status.description = "Failed to " + action + " (stream ID: " + header.StreamId + ")";
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error while invoking " + action + " on stream service.", ex);
                        status             = StatusASO.GetStatusObject(StatusASO.NS_FAILED, connection.ObjectEncoding);
                        status.description = "Error while invoking " + action + " (stream ID: " + header.StreamId + ")";
                        status.details     = ex.Message;
                    }
                    if (status != null)
                    {
                        channel.SendStatus(status);
                    }
                }
                break;

                default:
                    if (connection.IsConnected)
                    {
                        InvokeCall(connection, serviceCall);
                    }
                    else
                    {
                        // Warn user attemps to call service without being connected
                        if (log.IsWarnEnabled)
                        {
                            log.Warn("Not connected, closing connection");
                        }
                        connection.Close();
                    }
                    break;
                }
            }

            /*
             *          if(invoke is FlexInvoke)
             *          {
             *                  FlexInvoke reply = new FlexInvoke();
             *                  reply.InvokeId = invoke.InvokeId;
             *                  reply.SetResponseSuccess();
             *                  //TODO
             *                  if( serviceCall is IPendingServiceCall )
             *                  {
             *                          IPendingServiceCall pendingCall = (IPendingServiceCall)serviceCall;
             *                          reply.Response = pendingCall.Result;
             *                  }
             *                  channel.Write(reply);
             *          }
             *          else if(invoke is Invoke)
             */
            if (invoke is Invoke)
            {
                if ((header.StreamId != 0) &&
                    (serviceCall.Status == Call.STATUS_SUCCESS_VOID || serviceCall.Status == Call.STATUS_SUCCESS_NULL))
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Method does not have return value, do not reply");
                    }
                    return;
                }

                // The client expects a result for the method call.
                Invoke reply = new Invoke();
                reply.ServiceCall = serviceCall;
                reply.InvokeId    = invoke.InvokeId;
                //sending reply
                channel.Write(reply);
            }
            if (disconnectOnReturn)
            {
                connection.Close();
            }
            if (action == ACTION_CONNECT)
            {
                connection.Context.ObjectEncoding = connection.ObjectEncoding;
            }
        }
Esempio n. 59
0
        public string Get(int id)
        {
            AuthenticationService service = new AuthenticationService();

            return("value");
        }
Esempio n. 60
0
 public AuthenticationTestBase()
 {
     _authStore             = new Mock <IAuthStore>();
     _authenticationService = new AuthenticationService(_authStore.Object);
 }