Exemple #1
0
        private async Task <string> EnsureNuGetExeExistsAsync(
            ILogger logger,
            string userSpecifiedNuGetExePath,
            string nugetExeUri = null)
        {
            if (!string.IsNullOrWhiteSpace(userSpecifiedNuGetExePath))
            {
                var fileInfo = new FileInfo(userSpecifiedNuGetExePath);

                if (fileInfo.Name.Equals("nuget.exe", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (File.Exists(userSpecifiedNuGetExePath))
                    {
                        logger.Write(
                            $"Using NuGet '{userSpecifiedNuGetExePath}' from user specified variable '{WellKnownVariables.ExternalTools_NuGet_ExePath_Custom}'");
                        return(userSpecifiedNuGetExePath);
                    }

                    logger.WriteWarning(
                        $"User has specified custom NuGet '{userSpecifiedNuGetExePath}' but the file does not exist, using fallback method to ensure NuGet exists");
                }
                else
                {
                    logger.WriteWarning(
                        $"User has specified custom NuGet '{userSpecifiedNuGetExePath}' but it does not have name 'nuget.exe', ignoring and using fallback method to ensure NuGet exists");
                }
            }

            logger.WriteVerbose("Using default method to ensure NuGet exists");

            var    helper       = new NuGetHelper(logger);
            string nuGetExePath = await helper.EnsureNuGetExeExistsAsync(nugetExeUri, _cancellationToken);

            return(nuGetExePath);
        }
Exemple #2
0
        private void TurnServer_PeerDataReceived(ref ServerAsyncEventArgs e)
        {
            //lock (syncRoot)
            {
                try
                {
                    Allocation allocation = allocations.GetByPeer(e.LocalEndPoint, e.RemoteEndPoint);

                    if (allocation != null)
                    {
                        allocation.TouchLifetime();

                        if (allocation.IsActiveDestinationEnabled)
                        {
                            e.LocalEndPoint  = allocation.Alocated;
                            e.RemoteEndPoint = allocation.ActiveDestination;
                            e.Count          = e.BytesTransferred;
                            e.ConnectionId   = ServerAsyncEventArgs.AnyNewConnectionId;

                            peerServer.SendAsync(e);

                            e = null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.WriteWarning(ex.ToString());
                }
            }
        }
Exemple #3
0
        public static List <AutomationElement> FindAll(UIATestObject testObject)
        {
            _Logger.WriteLog(LogTypeEnum.Debug, () => "FindAll:\r\n" + UIAUtility.DumpTestObject(testObject));

            List <AutomationElement> matchedElements =
                ConditionLocator(testObject);

            if (matchedElements.Count == 0)
            {
                _Logger.WriteWarning("Can not find child in the parent container:" + testObject.ControlName);
                return(matchedElements);
            }

            /*
             * // if window, just check the caption, 60% match will be recognized.
             * call the following lines in sequence
             * matchedElements = TopWindowLocator(testObject, matchedElements);
             * matchedElements = LeftRightLocator(testObject, matchedElements);
             * matchedElements = IndexLocator(testObject, matchedElements);
             */
            matchedElements = FilterWithLocators(testObject, matchedElements);

            if (matchedElements.Count == 1)
            {
                return(matchedElements);                            //ignore other optional parameters
            }
            matchedElements = FindInMatchedCollection(testObject, matchedElements);

            _Logger.WriteDebug("FindAll returns count:" + matchedElements.Count);

            return(matchedElements);
        }
        public async Task <IHttpActionResult> PostAsync([FromBody] IEvent @event)
        {
            return(await ActionHelper.TryCatchWithLoggerAsync(async() =>
            {
                _logger.WriteDebug(new LogMessage(string.Concat("VecompSoftware.DocSuiteWeb.WebAPI.Controllers.ServiceBus.TopicController.PostAsync(", @event != null, ")")), LogCategories);
                if (@event == null)
                {
                    _logger.WriteWarning(new LogMessage(string.Concat("Event received is invalid (json deserialization set null value) : ",
                                                                      GetType().ToString())), LogCategories);

                    return BadRequest("Event received is invalid (json deserialization set null value)");
                }

                _logger.WriteInfo(new LogMessage(string.Concat("Event received ", @event.ToString())), LogCategories);

                if (!_validationService.Validate(@event, _ruleset.INSERT))
                {
                    _logger.WriteWarning(new LogMessage(string.Concat("Service Bus validation error: ", GetType().ToString())), LogCategories);
                    return BadRequest("Service Bus validation error.");
                }

                ServiceBusMessage message = _mapper.Map(@event, new ServiceBusMessage());
                if (string.IsNullOrEmpty(message.ChannelName))
                {
                    throw new DSWException(string.Concat("Topic name to event [", @event.ToString(), "] is not mapped"), null, DSWExceptionCode.SC_Mapper);
                }
                ServiceBusMessage response = await _service.SendToTopicAsync(message);
                return Ok(response);
            }, BadRequest, Content, InternalServerError, _logger, LogCategories));
        }
Exemple #5
0
        public async Task <IActionResult> FindMessage([FromQuery] string query)
        {
            ViewBag.Localization     = _translationLookup;
            ViewBag.EnableColorCodes = _manager.GetApplicationSettings().Configuration().EnableColorCodes;
            ViewBag.Query            = query;
            ViewBag.QueryLimit       = 100;
            ViewBag.Title            = _translationLookup["WEBFRONT_STATS_MESSAGES_TITLE"];
            ViewBag.Error            = null;
            ViewBag.IsFluid          = true;
            ChatSearchQuery searchRequest = null;

            try
            {
                searchRequest = query.ParseSearchInfo(int.MaxValue, 0);
            }

            catch (ArgumentException e)
            {
                _logger.WriteWarning($"Could not parse chat message search query - {query}");
                _logger.WriteDebug(e.GetExceptionInfo());
                ViewBag.Error = e;
            }

            catch (FormatException e)
            {
                _logger.WriteWarning($"Could not parse chat message search query filter format - {query}");
                _logger.WriteDebug(e.GetExceptionInfo());
                ViewBag.Error = e;
            }

            var result = searchRequest != null ? await _chatResourceQueryHelper.QueryResource(searchRequest) : null;

            return(View("Message/Find", result));
        }
 public StatPoint[] Collect()
 {
     try
     {
         _performanceCounter = _initializer();
     }
     catch (CategoryNotFoundException e)
     {
         lock (MutexWarningIsLogged)
         {
             if (_warningIsLogged)
             {
                 return(new StatPoint[0]);
             }
             _warningIsLogged = true;
         }
         _logger.WriteWarning(e.ToString());
         return(new StatPoint[0]);
     }
     try
     {
         return(_performanceCounter.Collect());
     }
     catch (Exception e)
     {
         _performanceCounter = null;
         _logger.WriteWarning(e.ToString());
         return(new StatPoint[0]);
     }
 }
        protected virtual Task <AuthenticationTicket> ProcessAuthValue(string authValue)
        {
            if (authValue.StartsWith(Options.AuthenticationType, StringComparison.OrdinalIgnoreCase))
            {
                log.WriteVerbose($"{Options.AuthenticationType} auth type detected");
                var token = authValue.Substring(Options.AuthenticationType.Length + 1);
                if (!string.IsNullOrWhiteSpace(token))
                {
                    var identity = new ClaimsIdentity(Options.AuthenticationType);
                    if (token[0] == Const.ComplexTokenMarker)
                    {
                        FillupComplexIdentity(token.Substring(1), identity);
                    }
                    else
                    {
                        FillUpSimpleIdentity(token, identity);
                    }

                    log.WriteInformation($"Authenticated successfully as {token}");
                    return(Task.FromResult(new AuthenticationTicket(identity, new AuthenticationProperties())));
                }
                log.WriteWarning("No user info found in Authorization header");
            }
            else
            {
                log.WriteWarning("Unsupported authorization type");
            }
            return(Task.FromResult <AuthenticationTicket>(null));
        }
Exemple #8
0
        private async void StartAsync([NotNull] ServerMain main, CancellationToken simulatorToken, CancellationToken mainToken)
        {
            if (main == null)
            {
                throw new ArgumentNullException(nameof(main));
            }

            while (!simulatorToken.IsCancellationRequested && !mainToken.IsCancellationRequested)
            {
                try
                {
                    await main.StartAsync(mainToken);
                }
                catch (Exception e)
                {
                    _logger.WriteError(e.ToString());
                    _logger.WriteWarning("Sleep 10 seconds before restart..");
                    await Task.Delay(TimeSpan.FromSeconds(10), simulatorToken);
                }

                if (!mainToken.IsCancellationRequested)
                {
                    _logger.WriteWarning("Restarting simulator..");
                }
            }
        }
Exemple #9
0
        private async Task <bool> IsCurrentDirectoryClonableAsync()
        {
            if (!_directoryCloneEnabled)
            {
                _logger.WriteVerbose("Directory clone is disabled");
                return(false);
            }

            _logger.WriteVerbose("Directory clone is enabled");

            string sourceRoot = VcsPathHelper.TryFindVcsRootPath();

            if (string.IsNullOrWhiteSpace(sourceRoot))
            {
                _logger.WriteWarning("Could not find source root", _Prefix);
                return(false);
            }

            bool isClonable = false;

            string gitExePath = GitHelper.GetGitExePath(_logger);

            if (!string.IsNullOrWhiteSpace(gitExePath))
            {
                string gitDir = Path.Combine(sourceRoot, ".git");

                var statusAllArguments = new[]
                {
                    $"--git-dir={gitDir}",
                    $"--work-tree={sourceRoot}",
                    "status"
                };

                var argumentVariants = new List <string[]> {
                    new[] { "status" }, statusAllArguments
                };

                foreach (string[] argumentVariant in argumentVariants)
                {
                    ExitCode statusExitCode = await ProcessRunner.ExecuteAsync(
                        gitExePath,
                        arguments : argumentVariant,
                        standardOutLog : _logger.WriteVerbose,
                        standardErrorAction : _logger.WriteVerbose,
                        toolAction : _logger.Write,
                        verboseAction : _logger.WriteVerbose);

                    if (statusExitCode.IsSuccess)
                    {
                        isClonable = true;
                        break;
                    }
                }
            }

            _logger.WriteVerbose($"Is directory clonable: {isClonable}");

            return(isClonable);
        }
Exemple #10
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                var query = Request.Query;
                var protectedRequestToken = Request.Cookies[StateCookie];

                var returnedToken = query.Get("oauth_token");
                if (string.IsNullOrWhiteSpace(returnedToken))
                {
                    _logger.WriteWarning("Missing oauth_token");
                    return(new AuthenticationTicket(null, properties));
                }

                var oauthVerifier = query.Get("oauth_verifier");
                if (string.IsNullOrWhiteSpace(oauthVerifier))
                {
                    _logger.WriteWarning("Missing or blank oauth_verifier");
                    return(new AuthenticationTicket(null, properties));
                }

                var context = new RavenAuthenticatedContext(Context)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                if (!string.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId,
                                                        XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName,
                                                        XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FullName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.FullName,
                                                        XmlSchemaString, Options.AuthenticationType));
                }

                Response.Cookies.Delete(StateCookie);

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #11
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationTicket      ticket = null;
            IReadableStringCollection query  = Request.Query;
            var redirectUrl = query.Get(Options.ReturnUrlParameter);
            var state       = query.Get("state");
            var grantType   = query.Get("");


            try
            {
                string cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName);
                if (string.IsNullOrWhiteSpace(cookie))
                {
                    return(await GenerateEmptyTiket(redirectUrl));
                }

                ticket = Options.TicketDataFormat.Unprotect(cookie);
                if (ticket == null)
                {
                    _logger.WriteWarning(@"Unprotect ticket failed");
                    return(await GenerateEmptyTiket(redirectUrl));
                }
                if (Options.SessionStore != null)
                {
                    Claim claim = ticket.Identity.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim));
                    if (claim == null)
                    {
                        _logger.WriteWarning(@"SessoinId missing");
                        return(await GenerateEmptyTiket(redirectUrl));
                    }
                    _sessionKey = claim.Value;
                    ticket      = await Options.SessionStore.RetrieveAsync(_sessionKey);

                    if (ticket == null)
                    {
                        _logger.WriteWarning(@"Identity missing in session store");
                        return(await GenerateEmptyTiket(redirectUrl));
                    }
                }
                DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
                DateTimeOffset?issuedUtc  = ticket.Properties.IssuedUtc;
                DateTimeOffset?expiresUtc = ticket.Properties.ExpiresUtc;

                if (expiresUtc != null && expiresUtc.Value < currentUtc)
                {
                    return(await GenerateEmptyTiket(redirectUrl));
                }
                ticket.Properties.RedirectUri = redirectUrl;
                return(ticket);
            }
            catch (Exception exception)
            {
                _logger.WriteError("Authenticate error", exception);
                ticket = new AuthenticationTicket(null, new AuthenticationProperties());
                ticket.Properties.RedirectUri = redirectUrl;
                return(ticket);
            }
        }
        private async Task EnsureMinNuGetVersionAsync(string nuGetExePath, ILogger logger)
        {
            void NullLogger(string message, string category)
            {
            }

            var     standardOut   = new List <string>();
            ILogger versionLogger = new DelegateLogger(
                (message, category) => standardOut.Add(message),
                NullLogger,
                NullLogger);

            IEnumerable <string> args            = new List <string>();
            ExitCode             versionExitCode = await ProcessHelper.ExecuteAsync(nuGetExePath, args, versionLogger);

            if (!versionExitCode.IsSuccess)
            {
                logger.WriteWarning($"NuGet version exit code was {versionExitCode}");
                return;
            }

            string nugetVersion = "NuGet Version: ";
            string versionLine  =
                standardOut.FirstOrDefault(
                    line => line.StartsWith(nugetVersion, StringComparison.InvariantCultureIgnoreCase));

            if (string.IsNullOrWhiteSpace(versionLine))
            {
                logger.WriteWarning("Could not ensure NuGet version, no version line in NuGet output");
                return;
            }

            char majorNuGetVersion = versionLine.Substring(nugetVersion.Length).FirstOrDefault();

            if (majorNuGetVersion == '2')
            {
                IEnumerable <string> updateSelfArgs = new List <string> {
                    "update", "-self"
                };
                ExitCode exitCode = await ProcessHelper.ExecuteAsync(nuGetExePath, updateSelfArgs, logger);

                if (!exitCode.IsSuccess)
                {
                    logger.WriteWarning($"The NuGet version could not be determined, exit code {exitCode}");
                }

                return;
            }

            if (majorNuGetVersion != '3')
            {
                logger.WriteWarning(
                    $"NuGet version could not be determined, major version starts with character {majorNuGetVersion}");
                return;
            }

            logger.WriteVerbose($"NuGet major version is {majorNuGetVersion}");
        }
