private async Task HandleVerifiedIndividualLogin(UserSettings userSettings, HttpContext context)
        {
            IConfiguration    _configuration     = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));
            IDynamicsClient   _dynamicsClient    = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient));
            FileManagerClient _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient));

            Contact contact = new Contact();

            contact.CopyHeaderValues(context.Request.Headers);

            MicrosoftDynamicsCRMcontact savedContact = _dynamicsClient.Contacts.GetByKey(userSettings.ContactId);

            if (savedContact.Address1Line1 != null && savedContact.Address1Line1 != contact.address1_line1)
            {
                MicrosoftDynamicsCRMadoxioPreviousaddress prevAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress
                {
                    AdoxioStreetaddress = savedContact.Address1Line1,
                    AdoxioProvstate     = savedContact.Address1Stateorprovince,
                    AdoxioCity          = savedContact.Address1City,
                    AdoxioCountry       = savedContact.Address1Country,
                    AdoxioPostalcode    = savedContact.Address1Postalcode,
                    ContactIdODataBind  = _dynamicsClient.GetEntityURI("contacts", savedContact.Contactid)
                };
                _dynamicsClient.Previousaddresses.Create(prevAddress);
            }

            _dynamicsClient.Contacts.Update(userSettings.ContactId, contact.ToModel());
        }
Exemple #2
0
        public async Task <IActionResult> UpdateAddress([FromBody] ViewModels.PreviousAddress item, string id)
        {
            if (id != null && item.id != null && id != item.id)
            {
                return(BadRequest());
            }

            // get the Address
            MicrosoftDynamicsCRMadoxioPreviousaddress Address = await _dynamicsClient.GetPreviousAddressById(id);

            if (Address == null)
            {
                return(new NotFoundResult());
            }
            MicrosoftDynamicsCRMadoxioPreviousaddress patchAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress();

            patchAddress.CopyValues(item);
            try
            {
                await _dynamicsClient.Previousaddresses.UpdateAsync(id, patchAddress);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating Address");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
            }

            Address = await _dynamicsClient.GetPreviousAddressById(id);

            return(Json(Address.ToViewModel()));
        }
Exemple #3
0
 public static void CopyValues(this MicrosoftDynamicsCRMadoxioPreviousaddress to, ViewModels.PreviousAddress from)
 {
     to.AdoxioName          = from.name;
     to.AdoxioStreetaddress = from.streetaddress;
     to.AdoxioCity          = from.city;
     to.AdoxioProvstate     = from.provstate;
     to.AdoxioCountry       = from.country;
     to.AdoxioPostalcode    = from.postalcode;
     to.AdoxioFromdate      = from.fromdate;
     to.AdoxioTodate        = from.todate;
 }
Exemple #4
0
        public async Task <IActionResult> CreateAddress([FromBody] ViewModels.PreviousAddress item)
        {
            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);

            MicrosoftDynamicsCRMadoxioPreviousaddress address = new MicrosoftDynamicsCRMadoxioPreviousaddress();

            // copy received values to Dynamics Application
            address.CopyValues(item);
            try
            {
                address = _dynamicsClient.Previousaddresses.Create(address);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error creating application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }


            MicrosoftDynamicsCRMadoxioPreviousaddress patchAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress();

            // set contact and worker associations
            try
            {
                var contact = _dynamicsClient.GetContactById(Guid.Parse(item.contactId));
                patchAddress.ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", item.contactId);

                var worker = _dynamicsClient.GetWorkerById(Guid.Parse(item.workerId));
                patchAddress.WorkerIdODataBind = _dynamicsClient.GetEntityURI("adoxio_workers", item.workerId);

                await _dynamicsClient.Previousaddresses.UpdateAsync(address.AdoxioPreviousaddressid, patchAddress);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }

            return(Json(address.ToViewModel()));
        }
Exemple #5
0
        public async Task <IActionResult> DeleteAddress(string id)
        {
            MicrosoftDynamicsCRMadoxioPreviousaddress address = await _dynamicsClient.GetPreviousAddressById(id);

            if (address == null)
            {
                return(new NotFoundResult());
            }

            await _dynamicsClient.Previousaddresses.DeleteAsync(id);

            return(NoContent()); // 204
        }
