public static void LogUserInformation(ILogger logger, IUserInformationProvider userInformationProvider)
        {
            if (userInformationProvider == null)
            {
                throw new ArgumentNullException(nameof(userInformationProvider));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (userInformationProvider.IsAuthenticated())
            {
                BitJwtToken bitJwtToken = userInformationProvider.GetBitJwtToken();
                logger.AddLogData("UserId", bitJwtToken.UserId);
                if (bitJwtToken.CustomProps != null)
                {
                    foreach (var keyVal in bitJwtToken.CustomProps)
                    {
                        logger.AddLogData(keyVal.Key, keyVal.Value);
                    }
                }
                logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
                logger.AddLogData("ClientId", userInformationProvider.GetClientId());
            }
        }
Exemple #2
0
 public virtual async Task OnConnected(MessagesHub hub)
 {
     if (_userInformationProvider.IsAuthenticated())
     {
         await hub.Groups.Add(hub.Context.ConnectionId, _userInformationProvider.GetCurrentUserId());
     }
 }
Exemple #3
0
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
            IOwinContext             owinContext             = new OwinContext(context.GetOwinEnvironment());
            IUserInformationProvider userInformationProvider = owinContext.GetDependencyResolver().Resolve <IUserInformationProvider>();
            bool isAuthenticated = userInformationProvider.IsAuthenticated();

            return(isAuthenticated);
        }
Exemple #4
0
 public static void LogUserInformation(ILogger logger, IUserInformationProvider userInformationProvider)
 {
     if (userInformationProvider.IsAuthenticated())
     {
         logger.AddLogData("UserId", userInformationProvider.GetCurrentUserId());
         logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
     }
 }
Exemple #5
0
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
#if DotNetCore
            throw new NotImplementedException();
#else
            IUserInformationProvider userInformationProvider = null;
            IOwinContext             owinContext             = new OwinContext(context.GetOwinEnvironment());
            userInformationProvider = owinContext.GetDependencyResolver().Resolve <IUserInformationProvider>();
            bool isAuthenticated = userInformationProvider.IsAuthenticated();
            return(isAuthenticated);
#endif
        }
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
            IUserInformationProvider userInformationProvider = null;

#if NET461
            IOwinContext owinContext = new OwinContext(context.GetOwinEnvironment());
            userInformationProvider = owinContext.GetDependencyResolver().Resolve <IUserInformationProvider>();
#else
            userInformationProvider = Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService <IUserInformationProvider>(context.GetHttpContext().RequestServices);
#endif
            bool isAuthenticated = userInformationProvider.IsAuthenticated();
            return(isAuthenticated);
        }
Exemple #7
0
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IServiceProvider         serviceProvider         = GetServiceProvider(context);
            IUserInformationProvider userInformationProvider = serviceProvider.GetRequiredService <IUserInformationProvider>();
            bool isAuthenticated = userInformationProvider.IsAuthenticated();

            return(isAuthenticated);
        }
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IUserInformationProvider userInformationProvider =
                dependencyResolver.Resolve <IUserInformationProvider>();

            if (userInformationProvider.IsAuthenticated())
            {
                logger.AddLogData("UserId", userInformationProvider.GetCurrentUserId());
                logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
            }

            await Next.Invoke(context);
        }
