Exemplo n.º 1
0
 public CloudError(Exception exception)
     : base(CloudItemType.Error)
 {
     this.exception     = exception;
     this.errorMessages = new List <string>();
     ErrorFormatter.FormatExceptionMessage(this.exception, this.errorMessages);
 }
 private System.Web.Compilation.BuildProvider GetBuildProviderFromLinePragmaInternal(string linePragma)
 {
     if (this._buildProviderToSourceFileMap != null)
     {
         string virtualPathFromHttpLinePragma = ErrorFormatter.GetVirtualPathFromHttpLinePragma(linePragma);
         foreach (System.Web.Compilation.BuildProvider provider in this.BuildProviders)
         {
             if (provider.VirtualPath != null)
             {
                 if (virtualPathFromHttpLinePragma != null)
                 {
                     if (System.Web.Util.StringUtil.EqualsIgnoreCase(virtualPathFromHttpLinePragma, provider.VirtualPath))
                     {
                         return(provider);
                     }
                 }
                 else
                 {
                     string str2 = HostingEnvironment.MapPathInternal(provider.VirtualPath);
                     if (System.Web.Util.StringUtil.EqualsIgnoreCase(linePragma, str2))
                     {
                         return(provider);
                     }
                 }
             }
         }
     }
     return(null);
 }
 private void AddChecksumPragma(System.Web.Compilation.BuildProvider buildProvider, CodeCompileUnit compileUnit)
 {
     if (((buildProvider != null) && (buildProvider.VirtualPath != null)) && this._compilerType.CompilerParameters.IncludeDebugInformation)
     {
         string path = HostingEnvironment.MapPathInternal(buildProvider.VirtualPath);
         if (File.Exists(path))
         {
             if (!s_hashMD5Guid.HasValue)
             {
                 s_hashMD5Guid = new Guid(0x406ea660, 0x64cf, 0x4c82, 0xb6, 240, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99);
             }
             CodeChecksumPragma pragma = new CodeChecksumPragma();
             if (this._compConfig.UrlLinePragmas)
             {
                 pragma.FileName = ErrorFormatter.MakeHttpLinePragma(buildProvider.VirtualPathObject.VirtualPathString);
             }
             else
             {
                 pragma.FileName = path;
             }
             pragma.ChecksumAlgorithmId = s_hashMD5Guid.Value;
             using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
             {
                 pragma.ChecksumData = this.ComputeHash(stream);
             }
             compileUnit.StartDirectives.Add(pragma);
         }
     }
 }
        internal static CodeLinePragma CreateCodeLinePragmaHelper(string virtualPath, int lineNumber)
        {
            string path = null;

            if (UrlPath.IsAbsolutePhysicalPath(virtualPath))
            {
                path = virtualPath;
            }
            else if (_urlLinePragmas)
            {
                path = ErrorFormatter.MakeHttpLinePragma(virtualPath);
            }
            else
            {
                try
                {
                    path = HostingEnvironment.MapPathInternal(virtualPath);
                    if (!File.Exists(path))
                    {
                        path = ErrorFormatter.MakeHttpLinePragma(virtualPath);
                    }
                }
                catch
                {
                    path = ErrorFormatter.MakeHttpLinePragma(virtualPath);
                }
            }
            return(new CodeLinePragma(path, lineNumber));
        }