Exemple #6
0
        public async Task <IActionResult> CreateAddress([FromBody] ViewModels.PreviousAddress item)
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            MicrosoftDynamicsCRMadoxioPreviousaddress address = new MicrosoftDynamicsCRMadoxioPreviousaddress();

            // copy received values to Dynamics Application
            address.CopyValues(item);
            try
            {
                address = _dynamicsClient.Previousaddresses.Create(address);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating application");
                // fail if we can't create.
                throw (httpOperationException);
            }


            MicrosoftDynamicsCRMadoxioPreviousaddress patchAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress();

            // set contact and worker associations
            try
            {
                var contact = _dynamicsClient.GetContactById(Guid.Parse(item.contactId));
                patchAddress.ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", item.contactId);

                if (item.workerId != null)
                {
                    var worker = _dynamicsClient.GetWorkerById(Guid.Parse(item.workerId));
                    patchAddress.WorkerIdODataBind = _dynamicsClient.GetEntityURI("adoxio_workers", item.workerId);
                }

                await _dynamicsClient.Previousaddresses.UpdateAsync(address.AdoxioPreviousaddressid, patchAddress);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating application");
                // fail if we can't create.
                throw (httpOperationException);
            }

            return(new JsonResult(address.ToViewModel()));
        }
Exemple #7
0
        /// <summary>
        /// Convert a given voteQuestion to a ViewModel
        /// </summary>
        public static ViewModels.PreviousAddress ToViewModel(this MicrosoftDynamicsCRMadoxioPreviousaddress address)
        {
            ViewModels.PreviousAddress result = null;
            if (address != null)
            {
                result = new ViewModels.PreviousAddress();
                if (address.AdoxioPreviousaddressid != null)
                {
                    result.id = address.AdoxioPreviousaddressid;
                }

                result.name          = address.AdoxioName;
                result.streetaddress = address.AdoxioStreetaddress;
                result.city          = address.AdoxioCity;
                result.provstate     = address.AdoxioProvstate;
                result.country       = address.AdoxioCountry;
                result.postalcode    = address.AdoxioPostalcode;
                result.fromdate      = address.AdoxioFromdate;
                result.todate        = address.AdoxioTodate;
            }
            return(result);
        }
        /// <summary>
        /// Update entity in adoxio_previousaddresses
        /// </summary>
        /// <param name='adoxioPreviousaddressid'>
        /// key: adoxio_previousaddressid of adoxio_previousaddress
        /// </param>
        /// <param name='body'>
        /// New property values
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> UpdateWithHttpMessagesAsync(string adoxioPreviousaddressid, MicrosoftDynamicsCRMadoxioPreviousaddress body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (adoxioPreviousaddressid == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "adoxioPreviousaddressid");
            }
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("adoxioPreviousaddressid", adoxioPreviousaddressid);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_previousaddresses({adoxio_previousaddressid})").ToString();

            _url = _url.Replace("{adoxio_previousaddressid}", System.Uri.EscapeDataString(adoxioPreviousaddressid));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PATCH");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 204)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Exemple #9