Exemple #13
0
        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <returns></returns>
        public async Task Invoke(IDictionary <string, object> environment)
        {
            var context = new OwinContext(environment);

            var token = await GetTokenAsync(context);

            if (token == null)
            {
                await _next(environment);

                return;
            }

            context.Set("idsrv:tokenvalidation:token", token);

            // seems to be a JWT
            if (token.Contains('.'))
            {
                // see if local validation is setup
                if (_localValidationFunc != null)
                {
                    await _localValidationFunc.Value(environment);

                    return;
                }
                // otherwise use validation endpoint
                if (_endpointValidationFunc != null)
                {
                    await _endpointValidationFunc.Value(environment);

                    return;
                }

                _logger.WriteWarning("No validator configured for JWT token");
            }
            else
            {
                if (_referenceTokenValidationFunc != null)
                {
                    await _referenceTokenValidationFunc.Value(environment);

                    return;
                }

                // use validation endpoint
                if (_endpointValidationFunc != null)
                {
                    await _endpointValidationFunc.Value(environment);

                    return;
                }

                _logger.WriteWarning("No validator configured for reference token");
            }

            await _next(environment);
        }
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);

            if (signout != null)
            {
                AuthenticationProperties properties = signout.Properties;

                B2CConfigurationManager mgr = Options.ConfigurationManager as B2CConfigurationManager;
                _configuration = await mgr.GetConfigurationAsync(Context.Request.CallCancelled, "b2c_1_sign_in");

                OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage()
                {
                    IssuerAddress = _configuration.EndSessionEndpoint ?? string.Empty,
                    RequestType   = OpenIdConnectRequestType.LogoutRequest,
                };

                string redirect = string.Empty;
                if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
                {
                    openIdConnectMessage.PostLogoutRedirectUri = properties.RedirectUri;
                    redirect = properties.RedirectUri;
                }
                else if (!string.IsNullOrWhiteSpace(Options.PostLogoutRedirectUri))
                {
                    openIdConnectMessage.PostLogoutRedirectUri = Options.PostLogoutRedirectUri;
                    redirect = Options.RedirectUri;
                }

                if (string.IsNullOrWhiteSpace(openIdConnectMessage.PostLogoutRedirectUri))
                {
                    throw new Exception("For B2C, the PostLogoutRedirectUri is required.");
                }
                if (string.IsNullOrWhiteSpace(redirect))
                {
                    throw new Exception("For B2C, the RedirectUri is required.");
                }

                var notification = new RedirectToIdentityProviderNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage
                };
                await Options.Notifications.RedirectToIdentityProvider(notification);

                if (!notification.HandledResponse)
                {
                    string redirectUri = notification.ProtocolMessage.CreateLogoutRequestUrl();
                    redirectUri = redirectUri + "&" + OpenIdConnectParameterNames.RedirectUri + "=" + HttpUtility.UrlEncode(redirect) + "&" + OpenIdConnectParameterNames.ClientId + "=" + Options.ClientId;
                    if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                    {
                        _logger.WriteWarning("The logout redirect URI is malformed: " + redirectUri);
                    }
                    Response.Redirect(redirectUri);
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Handles Signout
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);

            if (signout == null)
            {
                return;
            }

            if (_configuration == null)
            {
                _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
            }

            WsFederationMessage wsFederationMessage = new WsFederationMessage()
            {
                IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
                Wtrealm       = Options.Wtrealm,
                Wa            = WsFederationActions.SignOut,
            };

            // Set Wreply in order:
            // 1. properties.Redirect
            // 2. Options.SignOutWreply
            // 3. Options.Wreply
            AuthenticationProperties properties = signout.Properties;

            if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
            {
                wsFederationMessage.Wreply = properties.RedirectUri;
            }
            else if (!string.IsNullOrWhiteSpace(Options.SignOutWreply))
            {
                wsFederationMessage.Wreply = Options.SignOutWreply;
            }
            else if (!string.IsNullOrWhiteSpace(Options.Wreply))
            {
                wsFederationMessage.Wreply = Options.Wreply;
            }

            var notification = new RedirectToIdentityProviderNotification <WsFederationMessage, WsFederationAuthenticationOptions>(Context, Options)
            {
                ProtocolMessage = wsFederationMessage
            };
            await Options.Notifications.RedirectToIdentityProvider(notification);

            if (!notification.HandledResponse)
            {
                string redirectUri = notification.ProtocolMessage.CreateSignOutUrl();
                if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                {
                    _logger.WriteWarning("The sign-out redirect URI is malformed: " + redirectUri);
                }
                Response.Redirect(redirectUri);
            }
        }
