public override void OnException(ExceptionContext context)
        {
            if (context.Exception is HttpException hex)
            {
                CustomLogger.Warning(hex.Message, hex);
                context.Result = new ViewResult {
                    ViewName = "CustomError",
                    ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState)
                    {
                        Model = new ErrorViewModel(hex.StatusCode) // set the model
                    }
                };

                context.ExceptionHandled = true;
            }
            else if (context.Exception is CustomErrorPageException customErrorPageException)
            {
                context.Result = new ViewResult
                {
                    StatusCode = customErrorPageException.StatusCode,
                    ViewName   = customErrorPageException.ViewName,
                    ViewData   = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState)
                    {
                        // For this type of custom error page, we use the exception itself as the model
                        Model = customErrorPageException
                    }
                };
            }
            else if (context.Exception is CustomRedirectException customRedirectException)
            {
                context.Result = new RedirectResult(customRedirectException.RedirectUrl, permanent: false);
            }
        }
Example #2
0
        public override Task ExecuteResultAsync(ActionContext actionContext)
        {
            string message;

            if (Enum.IsDefined(typeof(HttpStatusCode), StatusCode.Value))
            {
                message = $"{(HttpStatusCode) StatusCode.Value} ({StatusCode.Value}):  {StatusDescription}";
            }
            else
            {
                message = $"HttpStatusCode ({StatusCode.Value}):  {StatusDescription}";
            }
            if (StatusCode == 404 || StatusCode == 405)
            {
                CustomLogger.Warning(message);
            }
            else if (StatusCode >= 500)
            {
                CustomLogger.Fatal(message);
            }
            else if (StatusCode >= 400)
            {
                CustomLogger.Error(message);
            }

            return(base.ExecuteResultAsync(actionContext));
        }
        public override Task ExecuteResultAsync(ActionContext actionContext)
        {
            string message;

            if (Enum.IsDefined(typeof(HttpStatusCode), StatusCode.Value))
            {
                message = $"{(HttpStatusCode)StatusCode.Value} ({StatusCode.Value}):  {StatusDescription}";
            }
            else
            {
                message = $"HttpStatusCode ({StatusCode.Value}):  {StatusDescription}";
            }
            if (StatusCode == 404 || StatusCode == 405)
            {
                CustomLogger.Warning(message);
            }
            else if (StatusCode >= 500)
            {
                CustomLogger.Fatal(message);
            }
            else if (StatusCode >= 400)
            {
                CustomLogger.Error(message);
            }

            ViewName = "Error";
            ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), actionContext.ModelState)
            {
                Model = new ErrorViewModel((int)StatusCode)  // set the model
            };

            return(base.ExecuteResultAsync(actionContext));
        }