Exemple #9
0
        private void PerformLog(LogEntry logEntry)
        {
            RequestTelemetry requestTelemetry = null;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.DisplayUrl)) && HttpContextAccessor.HttpContext != null)
            {
                HttpContext httpContext = HttpContextAccessor.HttpContext;

                if (!httpContext.Items.ContainsKey(nameof(RequestTelemetry)))
                {
                    throw new InvalidOperationException($"Register app insight logger using dependencyManager.{nameof(IDependencyManagerExtensions.RegisterApplicationInsights)}();");
                }

                requestTelemetry = (RequestTelemetry)httpContext.Items[nameof(RequestTelemetry)];

                IUserInformationProvider userInformationProvider = httpContext.RequestServices.GetRequiredService <IUserInformationProvider>();

                if (userInformationProvider.IsAuthenticated())
                {
                    requestTelemetry.Context.User.AccountId = requestTelemetry.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId();
                }
            }

            List <KeyVal> keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.DisplayUrl) ||
                    k == nameof(IRequestInformationProvider.UserAgent) ||
                    k == "UserId" ||
                    k == "ResponseStatusCode" ||
                    k == nameof(IRequestInformationProvider.ClientIp) ||
                    ld.Value == null)
                {
                    return(null); // Already being logged by app insights!
                }
                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(new KeyVal {
                    Key = k, Value = v
                });
            })
                                      .Where(d => d != null)
                                      .ToList();

            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.MemoryUsage), Value = logEntry.MemoryUsage.ToString()
            });

            if (logEntry.AppServerDateTime.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString()
                });
            }

            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.Severity), Value = logEntry.Severity
            });
            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.Message), Value = logEntry.Message
            });

            if (logEntry.Id.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString()
                });
            }

            if (logEntry.AppServerThreadId.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString()
                });
            }

            if (requestTelemetry != null)
            {
                LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));
                if (userAgent != null)
                {
                    requestTelemetry.Context.User.UserAgent = (string)userAgent.Value;
                }

                foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                {
                    if (!requestTelemetry.Properties.ContainsKey(keyVal.Key))
                    {
                        requestTelemetry.Properties.Add(keyVal.Key, keyVal.Value);
                    }
                }
            }
            else
            {
                TelemetryClient telemetryClient = new TelemetryClient();

                Dictionary <string, string> customData = new Dictionary <string, string>();

                foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                {
                    if (!customData.ContainsKey(keyVal.Key))
                    {
                        customData.Add(keyVal.Key, keyVal.Value);
                    }
                }

                Exception ex = null;

                try
                {
                    customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName);

                    if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName))
                    {
                        ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName) ?? throw new InvalidOperationException($"{exceptionTypeAssemblyQualifiedName} could not be found"), args: new object[] { logEntry.Message });
                    }
                }
                catch { }

                if (ex == null)
                {
                    switch (logEntry.Severity)
                    {
                    case "Information":
                        ex = new InformationException(logEntry.Message);
                        break;

                    case "Warning":
                        ex = new WarningException(logEntry.Message);
                        break;

                    case "Error":
                        ex = new ErrorException(logEntry.Message);
                        break;

                    case "Fatal":
                        ex = new FatalException(logEntry.Message);
                        break;

                    default:
                        ex = new Exception(logEntry.Message);
                        break;
                    }
                }

                telemetryClient.TrackException(ex, customData);
            }
        }
        private void PerformLog(LogEntry logEntry)
        {
            TelemetryClient          telemetryClient         = null;
            IUserInformationProvider userInformationProvider = null;
            bool isPerRequestTelemetryClient = false;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.RequestUri)))
            {
                IOwinContext owinContext = OwinContext.Value;

                IDependencyResolver resolver = owinContext.GetDependencyResolver();

                telemetryClient = resolver.Resolve <TelemetryClient>();

                userInformationProvider = resolver.Resolve <IUserInformationProvider>();

                isPerRequestTelemetryClient = true;
            }

            List <KeyVal> keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.RequestUri) ||
                    k == nameof(IRequestInformationProvider.UserAgent) ||
                    k == "UserId" ||
                    k == "ResponseStatusCode" ||
                    k == nameof(IRequestInformationProvider.ClientIp) ||
                    ld.Value == null)
                {
                    return(null);
                }

                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(new KeyVal {
                    Key = k, Value = v
                });
            })
                                      .Where(d => d != null)
                                      .ToList();

            try
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppEnvironmentName), Value = logEntry.AppEnvironmentName
                });

                if (logEntry.AppServerProcessId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerProcessId), Value = logEntry.AppServerProcessId.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerAppDomainName), Value = logEntry.AppServerAppDomainName
                });

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerOSVersion), Value = logEntry.AppServerOSVersion
                });

                if (logEntry.AppServerDateTime.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerName), Value = logEntry.AppServerName
                });

                if (logEntry.AppWasInDebugMode.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppWasInDebugMode), Value = logEntry.AppWasInDebugMode.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerUserAccountName), Value = logEntry.AppServerUserAccountName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppVersion), Value = logEntry.AppVersion
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.ApplicationName), Value = logEntry.ApplicationName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Severity), Value = logEntry.Severity
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Message), Value = logEntry.Message
                });

                if (logEntry.Id.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString()
                    });
                }

                if (logEntry.AppServerThreadId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString()
                    });
                }

                if (isPerRequestTelemetryClient == true)
                {
                    if (userInformationProvider.IsAuthenticated())
                    {
                        telemetryClient.Context.User.AccountId = telemetryClient.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId();
                    }

                    LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));
                    if (userAgent != null)
                    {
                        telemetryClient.Context.User.UserAgent = (string)userAgent.Value;
                    }

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!telemetryClient.Context.Properties.ContainsKey(keyVal.Key))
                        {
                            telemetryClient.Context.Properties.Add(keyVal.Key, keyVal.Value);
                        }
                    }
                }
                else
                {
                    telemetryClient = new TelemetryClient();

                    Dictionary <string, string> customData = new Dictionary <string, string>();

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!customData.ContainsKey(keyVal.Key))
                        {
                            customData.Add(keyVal.Key, keyVal.Value);
                        }
                    }

                    Exception ex = null;

                    try
                    {
                        customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName);

                        if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName))
                        {
                            ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName) ?? throw new InvalidOperationException($"{exceptionTypeAssemblyQualifiedName} could not be found"), args: new object[] { logEntry.Message });
                        }
                    }
                    catch { }

                    if (ex == null)
                    {
                        switch (logEntry.Severity)
                        {
                        case "Information":
                            ex = new InformationException(logEntry.Message);
                            break;

                        case "Warning":
                            ex = new WarningException(logEntry.Message);
                            break;

                        case "Error":
                            ex = new ErrorException(logEntry.Message);
                            break;

                        case "Fatal":
                            ex = new FatalException(logEntry.Message);
                            break;

                        default:
                            ex = new Exception(logEntry.Message);
                            break;
                        }
                    }

                    telemetryClient.TrackException(ex, customData);
                }
            }
            finally
            {
                telemetryClient.Flush();
            }
        }