Exemple #16
0
        public async Task <ExitCode> ExecuteAsync(
            ILogger logger,
            IReadOnlyCollection <IVariable> buildVariables,
            CancellationToken cancellationToken)
        {
            bool enabled = buildVariables.GetBooleanByKey(WellKnownVariables.VSTestEnabled, true);

            if (!enabled)
            {
                logger.WriteWarning("VSTest not enabled");
                return(ExitCode.Success);
            }

            string reportPath =
                buildVariables.Require(WellKnownVariables.ExternalTools_VSTest_ReportPath).ThrowIfEmptyValue().Value;

            _sourceRoot = buildVariables.Require(WellKnownVariables.SourceRoot).ThrowIfEmptyValue().Value;

            string vsTestExePath = buildVariables.GetVariableValueOrDefault(
                WellKnownVariables.ExternalTools_VSTest_ExePath,
                string.Empty);

            if (string.IsNullOrWhiteSpace(vsTestExePath))
            {
                logger.WriteWarning(
                    $"{WellKnownVariables.ExternalTools_VSTest_ExePath} is not defined, cannot run any VSTests");
                return(ExitCode.Success);
            }

            bool ignoreTestFailures = buildVariables.GetBooleanByKey(
                WellKnownVariables.IgnoreTestFailures,
                false);

            bool runTestsInReleaseConfiguration =
                buildVariables.GetBooleanByKey(
                    WellKnownVariables.RunTestsInReleaseConfigurationEnabled,
                    true);

            string assemblyFilePrefix = buildVariables.GetVariableValueOrDefault(WellKnownVariables.TestsAssemblyStartsWith, string.Empty);

            if (ignoreTestFailures)
            {
                try
                {
                    return(await RunVsTestAsync(logger, reportPath, vsTestExePath, runTestsInReleaseConfiguration, assemblyFilePrefix));
                }
                catch (Exception ex)
                {
                    logger.WriteWarning($"Ignoring test exception: {ex}");
                }

                return(ExitCode.Success);
            }

            return(await RunVsTestAsync(logger, reportPath, vsTestExePath, runTestsInReleaseConfiguration, assemblyFilePrefix));
        }