Example #4
0
        public IActionResult ChangeAddressGet(long id)
        {
            Organisation organisation = dataRepository.Get <Organisation>(id);

            if (!string.IsNullOrWhiteSpace(organisation.CompanyNumber))
            {
                try
                {
                    CompaniesHouseCompany organisationFromCompaniesHouse =
                        companiesHouseApi.GetCompany(organisation.CompanyNumber);

                    OrganisationAddress addressFromCompaniesHouse =
                        UpdateFromCompaniesHouseService.CreateOrganisationAddressFromCompaniesHouseAddress(
                            organisationFromCompaniesHouse.RegisteredOfficeAddress);

                    if (!organisation.GetLatestAddress().AddressMatches(addressFromCompaniesHouse))
                    {
                        return(OfferNewCompaniesHouseAddress(organisation, addressFromCompaniesHouse));
                    }
                }
                catch (Exception ex)
                {
                    // Use Manual Change page instead
                    CustomLogger.Warning("Error from Companies House API", ex);
                }
            }

            // In all other cases...
            // * Organisation doesn't have a Companies House number
            // * CoHo API returns an error
            // * CoHo address matches Organisation address
            // ... send to the Manual Change page
            return(SendToManualChangePage(organisation));
        }
        public IActionResult ChangeSicCodesGet(long id)
        {
            Organisation organisation = dataRepository.Get <Organisation>(id);

            if (!string.IsNullOrWhiteSpace(organisation.CompanyNumber))
            {
                try
                {
                    CompaniesHouseCompany organisationFromCompaniesHouse =
                        companiesHouseApi.GetCompany(organisation.CompanyNumber);

                    List <string> sicCodeIdsFromCompaniesHouse = organisationFromCompaniesHouse.SicCodes;
                    List <string> sicCodesFromDatabase         = organisation.GetSicCodes().Select(osc => osc.SicCodeId.ToString()).ToList();

                    if (!sicCodesFromDatabase.ToHashSet().SetEquals(sicCodeIdsFromCompaniesHouse))
                    {
                        return(OfferNewCompaniesHouseSicCodes(organisation, sicCodeIdsFromCompaniesHouse));
                    }
                }
                catch (Exception ex)
                {
                    // Use Manual Change page instead
                    CustomLogger.Warning("Error from Companies House API", ex);
                }
            }

            // In all other cases...
            // * Organisation doesn't have a Companies House number
            // * CoHo API returns an error
            // * CoHo SIC codes match Organisation SIC codes
            // ... send to the Manual Change page
            return(SendToManualChangePage(organisation));
        }
        public IActionResult ChangeNameGet(long id)
        {
            Organisation organisation = dataRepository.Get <Organisation>(id);

            if (!string.IsNullOrWhiteSpace(organisation.CompanyNumber))
            {
                try
                {
                    CompaniesHouseCompany organisationFromCompaniesHouse =
                        companiesHouseApi.GetCompany(organisation.CompanyNumber);

                    string nameFromCompaniesHouse = organisationFromCompaniesHouse.CompanyName;

                    if (!string.Equals(organisation.OrganisationName, nameFromCompaniesHouse, StringComparison.Ordinal))
                    {
                        return(OfferNewCompaniesHouseName(organisation, nameFromCompaniesHouse));
                    }
                }
                catch (Exception ex)
                {
                    // Use Manual Change page instead
                    CustomLogger.Warning("Error from Companies House API", ex);
                }
            }

            // In all other cases...
            // * Organisation doesn't have a Companies House number
            // * CoHo API returns an error
            // * CoHo name matches Organisation name
            // ... send to the Manual Change page
            return(SendToManualChangePage(organisation));
        }
        private void RetireUserAccount(User user)
        {
            try
            {
                // update retired user registrations
                registrationRepository.RemoveRetiredUserRegistrations(user);

                // retire user
                userRepository.RetireUser(user);
            }
            catch (Exception ex)
            {
                CustomLogger.Warning($"Failed to retire user {user.UserId}", ex);
                throw;
            }
        }
        private void AddOrganisationSicCode(Organisation organisation, int sicCodeInt, SourceOfData sourceOfData)
        {
            SicCode sicCode = dataRepository.Get <SicCode>(sicCodeInt);

            if (sicCode == null)
            {
                CustomLogger.Warning(
                    "Bad SIC code",
                    new
                {
                    OrganisationName = organisation.OrganisationName,
                    CompanyNumber    = organisation.CompanyNumber,
                    SicCode          = sicCodeInt,
                    Source           = sourceOfData.ToString(),
                    Error            = $"SIC code ({sicCodeInt}) not found in our database"
                });
                return;
            }

            string source;

            switch (sourceOfData)
            {
            case SourceOfData.CompaniesHouse:
                source = "CoHo";
                break;

            case SourceOfData.Manual:
                source = "Manual";
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(sourceOfData), sourceOfData, null);
            }

            var organisationSicCode = new OrganisationSicCode
            {
                Organisation = organisation,
                SicCode      = sicCode,
                Source       = source
            };

            organisation.OrganisationSicCodes.Add(organisationSicCode);

            dataRepository.Insert(organisationSicCode);
        }
        private void AddOrganisationSicCode(Organisation organisation, string sicCodeString, SourceOfData sourceOfData)
        {
            if (!int.TryParse(sicCodeString, out int sicCodeInt))
            {
                CustomLogger.Warning(
                    "Bad SIC code",
                    new
                {
                    OrganisationName = organisation.OrganisationName,
                    CompanyNumber    = organisation.CompanyNumber,
                    SicCode          = sicCodeString,
                    Source           = sourceOfData.ToString(),
                    Error            = $"Could not parse ({sicCodeString}) as an integer"
                });
                return;
            }

            AddOrganisationSicCode(organisation, sicCodeInt, sourceOfData);
        }
        private void LogAttempt(ActionExecutingContext context, string userHostAddress)
        {
            try
            {
                string controllerMessagePart = context.Controller == null || string.IsNullOrWhiteSpace(context.Controller.ToString())
                    ? "an unknown controller"
                    : $"controller {context.Controller}";

                string forbiddingReasonMessagePart = string.IsNullOrWhiteSpace(userHostAddress)
                    ? "since it was not possible to read its host address information"
                    : $"for address {userHostAddress} as it is not part of the configured ips {_ipRange}";

                CustomLogger.Warning($"Access to {controllerMessagePart} was forbidden {forbiddingReasonMessagePart}");
            }
            catch (Exception ex)
            {
                // Don't care if there was an error during logging
                // It's more important that the code continues
            }
        }
        public IActionResult Default(int errorCode = 500)
        {
            if (errorCode == 0)
            {
                if (Response.StatusCode.Between(400, 599))
                {
                    errorCode = Response.StatusCode;
                }
                else
                {
                    errorCode = 500;
                }
            }

            var model = new ErrorViewModel(errorCode);

            //Get the exception which caused this error
            var errorData = HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            if (errorData == null)
            {
                //Log non-exception events
                var statusCodeData = HttpContext.Features.Get <IStatusCodeReExecuteFeature>();
                if (statusCodeData != null)

                {
                    if (errorCode == 404 || errorCode == 405)
                    {
                        CustomLogger.Warning($"HttpStatusCode {errorCode}, Path: {statusCodeData.OriginalPath}");
                    }
                    else if (errorCode >= 400)
                    {
                        CustomLogger.Error($"HttpStatusCode {errorCode}, Path: {statusCodeData.OriginalPath}");
                    }
                }
            }

            Response.StatusCode = errorCode;
            return(View("CustomError", model));
        }