Exemplo n.º 5
0
        private void OnLeave(object source, EventArgs eventArgs)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;

            if ((_fAuthChecked && _fAuthRequired) && (((context.User != null) && (context.User.Identity != null)) && (context.User.Identity is PassportIdentity)))
            {
                PassportIdentity identity = (PassportIdentity)context.User.Identity;
                if ((context.Response.StatusCode == 0x191) && !identity.WWWAuthHeaderSet)
                {
                    if (((_LoginUrl == null) || (_LoginUrl.Length < 1)) || (string.Compare(_LoginUrl, "internal", StringComparison.Ordinal) == 0))
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = 200;
                        if (!ErrorFormatter.RequiresAdaptiveErrorReporting(context))
                        {
                            string str   = context.Request.Url.ToString();
                            int    index = str.IndexOf('?');
                            if (index >= 0)
                            {
                                str = str.Substring(0, index);
                            }
                            string str2 = identity.LogoTag2(HttpUtility.UrlEncode(str, context.Request.ContentEncoding));
                            string s    = System.Web.SR.GetString("PassportAuthFailed", new object[] { str2 });
                            context.Response.Write(s);
                        }
                        else
                        {
                            ErrorFormatter formatter = new PassportAuthFailedErrorFormatter();
                            context.Response.Write(formatter.GetAdaptiveErrorMessage(context, true));
                        }
                    }
                    else
                    {
                        string str7;
                        string completeLoginUrl = AuthenticationConfig.GetCompleteLoginUrl(context, _LoginUrl);
                        if ((completeLoginUrl == null) || (completeLoginUrl.Length <= 0))
                        {
                            throw new HttpException(System.Web.SR.GetString("Invalid_Passport_Redirect_URL"));
                        }
                        string str5 = context.Request.Url.ToString();
                        if (completeLoginUrl.IndexOf('?') >= 0)
                        {
                            str7 = "&";
                        }
                        else
                        {
                            str7 = "?";
                        }
                        string url  = completeLoginUrl + str7 + "ReturnUrl=" + HttpUtility.UrlEncode(str5, context.Request.ContentEncoding);
                        int    num2 = str5.IndexOf('?');
                        if ((num2 >= 0) && (num2 < (str5.Length - 1)))
                        {
                            url = url + "&" + str5.Substring(num2 + 1);
                        }
                        context.Response.Redirect(url, false);
                    }
                }
            }
        }
        public IActionResult CreateUser([FromBody] User user)
        {
            UserValidator validator = new UserValidator();
            var           results   = validator.Validate(user);

            var errors = results.ToString("\n");

            if (errors != string.Empty)
            {
                var errorList = ErrorFormatter.FormatValidationErrors(errors);
                return(BadRequest(new { Errors = errorList }));
            }

            if (_repository.GetUser(user.EmailAddress) != null)
            {
                return(BadRequest("Email address already exists. Please sign in"));
            }

            try
            {
                User newUser       = _repository.CreateUser(user);
                var  mappedNewUser = _userMappings.StripSensitiveDataSingleUser(newUser);
                return(CreatedAtRoute("User At Id", new { userId = mappedNewUser.Id }, mappedNewUser));
            } catch (Exception e)
            {
                _logger.LogError($"Something went wrong while trying to create user. ${e}");
            }

            return(StatusCode(500, "Unable to create new user. Try again later"));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Renders the error response.
        /// </summary>
        public Task RenderErrorResponse(HttpContext context, Exception error)
        {
            context.Response.ContentType = "text/html";

            try
            {
                var text = (Formatter ?? (Formatter = ErrorFormatter.CreateDefault()))
                           .ErrorHtml(error, DotvvmMiddleware.ConvertHttpContext(context));
                return(context.Response.WriteAsync(text));
            }
            catch (Exception exc)
            {
                context.Response.ContentType = "text/plain";
                try
                {
                    using (var writer = new StreamWriter(context.Response.Body))
                    {
                        writer.WriteLine("Error in Dotvvm Application:");
                        writer.WriteLine(error.ToString());
                        writer.WriteLine();
                        writer.WriteLine("Error occured while displaying the error page. This it s internal error and should not happend, please report it:");
                        writer.WriteLine(exc.ToString());
                    }
                }
                catch { }
                throw new Exception("Error occured inside dotvvm error handler, this is internal error and should not happen; \n Original error:" + error.ToString(), exc);
            }
        }
Exemplo n.º 8
0
        private void GetOutput(ref string aText, string aSearchedSubstring)
        {
            var errorFormatter = new ErrorFormatter();

            aText = errorFormatter.Format(aText, aSearchedSubstring);
            aText = aText.SubstringAfter(aSearchedSubstring);
        }
Exemplo n.º 9
0
 public static string FormatError(FsUtils.SemanticError ex)
 {
     if (ex.Data0.Equals(FsUtils.emptyLocation))
     {
         return("error: " + ex.Data1);
     }
     return(ErrorFormatter.FormatError(ex.Data0.srcFilename, ex.Data0.srcLine, ex.Data0.charPos, ex.Data1));
 }
Exemplo n.º 10
0
        public async Task Serialize_error_with_only_id()
        {
            var error = new Mock <IError>();

            error.Setup(e => e.Id).Returns("123456");

            var formatter = new ErrorFormatter(null, null);

            await AssertSerializeOutput(formatter, error.Object, "Json/Fixtures/ErrorFormatter/Serialize_error_with_only_id.json");
        }
Exemplo n.º 11
0
        private ErrorFormatter CreateDefaultWithDemystifier()
        {
            var errorFormatter = ErrorFormatter.CreateDefault();

            var insertPosition = errorFormatter.Formatters.Count > 0 ? 1 : 0;

            errorFormatter.Formatters.Insert(insertPosition, (e, o) =>
                                             new ExceptionSectionFormatter(LoadDemystifiedException(errorFormatter, e)));

            return(errorFormatter);
        }
Exemplo n.º 12
0
        public static void DumpException(AphidLoadScriptException exception, AphidInterpreter interpreter)
        {
            WriteErrorMessage(
                StyleEscape(
                    ErrorFormatter.Format(
                        exception,
                        AphidScript.Read(exception.ScriptFile))));

            DumpStackTrace(interpreter, exception);
            DumpScope(exception, interpreter);
        }
Exemplo n.º 13
0
        public static void DumpException(Exception exception, AphidInterpreter interpreter)
        {
            WriteErrorMessage(StyleEscape(ErrorFormatter.Format(exception)));

            if (interpreter != null)
            {
                DumpStackTrace(interpreter, exception);
            }

            DumpScope(exception, interpreter);
        }
Exemplo n.º 14
0
        public void Handle(AppUser user, IEnumerable <IdentityError> errors, string exceptionMessage)
        {
            var identityErrors = errors as IdentityError[] ?? errors.ToArray();

            foreach (var error in identityErrors)
            {
                var errorMessage = ErrorFormatter.FormatIdentityError(error);
                _eventBus.Publish(new ErrorLogEvent(user.Id, errorMessage));
            }

            throw new RestException(HttpStatusCode.InternalServerError, identityErrors);
        }
Exemplo n.º 15
0
        private string GetOutput(ref string aText, string aSearchedSubstring)
        {
            var errorFormatter = new ErrorFormatter();

            aText = errorFormatter.Format(aText, aSearchedSubstring);

            var substringBefore = aText.SubstringBefore(aSearchedSubstring);
            var substringAfter  = aText.SubstringAfter(aSearchedSubstring);

            aText = substringAfter;
            return(substringBefore + aSearchedSubstring);
        }
Exemplo n.º 16
0
        public override void Evaluate(Response response, dynamic arguments)
        {
            var expStr = (string)DynamicHelper.GetString(arguments, "expression");
            var exp    = AphidParser.ParseExpression(expStr);

            var retExp =
                exp.Type != AphidExpressionType.UnaryOperatorExpression ||
                ((UnaryOperatorExpression)exp).Operator != AphidTokenType.retKeyword ?
                new UnaryOperatorExpression(
                    AphidTokenType.retKeyword,
                    exp,
                    isPostfix: false)
                .WithPositionFrom(exp) :
                exp;

            AphidObject value = null;

            try
            {
                value = Interpreter.CreateChild(createChildScope: false).Interpret(exp);
            }
            catch (Exception e)
            {
                SendErrorResponse(response, 3014, ErrorFormatter.FormatByType(e, expStr));
            }

            if (value == null)
            {
                return;
            }

            var v = _explorer.CreateVariable(new KeyValuePair <string, AphidObject>(expStr, value));

            SendResponse(response, new EvaluateResponseBody(v.value, v.variablesReference));


            //var value = (AphidObject)new AphidInterpreter(Interpreter.CurrentScope).Interpret(exp);

            //if (false)
            //{
            //    SendErrorResponse(response, 3014, "Evaluate request failed, invalid expression");
            //}
            //else
            //{
            //    var handle = _variableHandles.Create(value.ToArray());
            //    SendResponse(
            //        response,
            //        new EvaluateResponseBody(
            //            new AphidSerializer(Interpreter).Serialize(value),
            //            handle));
            //}
        }
Exemplo n.º 17
0
        public void Slice_FromIndexedExtensions_ReturnsCorrectValues()
        {
            this.RunSliceTestCases((from, to, step, length) =>
            {
                var source   = Enumerable.Range(0, length).ToArray();
                var sut      = IndexedExtensions.Slice(source, from, to, step).ToArray();
                var expected = SliceExpectedResultCalculator.Calculate(from, to, step, length);

                Assert.True(
                    expected.SequenceEqual(sut),
                    ErrorFormatter.Format(sliceResultErrorFormat, source, from, to, step, expected, sut));
            });
        }
Exemplo n.º 18
0
        public void Slice_FromEnumerableExtensions_GivenCollectionAsSource_ReturnsCorrectValues()
        {
            this.RunSliceTestCases((from, to, step, length) =>
            {
                var source   = new Queue <int>(Enumerable.Range(0, length));
                var sut      = EnumerableExtensions.SliceDelete(source, from, to, step).ToArray();
                var expected = SliceDeleteExpectedResultCalculator.Calculate(from, to, step, length);

                LazyAssert.True(
                    expected.SequenceEqual(sut),
                    () => ErrorFormatter.Format(sliceDeleteResultErrorFormat, source, from, to, step, expected, sut));
            });
        }
Exemplo n.º 19
0
        public void GivenErrorFormatter_WhenReceivesCollectionOfIdentityErrors_ThenShouldReturnFormattedString()
        {
            var error = new IdentityError
            {
                Code        = "1",
                Description = "First ErrorCode"
            };

            var          formattedString = ErrorFormatter.FormatIdentityError(error);
            const string expectedString  = "ErrorCode ErrorCode: 1, ErrorCode Message: First ErrorCode.";

            Assert.Equal(formattedString, expectedString);
        }
Exemplo n.º 20
0
        public async Task Serialize_error_with_all_possible_members()
        {
            var mockAboutLink = new Mock <ILink>(MockBehavior.Strict);

            mockAboutLink.Setup(l => l.Href).Returns("http://example.com/my-about-link");

            var mockMetadata = new Mock <IMetadata>(MockBehavior.Strict);

            mockMetadata.Setup(m => m.MetaObject).Returns(() =>
            {
                var obj    = new JObject();
                obj["foo"] = "qux";
                return(obj);
            });

            var error = new Mock <IError>(MockBehavior.Strict);

            error.Setup(e => e.Id).Returns("654321");
            error.Setup(e => e.AboutLink).Returns(mockAboutLink.Object);
            error.Setup(e => e.Status).Returns(HttpStatusCode.BadRequest);
            error.Setup(e => e.Code).Returns("9000");
            error.Setup(e => e.Title).Returns("Some error occurred.");
            error.Setup(e => e.Detail).Returns("The thingamabob fell through the whatsit.");
            error.Setup(e => e.Pointer).Returns("/data/attributes/bob");
            error.Setup(e => e.Parameter).Returns("sort");
            error.Setup(e => e.Metadata).Returns(mockMetadata.Object);

            var mockLinkFormatter = new Mock <ILinkFormatter>(MockBehavior.Strict);

            mockLinkFormatter.Setup(s => s.Serialize(mockAboutLink.Object, It.IsAny <JsonWriter>()))
            .Returns((ILink link, JsonWriter writer) =>
            {
                writer.WriteValue(link.Href);
                return(Task.FromResult(0));
            });

            var mockMetadataFormatter = new Mock <IMetadataFormatter>(MockBehavior.Strict);

            mockMetadataFormatter.Setup(s => s.Serialize(mockMetadata.Object, It.IsAny <JsonWriter>()))
            .Returns((IMetadata metadata, JsonWriter writer) =>
            {
                metadata.MetaObject.WriteTo(writer);
                return(Task.FromResult(0));
            });

            var formatter = new ErrorFormatter(mockLinkFormatter.Object, mockMetadataFormatter.Object);

            await AssertSerializeOutput(formatter, error.Object, "Json/Fixtures/ErrorFormatter/Serialize_error_with_all_possible_members.json");
        }
Exemplo n.º 21
0
        /// <summary>
        /// Renders the error response.
        /// </summary>
        public Task RenderErrorResponse(IOwinContext context, Exception error)
        {
            context.Response.ContentType = "text/html";

            try
            {
                var text = (Formatter ?? (Formatter = ErrorFormatter.CreateDefault()))
                           .ErrorHtml(error, DotvvmMiddleware.ConvertHttpContext(context));
                return(context.Response.WriteAsync(text));
            }
            catch (Exception exc)
            {
                throw new Exception("Error occured inside dotvvm error handler, this is internal error and should not happen; \n Original error:" + error.ToString(), exc);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Renders the error response.
        /// </summary>
        public Task RenderErrorResponse(HttpContext context, Exception error)
        {
            try
            {
                context.Response.ContentType = "text/html";

                var text = (Formatter ?? (Formatter = CreateDefaultWithDemystifier()))
                           .ErrorHtml(error, DotvvmMiddleware.ConvertHttpContext(context));
                return(context.Response.WriteAsync(text));
            }
            catch (Exception exc)
            {
                return(RenderFallbackMessage(context, error, exc));
            }
        }
Exemplo n.º 23
0
        private async void BtnFinish_Click(object sender, RoutedEventArgs e)
        {
            this.InfoSpinner.Visibility = System.Windows.Visibility.Visible;
            this.InfoMessage.Text       = "Checking cloud connectivity...";
            var targetUrl = this.tbUrl.Text;

            var errorResource = this.DataContext as ErrorResource;

            if (errorResource == null)
            {
                throw new InvalidOperationException("Invalid DataContext");
            }

            try
            {
                var client = new CloudFoundryClient(new Uri(targetUrl), new CancellationToken(), null, (bool)cbIgnoreSSK.IsChecked);

                CloudCredentials creds = new CloudCredentials();
                creds.User     = this.tbUsername.Text;
                creds.Password = this.pbPassword.Password;

                var authContext = await client.Login(creds);

                var info = await client.Info.GetInfo();

                this.version = info.ApiVersion;

                this.cloudTarget = CloudTarget.CreateV2Target(
                    new Uri(this.tbUrl.Text),
                    this.tbDescription.Text,
                    this.tbUsername.Text,
                    (bool)this.cbIgnoreSSK.IsChecked,
                    this.version);

                this.credentials  = creds;
                this.DialogResult = true;
                this.Close();
            }
            catch (Exception ex)
            {
                this.InfoSpinner.Visibility = System.Windows.Visibility.Hidden;
                this.InfoMessage.Text       = string.Empty;
                var errorMessages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(ex, errorMessages);
                errorResource.ErrorMessage = string.Join(Environment.NewLine, errorMessages.ToArray());
                errorResource.HasErrors    = true;
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Renders the error response.
        /// </summary>
        public Task RenderErrorResponse(IOwinContext context, Exception error)
        {
            context.Response.ContentType = "text/html";

            try
            {

                var text = (Formatter ?? (Formatter = ErrorFormatter.CreateDefault()))
                    .ErrorHtml(error, context);
                return context.Response.WriteAsync(text);
            }
            catch (Exception exc)
            {
                throw new Exception("Error occured inside dotvvm error handler, this is internal error and should not happen; \n Original error:" + error.ToString(), exc);
            }
        }
Exemplo n.º 25
0
        public void SliceDelete_FromEnumerableExtensions_CallsDisposeOnce()
        {
            this.RunSliceTestCases((from, to, step, length) =>
            {
                var sut = new EnumerableMock <int>(Enumerable.Range(0, length));
                EnumerableExtensions.SliceDelete(sut, from, to, step).Sum();

                if (sut.Enumerators.Count > 0)
                {
                    var disposeCallCount = sut.Enumerators.Single().DisposeCallCount;

                    LazyAssert.True(
                        disposeCallCount == 1,
                        () => ErrorFormatter.Format(sliceDeleteDisposeOnceErrorFormat, from, to, step, length, disposeCallCount));
                }
            });
        }
Exemplo n.º 26
0
        public void SliceDelete_FromEnumerableExtensions_DoesNotCallReset()
        {
            this.RunSliceTestCases((from, to, step, length) =>
            {
                var sut = new EnumerableMock <int>(Enumerable.Range(0, length));
                EnumerableExtensions.SliceDelete(sut, from, to, step).Sum();

                if (sut.Enumerators.Count > 0)
                {
                    var resetCallCount = sut.Enumerators.Single().ResetCallCount;

                    LazyAssert.True(
                        resetCallCount == 0,
                        () => ErrorFormatter.Format(sliceDeleteDoesntCallResetErrorFormat, from, to, step, length, resetCallCount));
                }
            });
        }
Exemplo n.º 27
0
        private void ExitRefresh(Exception error)
        {
            this.RefreshCounter--;
            this.Error.HasErrors = error != null;
            if (this.Error.HasErrors)
            {
                List <string> errors = new List <string>();
                ErrorFormatter.FormatExceptionMessage(error, errors);
                StringBuilder sb = new StringBuilder();
                foreach (string errorLine in errors)
                {
                    sb.AppendLine(errorLine);
                }

                this.Error.ErrorMessage = sb.ToString();
            }
        }
Exemplo n.º 28
0
        internal static CodeLinePragma CreateCodeLinePragmaHelper(string virtualPath, int lineNumber)
        {
            string pragmaFile = null;

            if (UrlPath.IsAbsolutePhysicalPath(virtualPath))
            {
                // Due to config system limitations, we can end up with virtualPath
                // actually being a physical path.  If that's the case, just use it as is.
                //

                pragmaFile = virtualPath;
            }
            else
            {
                if (_urlLinePragmas)
                {
                    // If specified in config, generate URL's for the line pragmas
                    // instead of physical path.  This is used for VS debugging.
                    // We don't know the server name, so we just used a fixed one.  This should be
                    // fine, as VS will ignore the server name.

                    pragmaFile = ErrorFormatter.MakeHttpLinePragma(virtualPath);
                }
                else
                {
                    try {
                        // Try using the physical path for the line pragma
                        pragmaFile = HostingEnvironment.MapPathInternal(virtualPath);

                        // If the physical path doesn't exist, use the URL instead.
                        // This can happen when using a VirtualPathProvider (VSWhidbey 272259)
                        if (!File.Exists(pragmaFile))
                        {
                            pragmaFile = ErrorFormatter.MakeHttpLinePragma(virtualPath);
                        }
                    }
                    catch {
                        // If MapPath failed, use the URL instead
                        pragmaFile = ErrorFormatter.MakeHttpLinePragma(virtualPath);
                    }
                }
            }

            return(new CodeLinePragma(pragmaFile, lineNumber));
        }
Exemplo n.º 29
0
        public void SliceDelete_FromEnumerableExtensions_DoesntHandleExceptions()
        {
            this.RunSliceTestCases((from, to, step, length) =>
            {
                bool expected  = false;
                var collection = new EnumerableMock <int>(Enumerable.Range(0, length));
                collection.EnumeratorCreated += e => { e.Current = () => { expected = true; throw new InvalidOperationException(); }; };
                bool sut = false;
                try
                {
                    EnumerableExtensions.SliceDelete(collection, from, to, step).Sum();
                }
                catch (InvalidOperationException)
                {
                    sut = true;
                }

                LazyAssert.True(sut == expected, () => ErrorFormatter.Format(sliceDeleteExceptionsAreNotHandledErrorFormat, from, to, step, length));
            });
        }
Exemplo n.º 30
0
 private ExceptionModel LoadDemystifiedException(ErrorFormatter formatter, Exception exception)
 {
     return(formatter.LoadException(exception,
                                    stackFrameGetter: ex => {
         var rawStackTrace = new StackTrace(ex, true).GetFrames();
         if (rawStackTrace == null)
         {
             return null;                            // demystifier throws in these cases
         }
         try
         {
             return new EnhancedStackTrace(ex).GetFrames();
         }
         catch
         {
             return rawStackTrace;
         }
     },
                                    methodFormatter: f => (f as EnhancedStackFrame)?.MethodInfo?.ToString()));
 }
        public IActionResult SignInWithToken([FromBody] UserCredentials userCreds)
        {
            UserCredentialsValidator validator = new UserCredentialsValidator();
            var results = validator.Validate(userCreds);

            var errors = results.ToString("\n");

            if (errors != string.Empty)
            {
                var errorList = ErrorFormatter.FormatValidationErrors(errors);
                return(BadRequest(new { Errors = errorList }));
            }

            try
            {
                // By default we return only if the user has curretn tenant in active tenants.
                // If the user is not active in current tenant, we will return not found
                User user = _repository.GetUser(userCreds.EmailAddress);
                if (user == null)
                {
                    return(NotFound("User not found or has not access"));
                }


                bool isValidUser = _repository.ValidatePassword(userCreds, user);
                if (!isValidUser)
                {
                    return(Unauthorized());
                }

                var token = _tokenManager.GenerateNewToken(user);

                return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }));
            } catch (Exception e)
            {
                _logger.LogError($"Could not create JWT. Error: ${e}");
            }

            return(BadRequest("Failed to signin. Coud not generate token"));
        }