Exemple #17
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;
                string protectedRequestToken    = Request.Cookies[StateCookie];

                RequestToken requestToken = DeveloperAuthenticationOptions.StateDataFormat.Unprotect(protectedRequestToken);

                if (requestToken == null)
                {
                    _logger.WriteWarning("Invalid state");
                    return(null);
                }

                properties = requestToken.Properties;

                var formCollection = await Request.ReadFormAsync();

                var accessToken = new AccessToken()
                {
                    CallBackUri       = requestToken.CallBackUri,
                    CallbackConfirmed = requestToken.CallbackConfirmed,
                    Properties        = requestToken.Properties,
                    ScreenName        = formCollection["_email"],
                    UserId            = formCollection["_userId"]
                };


                var context = new DeveloperAuthenticatedContext(Context, accessToken.UserId, accessToken.ScreenName, accessToken.Token, accessToken.TokenSecret);

                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(ClaimTypes.Name, accessToken.ScreenName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                context.Properties = requestToken.Properties;

                Response.Cookies.Delete(StateCookie);

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Exemple #18
0
        protected bool ValidateCorrelationId(ICookieManager cookieManager, AuthenticationProperties properties, ILogger logger)
        {
            if (cookieManager == null)
            {
                throw new ArgumentNullException("cookieManager");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;

            string correlationCookie = cookieManager.GetRequestCookie(Context, correlationKey);

            if (string.IsNullOrWhiteSpace(correlationCookie))
            {
                logger.WriteWarning("{0} cookie not found.", correlationKey);
                return(false);
            }

            var cookieOptions = new CookieOptions
            {
                SameSite = SameSiteMode.None,
                HttpOnly = true,
                Secure   = Request.IsSecure
            };

            cookieManager.DeleteCookie(Context, correlationKey, cookieOptions);

            string correlationExtra;

            if (!properties.Dictionary.TryGetValue(
                    correlationKey,
                    out correlationExtra))
            {
                logger.WriteWarning("{0} state property not found.", correlationKey);
                return(false);
            }

            properties.Dictionary.Remove(correlationKey);

            if (!string.Equals(correlationCookie, correlationExtra, StringComparison.Ordinal))
            {
                logger.WriteWarning("{0} correlation cookie and state property mismatch.", correlationKey);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Handles Signout
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);

            if (signout == null)
            {
                return;
            }

            SamlMessage SamlMessage = await SamlMessageFromRequest();

            // WS Fed was "TokenAddress". Not sure this is the right endpoint
            SamlMessage.IssuerAddress = Options.Configuration.ServiceProvider.Endpoints.DefaultLogoutEndpoint.RedirectUrl ?? string.Empty;
            SamlMessage.Reply         = string.Empty;

            // Set Wreply in order:
            // 1. properties.Redirect
            // 2. Options.SignOutWreply
            // 3. Options.Wreply
            AuthenticationProperties properties = signout.Properties;

            if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
            {
                SamlMessage.Reply = properties.RedirectUri;
            }
            else if (!string.IsNullOrWhiteSpace(Options.Configuration.ServiceProvider.Endpoints.DefaultLogoutEndpoint.RedirectUrl))
            {
                SamlMessage.Reply = Options.Configuration.ServiceProvider.Endpoints.DefaultLogoutEndpoint.RedirectUrl;
            }

            var notification = new RedirectToIdentityProviderNotification <SamlMessage, SamlAuthenticationOptions>(Context, Options)
            {
                ProtocolMessage = SamlMessage
            };
            await Options.Notifications.RedirectToIdentityProvider(notification);

            if (!notification.HandledResponse)
            {
                string redirectUri = notification.ProtocolMessage.BuildSignOutRedirectUrl();
                if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                {
                    _logger.WriteWarning("The sign-out redirect URI is malformed: " + redirectUri);
                }

                if (Context.Request.IsAjaxRequest())
                {
                    Response.Headers.Add("X-Location", new[] { redirectUri });
                }
                else
                {
                    Response.Redirect(redirectUri);
                }
            }
        }
        private async Task <bool> InvokeReplyPathAsync()
        {
            if (!Options.CallbackPath.HasValue || Options.CallbackPath != Request.Path)
            {
                return(false);
            }
            // TODO: error responses

            var ticket = await AuthenticateAsync();

            if (ticket == null)
            {
                _logger.WriteWarning("Invalid return state, unable to redirect.");
                Response.StatusCode = 500;
                return(true);
            }

            var context = new LinkedInReturnEndpointContext(Context, ticket)
            {
                SignInAsAuthenticationType = Options.SignInAsAuthenticationType,
                RedirectUri = ticket.Properties.RedirectUri
            };

            await Options.Provider.ReturnEndpoint(context);

            if (context.SignInAsAuthenticationType != null &&
                context.Identity != null)
            {
                var grantIdentity = context.Identity;
                if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
                {
                    grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
                }
                Context.Authentication.SignIn(context.Properties, grantIdentity);
            }

            if (context.IsRequestCompleted || context.RedirectUri == null)
            {
                return(context.IsRequestCompleted);
            }
            var redirectUri = context.RedirectUri;

            if (context.Identity == null)
            {
                // add a redirect hint that sign-in failed in some way
                redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
            }
            Response.Redirect(redirectUri);
            context.RequestCompleted();

            return(context.IsRequestCompleted);
        }
Exemple #21
0
        protected override async Task <AuthenticationTicket> AuthenticateCore()
        {
            _logger.WriteVerbose("AuthenticateCore");

            IDictionary <string, string> cookies = Request.GetCookies();
            string cookie;

            if (!cookies.TryGetValue(Options.CookieName, out cookie))
            {
                _logger.WriteWarning("No cookie found");
                return(null);
            }

            AuthenticationTicket model = Options.TicketDataHandler.Unprotect(cookie);

            if (model == null)
            {
                _logger.WriteWarning("null model");
                return(null);
            }

            DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
            DateTimeOffset?issuedUtc  = model.Extra.IssuedUtc;
            DateTimeOffset?expiresUtc = model.Extra.ExpiresUtc;

            if (expiresUtc != null && expiresUtc.Value < currentUtc)
            {
                return(null);
            }

            if (issuedUtc != null && expiresUtc != null && Options.SlidingExpiration)
            {
                TimeSpan timeElapsed   = currentUtc.Subtract(issuedUtc.Value);
                TimeSpan timeRemaining = expiresUtc.Value.Subtract(currentUtc);

                if (timeRemaining < timeElapsed)
                {
                    _shouldRenew    = true;
                    _renewIssuedUtc = currentUtc;
                    TimeSpan timeSpan = expiresUtc.Value.Subtract(issuedUtc.Value);
                    _renewExpiresUtc = currentUtc.Add(timeSpan);
                }
            }

            var context = new FormsValidateIdentityContext(model);

            await Options.Provider.ValidateIdentity(context);

            return(new AuthenticationTicket(context.Identity, context.Extra));
        }
        public async Task <IEnumerable <IVariable> > GetEnvironmentVariablesAsync(
            ILogger logger,
            IReadOnlyCollection <IVariable> buildVariables,
            CancellationToken cancellationToken)
        {
            string dotNetExePath =
                buildVariables.GetVariableValueOrDefault(WellKnownVariables.DotNetExePath, string.Empty);

            if (!string.IsNullOrWhiteSpace(dotNetExePath))
            {
                return(Array.Empty <IVariable>());
            }

            if (string.IsNullOrWhiteSpace(dotNetExePath))
            {
                var sb = new List <string>(10);

                string winDir = Environment.GetEnvironmentVariable("WINDIR");

                if (string.IsNullOrWhiteSpace(winDir))
                {
                    logger.WriteWarning("Error finding Windows directory");
                    return(Array.Empty <IVariable>());
                }

                string whereExePath = Path.Combine(winDir, "System32", "where.exe");

                ExitCode exitCode = await Processing.ProcessRunner.ExecuteAsync(
                    whereExePath,
                    arguments : new[] { "dotnet.exe" },
                    standardOutLog : (message, _) => sb.Add(message),
                    cancellationToken : cancellationToken);

                if (!exitCode.IsSuccess)
                {
                    logger.WriteError("Failed to find dotnet.exe with where.exe");
                }

                dotNetExePath =
                    sb.FirstOrDefault(item => item.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase))?.Trim();
            }
            else if (!File.Exists(dotNetExePath))
            {
                logger.WriteWarning(
                    $"The specified path to dotnet.exe is from variable '{WellKnownVariables.DotNetExePath}' is set to '{dotNetExePath}' but the file does not exist");
                return(Array.Empty <IVariable>());
            }

            return(new[] { new EnvironmentVariable(WellKnownVariables.DotNetExePath, dotNetExePath) });
        }
        /// <summary>
        /// Handles Signout
        /// </summary>
        /// <returns></returns>
        protected override async Task ApplyResponseGrantAsync()
        {
            var signout = SignOutContext;

            if (signout != null)
            {
                if (_configuration == null && Options.ConfigurationManager != null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
                }

                OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage()
                {
                    IssuerAddress = _configuration == null ? string.Empty : (_configuration.EndSessionEndpoint ?? string.Empty),
                    RequestType   = OpenIdConnectRequestType.LogoutRequest,
                };

                // Set End_Session_Endpoint in order:
                // 1. properties.Redirect
                // 2. Options.Wreply
                AuthenticationProperties properties = new AuthenticationProperties();
                if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
                {
                    openIdConnectMessage.PostLogoutRedirectUri = properties.RedirectUri;
                }
                else if (!string.IsNullOrWhiteSpace(Options.PostLogoutRedirectUri))
                {
                    openIdConnectMessage.PostLogoutRedirectUri = Options.PostLogoutRedirectUri;
                }

                var notification = new RedirectToIdentityProviderNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage
                };

                await Options.Notifications.RedirectToIdentityProvider(notification);

                if (!notification.HandledResponse)
                {
                    string redirectUri = notification.ProtocolMessage.CreateLogoutRequestUrl();
                    if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
                    {
                        _logger.WriteWarning("The logout redirect URI is malformed: {0}", (redirectUri ?? "null"));
                    }

                    Response.Redirect(redirectUri);
                }
            }
        }