Exemple #11
0
        public virtual void Initialize(ITelemetry telemetry)
        {
            if (telemetry == null)
            {
                throw new ArgumentNullException(nameof(telemetry));
            }

            LogEntryAppLevelConstantInfo logEntryAppLevelConstantInfo = LogEntryAppLevelConstantInfo.GetAppConstantInfo();

            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.ApplicationName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.ApplicationName), logEntryAppLevelConstantInfo.ApplicationName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppVersion)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppVersion), logEntryAppLevelConstantInfo.AppVersion);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppEnvironmentName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppEnvironmentName), logEntryAppLevelConstantInfo.AppEnvironmentName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppWasInDebugMode)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppWasInDebugMode), logEntryAppLevelConstantInfo.AppWasInDebugMode.ToString());
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerName), logEntryAppLevelConstantInfo.AppServerName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerOSVersion)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerOSVersion), logEntryAppLevelConstantInfo.AppServerOSVersion);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerAppDomainName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerAppDomainName), logEntryAppLevelConstantInfo.AppServerAppDomainName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerProcessId)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerProcessId), logEntryAppLevelConstantInfo.AppServerProcessId.ToString());
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerUserAccountName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerUserAccountName), logEntryAppLevelConstantInfo.AppServerUserAccountName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerWas64Bit)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerWas64Bit), logEntryAppLevelConstantInfo.AppServerWas64Bit.ToString(CultureInfo.InvariantCulture));
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppWas64Bit)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppWas64Bit), logEntryAppLevelConstantInfo.AppWas64Bit.ToString(CultureInfo.InvariantCulture));
            }

            if (telemetry is RequestTelemetry requestTelemetry && HttpContextAccessor.HttpContext != null)
            {
                List <AppInsightsLogKeyVal> logKeyValues;

                if (HttpContextAccessor.HttpContext.Items.TryGetValue("LogKeyValues", out object?logKeyValuesAsObj))
                {
                    logKeyValues = (List <AppInsightsLogKeyVal>)logKeyValuesAsObj;
                }
                else // in ok responses, we've no LogKeyValues because ApplicationInsightsLogStore won't gets called.
                {
                    using IDependencyResolver childResolver = DependencyManager.CreateChildDependencyResolver(); // HttpContextAccessor.HttpContext.RequestServices is null because scope is gets disposed at this time.

                    IRequestInformationProvider requestInformationProvider = childResolver.Resolve <IRequestInformationProvider>();
                    IUserInformationProvider    userInformationProvider    = childResolver.Resolve <IUserInformationProvider>();

                    logKeyValues = new List <AppInsightsLogKeyVal> {
                    };

                    if (userInformationProvider.IsAuthenticated())
                    {
                        logKeyValues.Add(new AppInsightsLogKeyVal {
                            Key = "UserId", Value = userInformationProvider.GetCurrentUserId()
                        });
                    }

                    logKeyValues.Add(new AppInsightsLogKeyVal {
                        Key = nameof(IRequestInformationProvider.UserAgent), Value = requestInformationProvider.UserAgent
                    });

                    logKeyValues.Add(new AppInsightsLogKeyVal {
                        Key = "X-Correlation-ID", Value = requestInformationProvider.XCorrelationId
                    });
                }

                AppInsightsLogKeyVal userAgent = logKeyValues.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));

                if (userAgent != null)
                {
                    requestTelemetry.Context.User.UserAgent = userAgent.Value;
                }

                AppInsightsLogKeyVal userId = logKeyValues.FirstOrDefault(ld => ld.Key == "UserId");

                if (userId != null)
                {
                    requestTelemetry.Context.User.AccountId = requestTelemetry.Context.User.Id = requestTelemetry.Context.User.AuthenticatedUserId = requestTelemetry.Context.User.AuthenticatedUserId = userId.Value;
                }

                foreach (AppInsightsLogKeyVal keyVal in logKeyValues.OrderBy(kv => kv.Key))
                {
                    if (keyVal.Key == nameof(IRequestInformationProvider.UserAgent) || keyVal.Key == "UserId")
                    {
                        continue;
                    }
                    if (!requestTelemetry.Properties.ContainsKey(keyVal.Key))
                    {
                        requestTelemetry.Properties.Add(keyVal.Key, keyVal.Value);
                    }
                }

                AppInsightsLogKeyVal xCorrelationId = logKeyValues.FirstOrDefault(ld => ld.Key == "X-Correlation-ID");

                if (xCorrelationId != null)
                {
                    requestTelemetry.Id = xCorrelationId.Value;
                }
            }
        }