0
 /// <summary>
 /// Update entity in adoxio_previousaddresses
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='adoxioPreviousaddressid'>
 /// key: adoxio_previousaddressid of adoxio_previousaddress
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task UpdateAsync(this IPreviousaddresses operations, string adoxioPreviousaddressid, MicrosoftDynamicsCRMadoxioPreviousaddress body, CancellationToken cancellationToken = default(CancellationToken))
 {
     (await operations.UpdateWithHttpMessagesAsync(adoxioPreviousaddressid, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
Exemple #10
0
 /// <summary>
 /// Update entity in adoxio_previousaddresses
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='adoxioPreviousaddressid'>
 /// key: adoxio_previousaddressid of adoxio_previousaddress
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 /// <param name='customHeaders'>
 /// Headers that will be added to request.
 /// </param>
 public static HttpOperationResponse UpdateWithHttpMessages(this IPreviousaddresses operations, string adoxioPreviousaddressid, MicrosoftDynamicsCRMadoxioPreviousaddress body, Dictionary <string, List <string> > customHeaders = null)
 {
     return(operations.UpdateWithHttpMessagesAsync(adoxioPreviousaddressid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult());
 }
Exemple #11
0
 /// <summary>
 /// Update entity in adoxio_previousaddresses
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='adoxioPreviousaddressid'>
 /// key: adoxio_previousaddressid of adoxio_previousaddress
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 public static void Update(this IPreviousaddresses operations, string adoxioPreviousaddressid, MicrosoftDynamicsCRMadoxioPreviousaddress body)
 {
     operations.UpdateAsync(adoxioPreviousaddressid, body).GetAwaiter().GetResult();
 }
Exemple #12
0
 /// <summary>
 /// Add new entity to adoxio_previousaddresses
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='prefer'>
 /// Required in order for the service to return a JSON representation of the
 /// object.
 /// </param>
 /// <param name='customHeaders'>
 /// Headers that will be added to request.
 /// </param>
 public static HttpOperationResponse <MicrosoftDynamicsCRMadoxioPreviousaddress> CreateWithHttpMessages(this IPreviousaddresses operations, MicrosoftDynamicsCRMadoxioPreviousaddress body, string prefer = "return=representation", Dictionary <string, List <string> > customHeaders = null)
 {
     return(operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult());
 }
Exemple #13
0
 /// <summary>
 /// Add new entity to adoxio_previousaddresses
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='prefer'>
 /// Required in order for the service to return a JSON representation of the
 /// object.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <MicrosoftDynamicsCRMadoxioPreviousaddress> CreateAsync(this IPreviousaddresses operations, MicrosoftDynamicsCRMadoxioPreviousaddress body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Exemple #14
0
 /// <summary>
 /// Add new entity to adoxio_previousaddresses
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='prefer'>
 /// Required in order for the service to return a JSON representation of the
 /// object.
 /// </param>
 public static MicrosoftDynamicsCRMadoxioPreviousaddress Create(this IPreviousaddresses operations, MicrosoftDynamicsCRMadoxioPreviousaddress body, string prefer = "return=representation")
 {
     return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult());
 }
        /// <summary>
        /// Process Authentication Request
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            // get siteminder headers
            _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential");

            SiteMinderAuthOptions options = new SiteMinderAuthOptions();
            bool isDeveloperLogin         = false;
            bool isBCSCDeveloperLogin     = false;

            try
            {
                ClaimsPrincipal principal;
                HttpContext     context = Request.HttpContext;

                IConfiguration _configuration = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));

                IDynamicsClient _dynamicsClient = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient));

                FileManagerClient _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient));

                IWebHostEnvironment hostingEnv = (IWebHostEnvironment)context.RequestServices.GetService(typeof(IWebHostEnvironment));

                UserSettings userSettings = new UserSettings();

                if (!string.IsNullOrEmpty(_configuration["FEATURE_DISABLE_LOGIN"]))
                {
                    return(AuthenticateResult.Fail(options.LoginDisabledError));
                }

                string userId                 = null;
                string devCompanyId           = null;
                string siteMinderGuid         = "";
                string siteMinderBusinessGuid = "";
                string siteMinderUserType     = "";

                // **************************************************
                // If this is an Error or Authentiation API - Ignore
                // **************************************************
                string url = context.Request.GetDisplayUrl().ToLower();

                if (url.Contains(".js"))
                {
                    return(AuthenticateResult.NoResult());
                }

                // **************************************************
                // Check if we have a Dev Environment Cookie
                // **************************************************
                if (!hostingEnv.IsProduction())
                {
                    // check for a fake BCeID login in dev mode
                    string temp = context.Request.Cookies[options.DevAuthenticationTokenKey];

                    if (string.IsNullOrEmpty(temp)) // could be an automated test user.
                    {
                        temp = context.Request.Headers["DEV-USER"];
                    }

                    if (!string.IsNullOrEmpty(temp))
                    {
                        if (temp.Contains("::"))
                        {
                            var temp2 = temp.Split("::");
                            userId = temp2[0];
                            if (temp2.Length >= 2)
                            {
                                devCompanyId = temp2[1];
                            }
                            else
                            {
                                devCompanyId = temp2[0];
                            }
                        }
                        else
                        {
                            userId       = temp;
                            devCompanyId = temp;
                        }
                        isDeveloperLogin = true;

                        _logger.LogDebug("Got user from dev cookie = " + userId + ", company = " + devCompanyId);
                    }
                    else
                    {
                        // same set of tests for a BC Services Card dev login
                        temp = context.Request.Cookies[options.DevBCSCAuthenticationTokenKey];

                        if (string.IsNullOrEmpty(temp)) // could be an automated test user.
                        {
                            temp = context.Request.Headers["DEV-BCSC-USER"];
                        }

                        if (!string.IsNullOrEmpty(temp))
                        {
                            userId = temp;
                            isBCSCDeveloperLogin = true;

                            _logger.LogDebug("Got user from dev cookie = " + userId);
                        }
                    }
                }

                // **************************************************
                // Check if the user session is already created
                // **************************************************
                try
                {
                    _logger.LogDebug("Checking user session");
                    userSettings = UserSettings.ReadUserSettings(context);
                    _logger.LogDebug("UserSettings found: " + userSettings.GetJson());
                }
                catch
                {
                    //do nothing
                    _logger.LogDebug("No UserSettings found");
                }

                // is user authenticated - if so we're done
                if ((userSettings.UserAuthenticated && string.IsNullOrEmpty(userId)) ||
                    (userSettings.UserAuthenticated && !string.IsNullOrEmpty(userId) &&
                     !string.IsNullOrEmpty(userSettings.UserId) && userSettings.UserId == userId))
                {
                    _logger.LogDebug("User already authenticated with active session: " + userSettings.UserId);
                    principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                    return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                }

                string smgov_userdisplayname = context.Request.Headers["smgov_userdisplayname"];
                if (!string.IsNullOrEmpty(smgov_userdisplayname))
                {
                    userSettings.UserDisplayName = smgov_userdisplayname;
                }

                string smgov_businesslegalname = context.Request.Headers["smgov_businesslegalname"];
                if (!string.IsNullOrEmpty(smgov_businesslegalname))
                {
                    userSettings.BusinessLegalName = smgov_businesslegalname;
                }

                // **************************************************
                // Authenticate based on SiteMinder Headers
                // **************************************************
                _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential");

                // At this point userID would only be set if we are logging in through as a DEV user

                if (string.IsNullOrEmpty(userId))
                {
                    _logger.LogDebug("Getting user data from headers");

                    userId = context.Request.Headers[options.SiteMinderUserNameKey];
                    if (string.IsNullOrEmpty(userId))
                    {
                        userId = context.Request.Headers[options.SiteMinderUniversalIdKey];
                    }

                    siteMinderGuid         = context.Request.Headers[options.SiteMinderUserGuidKey];
                    siteMinderBusinessGuid = context.Request.Headers[options.SiteMinderBusinessGuidKey];
                    siteMinderUserType     = context.Request.Headers[options.SiteMinderUserTypeKey];


                    // **************************************************
                    // Validate credentials
                    // **************************************************
                    if (string.IsNullOrEmpty(userId))
                    {
                        _logger.LogDebug(options.MissingSiteMinderUserIdError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError));
                    }

                    if (string.IsNullOrEmpty(siteMinderGuid))
                    {
                        _logger.LogDebug(options.MissingSiteMinderGuidError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError));
                    }
                    if (string.IsNullOrEmpty(siteMinderUserType))
                    {
                        _logger.LogDebug(options.MissingSiteMinderUserTypeError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderUserTypeError));
                    }
                }
                else // DEV user, setup a fake session and SiteMinder headers.
                {
                    if (isDeveloperLogin)
                    {
                        _logger.LogDebug("Generating a Development user");
                        userSettings.BusinessLegalName = devCompanyId + " TestBusiness";
                        userSettings.UserDisplayName   = userId + " TestUser";
                        siteMinderGuid         = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString();
                        siteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString();
                        siteMinderUserType     = "Business";
                    }
                    else if (isBCSCDeveloperLogin)
                    {
                        _logger.LogDebug("Generating a Development BC Services user");
                        userSettings.BusinessLegalName = null;
                        userSettings.UserDisplayName   = userId + " Associate";
                        siteMinderGuid         = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString();
                        siteMinderBusinessGuid = null;
                        siteMinderUserType     = "VerifiedIndividual";
                    }
                }

                // Previously the code would do a database lookup here.  However there is no backing database for the users table now,
                // so we just do a Dynamics lookup on the siteMinderGuid.

                _logger.LogDebug("Loading user external id = " + siteMinderGuid);
                // 3/18/2020 - Note that LoadUser will now work if there is a match on the guid, as well as a match on name in a case where there is no guid.
                userSettings.AuthenticatedUser = await _dynamicsClient.LoadUser(siteMinderGuid, context.Request.Headers, _logger);

                _logger.LogDebug("After getting authenticated user = "******" (" + userId + ")");
                    return(AuthenticateResult.Fail(options.InactivegDbUserIdError));
                }

                if (userSettings.AuthenticatedUser != null && !String.IsNullOrEmpty(siteMinderUserType))
                {
                    userSettings.AuthenticatedUser.UserType = siteMinderUserType;
                }
                userSettings.UserType = siteMinderUserType;

                // This line gets the various claims for the current user.
                ClaimsPrincipal userPrincipal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);

                // **************************************************
                // Create authenticated user
                // **************************************************
                _logger.LogDebug("Authentication successful: " + userId);
                _logger.LogDebug("Setting identity and creating session for: " + userId);

                // create session info for the current user
                userSettings.UserId                = userId;
                userSettings.UserAuthenticated     = true;
                userSettings.IsNewUserRegistration = userSettings.AuthenticatedUser == null;

                // set other session info
                userSettings.SiteMinderGuid         = siteMinderGuid;
                userSettings.SiteMinderBusinessGuid = siteMinderBusinessGuid;
                _logger.LogDebug("Before getting contact and account ids = " + userSettings.GetJson());

                if (userSettings.AuthenticatedUser != null)
                {
                    userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString();
                    // ensure that the given account has a documents folder.

                    if (siteMinderBusinessGuid != null) // BCeID user
                    {
                        var contact = _dynamicsClient.GetContactByExternalId(userSettings.ContactId);
                        if (contact == null)
                        {
                            // try by other means.
                            var contactVM = new Public.ViewModels.Contact();
                            contactVM.CopyHeaderValues(context.Request.Headers);
                            contact = _dynamicsClient.GetContactByContactVmBlankSmGuid(contactVM);
                        }
                        if (contact != null && contact.Contactid != null)
                        {
                            await CreateContactDocumentLocation(_dynamicsClient, _fileManagerClient, contact);
                        }


                        var account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(siteMinderBusinessGuid);

                        if (account == null)
                        {
                            // try by other means.
                            account = _dynamicsClient.GetAccountByLegalName(userSettings.BusinessLegalName);
                        }
                        if (account != null && account.Accountid != null)
                        {
                            userSettings.AccountId = account.Accountid;
                            userSettings.AuthenticatedUser.AccountId = Guid.Parse(account.Accountid);

                            // ensure that the given account has a documents folder.
                            await CreateAccountDocumentLocation(_dynamicsClient, _fileManagerClient, account);
                        }
                    }
                }

                if (!hostingEnv.IsProduction() && (isDeveloperLogin || isBCSCDeveloperLogin))
                {
                    _logger.LogDebug("DEV MODE Setting identity and creating session for: " + userId);

                    if (isDeveloperLogin)
                    {
                        userSettings.BusinessLegalName = devCompanyId + " TestBusiness";
                        userSettings.UserDisplayName   = userId + " TestUser";

                        // add generated guids
                        userSettings.SiteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString();
                        userSettings.SiteMinderGuid         = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString();
                    }
                    else if (isBCSCDeveloperLogin)
                    {
                        userSettings.BusinessLegalName = null;
                        userSettings.UserDisplayName   = userId + " Associate";

                        // add generated guids
                        userSettings.SiteMinderBusinessGuid = null;
                        userSettings.SiteMinderGuid         = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString();
                    }

                    if (userSettings.IsNewUserRegistration)
                    {
                        if (isDeveloperLogin)
                        {
                            // add generated guids
                            // set to null to indicate that the user is still registering the account
                            userSettings.AccountId = null;
                            userSettings.ContactId = null;
                        }
                        else if (isBCSCDeveloperLogin)
                        {
                            // set to null for now
                            userSettings.AccountId = null;
                            userSettings.ContactId = null;
                        }

                        _logger.LogDebug("New user registration:" + userSettings.UserDisplayName);
                        _logger.LogDebug("userSettings.SiteMinderBusinessGuid:" + userSettings.SiteMinderBusinessGuid);
                        _logger.LogDebug("userSettings.SiteMinderGuid:" + userSettings.SiteMinderGuid);
                        _logger.LogDebug("userSettings.AccountId:" + userSettings.AccountId);
                        _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId);
                    }
                    // Set account ID from authenticated user
                    else if (userSettings.AuthenticatedUser != null)
                    {
                        // populate the business GUID.
                        if (string.IsNullOrEmpty(userSettings.AccountId))
                        {
                            userSettings.AccountId = userSettings.AuthenticatedUser.AccountId.ToString();
                        }
                        if (string.IsNullOrEmpty(userSettings.ContactId))
                        {
                            userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString();
                        }
                        _logger.LogDebug("Returning user:"******"userSettings.AccountId:" + userSettings.AccountId);
                        _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId);
                    }
                }

                // add the worker settings if it is a new user.
                if (userSettings.IsNewUserRegistration)
                {
                    userSettings.NewWorker = new ViewModels.Worker();
                    userSettings.NewWorker.CopyHeaderValues(context.Request.Headers);

                    userSettings.NewContact = new ViewModels.Contact();
                    userSettings.NewContact.CopyHeaderValues(context.Request.Headers);

                    if (isBCSCDeveloperLogin)
                    {
                        userSettings.NewWorker.firstname  = userId;
                        userSettings.NewWorker.lastname   = "Associate";
                        userSettings.NewContact.firstname = userId;
                        userSettings.NewContact.lastname  = "Associate";
                    }
                }
                else if (siteMinderUserType == "VerifiedIndividual")
                {
                    // Verified individual is from BC Service Card which means it's a worker
                    // Update contact and worker with latest info from BC Service Card
                    MicrosoftDynamicsCRMadoxioWorkerCollection workerCollection = _dynamicsClient.Workers.Get(filter: $"_adoxio_contactid_value eq {userSettings.ContactId}");
                    if (workerCollection.Value.Count > 0)
                    {
                        MicrosoftDynamicsCRMadoxioWorker savedWorker = workerCollection.Value[0];
                        ViewModels.Contact contact = new ViewModels.Contact();
                        contact.CopyHeaderValues(context.Request.Headers);

                        MicrosoftDynamicsCRMcontact savedContact = _dynamicsClient.Contacts.GetByKey(userSettings.ContactId);
                        if (savedContact.Address1Line1 != null && savedContact.Address1Line1 != contact.address1_line1)
                        {
                            MicrosoftDynamicsCRMadoxioPreviousaddress prevAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress()
                            {
                                AdoxioStreetaddress = savedContact.Address1Line1,
                                AdoxioProvstate     = savedContact.Address1Stateorprovince,
                                AdoxioCity          = savedContact.Address1City,
                                AdoxioCountry       = savedContact.Address1Country,
                                AdoxioPostalcode    = savedContact.Address1Postalcode,
                                ContactIdODataBind  = _dynamicsClient.GetEntityURI("contacts", savedContact.Contactid)
                            };
                            _dynamicsClient.Previousaddresses.Create(prevAddress);
                        }


                        _dynamicsClient.Contacts.Update(userSettings.ContactId, contact.ToModel());


                        ViewModels.Worker worker = new ViewModels.Worker();
                        worker.CopyHeaderValues(context.Request.Headers);

                        MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker()
                        {
                            AdoxioFirstname  = worker.firstname,
                            AdoxioLastname   = worker.lastname,
                            AdoxioMiddlename = worker.middlename
                        };
                        if (worker.gender != 0)
                        {
                            patchWorker.AdoxioGendercode = (int)worker.gender;
                        }

                        _dynamicsClient.Workers.Update(savedWorker.AdoxioWorkerid, patchWorker);

                        var updatedWorker = await _dynamicsClient.GetWorkerByIdWithChildren(savedWorker.AdoxioWorkerid);

                        // only create the worker document location if the FEATURE_NO_WET_SIGNATURE setting is blank
                        if (string.IsNullOrEmpty(_configuration["FEATURE_NO_WET_SIGNATURE"]))
                        {
                            // ensure that the worker has a documents folder.
                            await CreateWorkerDocumentLocation(_dynamicsClient, _fileManagerClient, updatedWorker);
                        }
                    }
                }

                // **************************************************
                // Update user settings
                // **************************************************
                UserSettings.SaveUserSettings(userSettings, context);

                // done!
                principal = userPrincipal;
                return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw;
            }
        }