Exemple #24
0
        public static void DropDatabase(string databaseName, ILogger logger)
        {
            try
            {
                logger.WriteInformation("Trying to drop database '{0}'", databaseName);
                using (var conn = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB;Database=master;Trusted_Connection=True;"))
                {
                    conn.Open();

                    var cmd = conn.CreateCommand();
                    cmd.CommandText = string.Format(@"IF EXISTS (SELECT * FROM sys.databases WHERE name = N'{0}')
                                          BEGIN
                                               ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
                                               DROP DATABASE [{0}];
                                          END", databaseName);
                    cmd.ExecuteNonQuery();

                    logger.WriteInformation("Successfully dropped database {0}", databaseName);
                }
            }
            catch (Exception exception)
            {
                //Ignore if there is failure in cleanup.
                logger.WriteWarning("Error occured while dropping database {0}. Exception : {1}", databaseName, exception.ToString());
            }
        }
Exemple #25
0
 private void Scene_ComponentAdded(object sender, ComponentEventArgs args)
 {
     if (Container == null)
     {
         _logger.WriteWarning("Scene container failed to initialize, skipping injection");
         return;
     }
     try
     {
         Container.LateInject(args.Component);
     }
     catch (Exception e)
     {
         _logger.WriteError(e.Message);
     }
 }
        public T RetryingPolicyAction <T>(Func <T> func, string proccesName, ILogger _logger, IEnumerable <LogCategory> LogCategories, int step = 1)
        {
            _logger.WriteDebug(new LogMessage($"RetryingPolicyAction : tentative {step}/{_retry_tentative} in progress..."), LogCategories);
            if (step >= _retry_tentative)
            {
                _logger.WriteError(new LogMessage("BiblosDS.Library.Common.Converter.Office.OfficeToPdfConverter.RetryingPolicyAction: retry policy expired maximum tentatives"), LogCategories);
                throw new Exception("OpenOfficeToPdfConverter retry policy expired maximum tentatives");
            }
            try
            {
#if DEBUG
                if (step < 3)
                {
                    throw new COMException();
                }
#endif
                return(func());
            }
            catch (COMException ex)
            {
                _logger.WriteWarning(new LogMessage(string.Concat($"SafeActionWithRetryPolicy : tentative {step}/{_retry_tentative} failed. Killing Office process before retry.", ex)), LogCategories);
                //localContext = null;
                KillOfficeProcesses(proccesName, _logger, LogCategories);
                return(RetryingPolicyAction(func, proccesName, _logger, LogCategories, ++step));
            }
            catch (Exception ex)
            {
                _logger.WriteError(new LogMessage(string.Concat($"RetryingPolicyAction: exception type not manageable.", ex)), LogCategories);
                throw ex;
            }
        }
        internal async Task <SemVersion> GetDeployedRuntimeVersion(InstanceName instance, IAzure azure, CancellationToken cancellationToken)
        {
            logger.WriteVerbose($"Retrieving functions runtime from {instance.PlainName} app");
            SemVersion uploadedRuntimeVer;
            var        kudu = new KuduApi(instance, azure, logger);

            using (var client = new HttpClient())
                using (var request = await kudu.GetRequestAsync(HttpMethod.Get, $"api/vfs/site/wwwroot/aggregator-manifest.ini", cancellationToken))
                    using (var response = await client.SendAsync(request, cancellationToken))
                    {
                        string manifest = await response.Content.ReadAsStringAsync();

                        if (response.IsSuccessStatusCode)
                        {
                            uploadedRuntimeVer = ManifestParser.Parse(manifest).Version;
                        }
                        else
                        {
                            logger.WriteWarning($"Cannot read aggregator-manifest.ini: {response.ReasonPhrase} (disregard this message on new instances)");
                            uploadedRuntimeVer = new SemVersion(0, 0, 0);
                        }
                    }

            logger.WriteVerbose($"Function Runtime version is {uploadedRuntimeVer}.");
            return(uploadedRuntimeVer);
        }
        public bool ValidateTransaction(Transaction transaction, ILogger logger)
        {
            if (portfolioRepository.GetPortfolioByClientID(transaction.SellerID).AmountOfShares < transaction.AmountOfShares)
            {
                logger.WriteWarning($"{transaction.SellerID} has not enough shares to make this transaction.");
                return(false);
            }

            if (clientRepository.GetClientBalance(transaction.BuyerID) <= 0)
            {
                logger.WriteWarning($"{transaction.BuyerID} has no money and impossible to trade with.");
                return(false);
            }

            return(true);
        }
        public bool ValidateClientRegistrationData(ClientRegistrationData clientData, ILogger logger)
        {
            if (!clientData.ClientName.Replace(" ", "").All(char.IsLetter))
            {
                logger.WriteWarning("Client's name and last name must contain only letters.");
                return(false);
            }

            if (!clientData.ClientPhone.All(char.IsDigit))
            {
                logger.WriteWarning("Client's phone number must contain only digits.");
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <returns></returns>
        public async Task Invoke(IDictionary <string, object> environment)
        {
            var context = new OwinContext(environment);

            var token = GetToken(context);

            if (token == null)
            {
                await _next(environment);

                return;
            }

            context.Set("oidchelper:tokenvalidation:token", token);

            // seems to be a JWT
            if (token.Contains('.'))
            {
                // see if local validation is setup
                if (_localValidationFunc != null)
                {
                    await _localValidationFunc.Value(environment);

                    return;
                }

                _logger.WriteWarning("No validator configured for JWT token");
            }

            await _next(environment);
        }
        /// <summary>
        /// Returns a list of all the persistent migration script file paths sorted by name.
        /// </summary>
        public IEnumerable<string> GetScripts(ILogger logger)
        {
            IEnumerable<string> scriptPaths = GetPaths();
            IEnumerable<string> scripts = Enumerable.Empty<string>();

            foreach (var path in scriptPaths)
            {
                if (Directory.Exists(path))
                {
                    scripts = scripts.Union(Directory.GetFiles(path, ScriptFileNamePattern));
                }
                else
                {
                    logger.WriteWarning("WARNING: Persistent migration script directory does not exist.{1}Check the config settings or create the directory. [Path: {0}]", path, Environment.NewLine);
                }
            }

            if (scriptPaths.Count() == 0)
            {
                logger.WriteWarning("WARNING: No persistent migration script paths are defined.{1}Add a '{0}' appSetting with a semicolon delimited list of paths to use.", PerptualMigrationFoldersAppSetting, Environment.NewLine);
            }

            return scripts;
        }
        /// <summary>
        /// Returns the seed script path from the
        /// config file (if available) or the default path.
        /// </summary>
        public string GetPath(ILogger log)
        {
            string path = _configurationManager.AppSettings[AppSettingKeys.SeedFolder];

            if (string.IsNullOrEmpty(path))
            {
                if (log != null)
                {
                    log.WriteWarning(
                        "The " + AppSettingKeys.SeedFolder + " setting was not present in the configuration file so the default " +
                        DefaultSeedScriptPath + " folder will be used instead.");
                }
                path = DefaultSeedScriptPath;
            }

            VerifyAndCreatePath(path);

            return path;
        }
        protected bool ValidateCorrelationId(AuthenticationExtra extra, ILogger logger)
        {
            var correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;

            string correlationCookie;
            if (!Request.GetCookies().TryGetValue(
                correlationKey,
                out correlationCookie))
            {
                logger.WriteWarning(string.Format("{0} cookie not found", correlationKey));
                return false;
            }

            Response.DeleteCookie(correlationKey);

            string correlationExtra;
            if (!extra.Properties.TryGetValue(
                correlationKey,
                out correlationExtra))
            {
                logger.WriteWarning(string.Format("{0} state property not found", correlationKey));
                return false;
            }

            extra.Properties.Remove(correlationKey);

            if (!string.Equals(correlationCookie, correlationExtra, StringComparison.Ordinal))
            {
                logger.WriteWarning(string.Format("{0} correlation cookie and state property mismatch", correlationKey));
                return false;
            }

            return true;
        }
        protected bool ValidateCorrelationId(AuthenticationProperties properties, ILogger logger)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;

            string correlationCookie = Request.Cookies[correlationKey];
            if (string.IsNullOrWhiteSpace(correlationCookie))
            {
                logger.WriteWarning("{0} cookie not found.", correlationKey);
                return false;
            }

            Response.Cookies.Delete(correlationKey);

            string correlationExtra;
            if (!properties.Dictionary.TryGetValue(
                correlationKey,
                out correlationExtra))
            {
                logger.WriteWarning("{0} state property not found.", correlationKey);
                return false;
            }

            properties.Dictionary.Remove(correlationKey);

            if (!string.Equals(correlationCookie, correlationExtra, StringComparison.Ordinal))
            {
                logger.WriteWarning("{0} correlation cookie and state property mismatch.", correlationKey);
                return false;
            }

            return true;
        }