Example #12
0
        public IActionResult ActivateService(CompleteViewModel model)
        {
            //Ensure user has completed the registration process
            User          currentUser;
            IActionResult checkResult = CheckUserRegisteredOk(out currentUser);

            if (checkResult != null)
            {
                return(checkResult);
            }

            //Ensure they have entered a PIN
            if (!ModelState.IsValid)
            {
                this.CleanModelErrors <CompleteViewModel>();
                return(View("ActivateService", model));
            }

            //Get the user organisation
            UserOrganisation userOrg = DataRepository.GetAll <UserOrganisation>()
                                       .FirstOrDefault(uo => uo.UserId == currentUser.UserId && uo.OrganisationId == ReportingOrganisationId);

            ActionResult result1;

            TimeSpan remaining = userOrg.ConfirmAttemptDate == null
                ? TimeSpan.Zero
                : userOrg.ConfirmAttemptDate.Value.AddMinutes(Global.LockoutMinutes) - VirtualDateTime.Now;

            if (userOrg.ConfirmAttempts >= Global.MaxPinAttempts && remaining > TimeSpan.Zero)
            {
                return(View("CustomError", new ErrorViewModel(1113, new { remainingTime = remaining.ToFriendly(maxParts: 2) })));
            }

            var updateSearchIndex = false;

            if (PinMatchesPinInDatabase(userOrg, model.PIN))
            {
                //Set the user org as confirmed
                userOrg.PINConfirmedDate = VirtualDateTime.Now;

                //Set the pending organisation to active
                //Make sure the found organisation is active or pending

                if (userOrg.Organisation.Status.IsAny(OrganisationStatuses.Pending, OrganisationStatuses.Active))
                {
                    userOrg.Organisation.SetStatus(
                        OrganisationStatuses.Active,
                        OriginalUser == null ? currentUser.UserId : OriginalUser.UserId,
                        "PIN Confirmed");
                    updateSearchIndex = true;
                }
                else
                {
                    CustomLogger.Warning(
                        $"Attempt to PIN activate a {userOrg.Organisation.Status} organisation",
                        $"Organisation: '{userOrg.Organisation.OrganisationName}' Reference: '{userOrg.Organisation.EmployerReference}' User: '******'");
                    return(View("CustomError", new ErrorViewModel(1149)));
                }

                //Retire the old address
                OrganisationAddress latestAddress = userOrg.Organisation.GetLatestAddress();
                if (latestAddress != null && latestAddress.AddressId != userOrg.Address.AddressId)
                {
                    latestAddress.SetStatus(
                        AddressStatuses.Retired,
                        OriginalUser == null ? currentUser.UserId : OriginalUser.UserId,
                        "Replaced by PIN in post");
                    updateSearchIndex = true;
                }

                //Activate the address the pin was sent to
                userOrg.Address.SetStatus(
                    AddressStatuses.Active,
                    OriginalUser == null ? currentUser.UserId : OriginalUser.UserId,
                    "PIN Confirmed");
                userOrg.ConfirmAttempts = 0;

                model.AccountingDate = userOrg.Organisation.SectorType.GetAccountingStartDate();
                model.OrganisationId = userOrg.OrganisationId;
                this.StashModel(model);

                result1 = RedirectToAction("ServiceActivated");

                //Send notification email to existing users
                EmailSendingServiceHelpers.SendUserAddedEmailToExistingUsers(userOrg.Organisation, userOrg.User, emailSendingService);
            }
            else
            {
                userOrg.ConfirmAttempts++;
                AddModelError(3015, "PIN");
                result1 = View("ActivateService", model);
            }

            userOrg.ConfirmAttemptDate = VirtualDateTime.Now;

            //Save the changes
            DataRepository.SaveChanges();

            //Log the registration
            auditLogger.AuditChangeToOrganisation(
                AuditedAction.RegistrationLog,
                userOrg.Organisation,
                new
            {
                Status        = "PIN Confirmed",
                Sector        = userOrg.Organisation.SectorType,
                Organisation  = userOrg.Organisation.OrganisationName,
                CompanyNo     = userOrg.Organisation.CompanyNumber,
                Address       = userOrg.Address.GetAddressString(),
                SicCodes      = userOrg.Organisation.GetSicCodeIdsString(),
                UserFirstname = userOrg.User.Firstname,
                UserLastname  = userOrg.User.Lastname,
                UserJobtitle  = userOrg.User.JobTitle,
                UserEmail     = userOrg.User.EmailAddress,
                userOrg.User.ContactFirstName,
                userOrg.User.ContactLastName,
                userOrg.User.ContactJobTitle,
                userOrg.User.ContactOrganisation,
                userOrg.User.ContactPhoneNumber
            },
                User);

            //Prompt the user with confirmation
            return(result1);
        }