Example #1
0
        public static bool FileExists(this FileManagerClient _fileManagerClient, ILogger _logger, string entityName, string entityId, string folderName, string documentType, string fileName)
        {
            Contract.Requires(_fileManagerClient != null);
            var exists = false;

            try
            {
                // call the web service
                var request = new FolderFilesRequest
                {
                    DocumentType = documentType,
                    EntityId     = entityId,
                    EntityName   = entityName,
                    FolderName   = folderName
                };

                var result = _fileManagerClient.FolderFiles(request);

                if (result.ResultStatus == ResultStatus.Success)
                {
                    exists = result.Files.Any(f => f.Name == fileName);
                }
                else
                {
                    _logger.LogError($"ERROR in getting folder files for entity {entityName}");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error getting SharePoint File List");
            }
            return(exists);
        }
        private async Task CreateSharePointWorkerDocumentLocation(FileManagerClient _fileManagerClient, MicrosoftDynamicsCRMadoxioWorker worker)
        {
            string folderName    = "";
            string logFolderName = "";

            try
            {
                folderName    = worker.GetDocumentFolderName();
                logFolderName = WordSanitizer.Sanitize(folderName);

                var createFolderRequest = new CreateFolderRequest
                {
                    EntityName = "worker",
                    FolderName = folderName
                };

                var createFolderResult = _fileManagerClient.CreateFolder(createFolderRequest);

                if (createFolderResult.ResultStatus == ResultStatus.Fail)
                {
                    _logger.Error($"Error creating folder for contact {logFolderName}. Error is {createFolderResult.ErrorDetail}");
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Error creating folder for contact {logFolderName}");
            }
        }
Example #3
0
        public static void UploadPdf(this FileManagerClient _fileManagerClient, ILogger _logger, string entityName, string entityId, string folderName, string filename, byte[] data)
        {
            Contract.Requires(_fileManagerClient != null);

            // call the web service
            var uploadRequest = new UploadFileRequest
            {
                ContentType = "application/pdf",
                Data        = ByteString.CopyFrom(data),
                EntityName  = entityName,
                FileName    = filename,
                FolderName  = folderName
            };

            var uploadResult = _fileManagerClient.UploadFile(uploadRequest);

            // Do not save full file names to the logs (for privacy)
            var logFolderName = WordSanitizer.Sanitize(folderName);
            var logFileName   = WordSanitizer.Sanitize(filename);

            if (uploadResult.ResultStatus == ResultStatus.Success)
            {
                _logger.LogInformation($"SUCCESS in uploading PDF file {logFileName} to folder {logFolderName}");
            }
            else
            {
                _logger.LogError($"ERROR in uploading PDF file {logFileName} to folder {logFolderName}");
                throw new Exception($"ERROR in uploading PDF file {logFileName} to folder {logFolderName}");
            }
        }
        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());
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="httpContextAccessor"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="dynamicsClient"></param>
        /// <param name="fileClient"></param>

        public FileController(IConfiguration configuration, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient, FileManagerClient fileClient)
        {
            _configuration       = configuration;
            _httpContextAccessor = httpContextAccessor;
            _dynamicsClient      = dynamicsClient;
            _encryptionKey       = _configuration["ENCRYPTION_KEY"];
            _logger            = loggerFactory.CreateLogger(typeof(FileController));
            _fileManagerClient = fileClient;
        }
 public WorkerController(IConfiguration configuration, IDynamicsClient dynamicsClient, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IPdfService pdfClient, FileManagerClient fileClient)
 {
     _configuration       = configuration;
     _dynamicsClient      = dynamicsClient;
     _httpContextAccessor = httpContextAccessor;
     _logger            = loggerFactory.CreateLogger(typeof(WorkerController));
     _pdfClient         = pdfClient;
     _fileManagerClient = fileClient;
 }
Example #7
0
 public FederalReportingController(IConfiguration configuration, ILoggerFactory loggerFactory, FileManagerClient fileClient)
 {
     _configuration = configuration;
     if (_configuration["DYNAMICS_ODATA_URI"] != null)
     {
         _dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);
     }
     _fileManagerClient = fileClient;
     _logger            = loggerFactory.CreateLogger(typeof(FederalReportingController));
 }
Example #8
0
    public Form1()
    {
        InitializeComponent();
        Callback callback = new Callback();

        //Subscribe event for notification
        callback.OnDataReceivedEvent += new Callback.OnDataReceived(callback_OnDataReceivedEvent);
        InstanceContext ctx = new InstanceContext(callback);

        client = new FileManagerClient(ctx);
    }
Example #9
0
        static void Main(string[] args)
        {
            //文件相关client端
            FileManagerClient fileManagerClient = new FileManagerClient(baseUrl, new DictionaryTokenDataSource(), appId, appSecret);

            //上传文件相关API
            checkUploadFile(fileManagerClient);
            //下载文件相关API
            checkDownloadFile(fileManagerClient);

            //签章相关client端
            SignClient client = new SignClient(baseUrl, new DictionaryTokenDataSource(), appId, appSecret);

            //个人用户相关API
            checkPersonal(client);
            //企业用户相关API
            checkCompany(client);
            //证书相关API
            checkCert(client);
            //印章相关API
            checkSeal(client);
            //合同相关API
            checkContract(client);
            //模板相关API
            checkTemplate(client);
            //事件证书-扫码合同相关API
            checkEventCertScanContract(client);
            //扫码合同相关API
            checkScanContract(client);
            //短信相关API
            checkSms(client);
            //签章相关API
            checkSign(client);
            //事件证书-签章相关API
            checkEventCertSign(client);
            //验签相关API
            checkSignCheck(client);
            //认证相关API
            checkAuth(client);

            //初始化paas客户端
            PaasClient paasClient = new PaasClient(baseUrl, new DictionaryTokenDataSource(), appId, appSecret);

            //原始调用Paas Api接口,除文件上传以及文件下载API
            checkPaasApi(paasClient);

            Console.ReadKey();
        }
        private async Task HandleWorkerLogin(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));

            // Update 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];

                Worker worker = new 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 CreateSharePointWorkerDocumentLocation(_fileManagerClient, updatedWorker);
                }
            }
        }
Example #11
0
        public static string GetTruncatedFilename(this FileManagerClient _fileManagerClient, ILogger _logger, string entityName, string folderName, string fileName)
        {
            Contract.Requires(_fileManagerClient != null);
            var truncated = fileName;

            // Do not save full file names to the logs (for privacy)
            var logFileName   = WordSanitizer.Sanitize(fileName);
            var logFolderName = WordSanitizer.Sanitize(folderName);
            var errorMessage  = $"ERROR in getting truncated filename {logFileName} for folder {logFolderName}";

            try
            {
                // call the web service
                var request = new TruncatedFilenameRequest
                {
                    EntityName = entityName,
                    FolderName = folderName,
                    FileName   = fileName
                };

                // Get the (potentially) truncated filename from SharePoint
                var result = _fileManagerClient.GetTruncatedFilename(request);

                if (result.ResultStatus == ResultStatus.Success)
                {
                    truncated = result.FileName;
                }
                else
                {
                    _logger.LogError(errorMessage);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, errorMessage);
            }

            return(truncated);
        }
Example #12
0
 /// <summary>
 /// 下载附件
 /// </summary>
 /// <param name="fuJian">附件fileid</param>
 /// <param name="FileName">下载的路径</param>
 /// <returns></returns>
 private static string DownloadAtt(string fuJian, string FileName)
 {
     try
     {
         string            ls     = Environment.CurrentDirectory;
         FileManagerClient client = new FileManagerClient();
         client.FileOperator     = "manager";
         client.OperatorPassWord = "******";
         client.HostUrl          = canshu.serverName;
         client.Port             = 80;
         client.ProtocolType     = "HTTP";
         client.IsWeb            = true;
         client.ReadFile(fuJian, FileName);
         return(FileName);
         //sel.InlineShapes.AddPicture(FileName);
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.ToString());
         return("false");
     }
 }
Example #13
0
        public static void UploadPdfIfChanged(this FileManagerClient _fileManagerClient, ILogger _logger, string entityName, string entityId, string folderName, string documentType, byte[] data, string hash)
        {
            Contract.Requires(_fileManagerClient != null);
            Contract.Requires(documentType != null);

            // SharePoint can truncate file names that are too long. Make sure we account for that.
            var fileName = FileSystemItemExtensions.CombineNameDocumentType($"{hash}.pdf", documentType);

            fileName = _fileManagerClient.GetTruncatedFilename(_logger, entityName, folderName, fileName);

            var notChanged = _fileManagerClient.FileExists(_logger, entityName, entityId, folderName, documentType, fileName);

            if (notChanged)
            {
                // Do not save full file names to the logs (for privacy)
                var logFolderName = WordSanitizer.Sanitize(folderName);
                var logFileName   = WordSanitizer.Sanitize(fileName);
                _logger.LogInformation($"PDF file {logFileName} in folder {logFolderName} hasn't changed. Will NOT UPLOAD again.");

                // Abort early if PDF hasn't changed...
                return;
            }
            _fileManagerClient.UploadPdf(_logger, entityName, entityId, folderName, fileName, data);
        }
        public static void CreateFolderIfNotExist(this FileManagerClient _fileManagerClient, ILogger _logger, string entityName, string folderName)
        {
            string logFolderName = WordSanitizer.Sanitize(folderName);

            try
            {
                var createFolderRequest = new CreateFolderRequest()
                {
                    EntityName = entityName,
                    FolderName = folderName
                };

                var createFolderResult = _fileManagerClient.CreateFolder(createFolderRequest);

                if (createFolderResult.ResultStatus == ResultStatus.Fail)
                {
                    _logger.LogError($"Error creating folder for entity {entityName} and folder {logFolderName}. Error is {createFolderResult.ErrorDetail}");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error creating folder for account {entityName} and folder {logFolderName}");
            }
        }
Example #15
0
 /// <summary>
 /// 删除附件
 /// </summary>
 /// <param name="filename"></param>
 private static void DelAtt(string filename)
 {
     try
     {
         //string ls = Environment.CurrentDirectory;
         //string fuJian = "";
         //string FileName = ls + @"\tempcode.bmp";//图片所在路径
         FileManagerClient client = new FileManagerClient();
         client.FileOperator     = "manager";
         client.OperatorPassWord = "******";
         client.HostUrl          = canshu.serverName;
         client.Port             = 80;
         client.ProtocolType     = "HTTP";
         client.IsWeb            = true;
         client.DeleteFile(filename);
         //string cFileId = client.AddFile(filename, "test", 60000000, canshu.acc, canshu.acc, canshu.u8Login.CurDate.Year, true);
         ////sel.InlineShapes.AddPicture(FileName);
         //return cFileId;
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.ToString());
     }
 }
        private void SetupServices(IServiceCollection services)
        {
            string dynamicsOdataUri = _configuration["DYNAMICS_ODATA_URI"];
            string aadTenantId      = _configuration["DYNAMICS_AAD_TENANT_ID"];
            string serverAppIdUri   = _configuration["DYNAMICS_SERVER_APP_ID_URI"];
            string clientKey        = _configuration["DYNAMICS_CLIENT_KEY"];
            string clientId         = _configuration["DYNAMICS_CLIENT_ID"];

            string ssgUsername = _configuration["SSG_USERNAME"];
            string ssgPassword = _configuration["SSG_PASSWORD"];

            AuthenticationResult authenticationResult = null;



            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost",
                                        "http://cannabis-licensing-dev.pathfinder.bcgov",
                                        "http://cannabis-licensing-test.pathfinder.bcgov",
                                        "http://cannabis-licensing-prod.pathfinder.bcgov",
                                        "https://dev.justice.gov.bc.ca",
                                        "https://test.justice.gov.bc.ca",
                                        "https://justice.gov.bc.ca");
                });
            });


            services.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) =>
            {
                IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(_configuration);

                return(client);
            }));


            // add BCeID Web Services

            string bceidUrl    = _configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = _configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = _configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = _configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));

            // add BCEP services

            var bcep_svc_url       = _configuration["BCEP_SERVICE_URL"];
            var bcep_svc_svcid     = _configuration["BCEP_MERCHANT_ID"];
            var bcep_svc_alt_svcid = _configuration["BCEP_ALTERNATE_MERCHANT_ID"];
            var bcep_svc_hashid    = _configuration["BCEP_HASH_KEY"];
            var bcep_base_uri      = _configuration["BASE_URI"];
            var bcep_base_path     = _configuration["BASE_PATH"];
            var bcep_conf_path     = _configuration["BCEP_CONF_PATH"];

            services.AddTransient <BCEPWrapper>(_ => new BCEPWrapper(bcep_svc_url, bcep_svc_svcid, bcep_svc_alt_svcid, bcep_svc_hashid,
                                                                     bcep_base_uri + bcep_base_path + bcep_conf_path));

            // add the PDF client.
            string pdf_service_base_uri = _configuration["PDF_SERVICE_BASE_URI"];
            string bearer_token         = $"Bearer {_configuration["PDF_JWT_TOKEN"]}";

            services.AddTransient <PdfClient>(_ => new PdfClient(pdf_service_base_uri, bearer_token));

            // add the GeoCoder Client.

            services.AddTransient <GeocoderClient>(_ => new GeocoderClient(_configuration));

            // add the file manager.
            string fileManagerURI = _configuration["FILE_MANAGER_URI"];

            if (!_env.IsProduction()) // needed for macOS TLS being turned off
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            }
            if (!string.IsNullOrEmpty(fileManagerURI))
            {
                var httpClientHandler = new HttpClientHandler();

                if (!_env.IsProduction()) // Ignore certificate errors in non-production modes.
                                          // This allows you to use OpenShift self-signed certificates for testing.
                {
                    // Return `true` to allow certificates that are untrusted/invalid
                    httpClientHandler.ServerCertificateCustomValidationCallback =
                        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }

                var httpClient = new HttpClient(httpClientHandler);
                // set default request version to HTTP 2.  Note that Dotnet Core does not currently respect this setting for all requests.
                httpClient.DefaultRequestVersion = HttpVersion.Version20;

                var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                var initialClient = new FileManagerClient(initialChannel);
                // call the token service to get a token.
                var tokenRequest = new TokenRequest()
                {
                    Secret = _configuration["FILE_MANAGER_SECRET"]
                };

                var tokenReply = initialClient.GetToken(tokenRequest);

                if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success)
                {
                    // Add the bearer token to the client.

                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}");

                    var channel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions()
                    {
                        HttpClient = httpClient
                    });

                    services.AddTransient <FileManagerClient>(_ => new FileManagerClient(channel));
                }
            }
        }
        /// <summary>
        /// Return the list of files in a given folder.
        /// </summary>
        /// <param name="entityId"></param>
        /// <param name="entityName"></param>
        /// <param name="documentType"></param>
        /// <returns></returns>
        public static async Task <List <FileSystemItem> > GetListFilesInFolder(string entityId, string entityName, string documentType, IDynamicsClient _dynamicsClient, FileManagerClient _fileManagerClient, ILogger _logger)
        {
            var fileSystemItemVMList = new List <FileSystemItem>();

            // 4-9-2020 - GW removed session check to resolve issue with PHS links not working.  Session checks occur further up the call stack.

            if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(documentType))
            {
                return(fileSystemItemVMList);
            }
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    // call the web service
                    var request = new FolderFilesRequest
                    {
                        DocumentType = documentType,
                        EntityId     = entityId,
                        EntityName   = entityName,
                        FolderName   = await _dynamicsClient.GetFolderName(entityName, entityId)
                    };

                    var result = _fileManagerClient.FolderFiles(request);

                    if (result.ResultStatus == ResultStatus.Success)
                    {
                        // convert the results to the view model.
                        foreach (var fileDetails in result.Files)
                        {
                            var fileSystemItemVM = new FileSystemItem
                            {
                                // remove the document type text from file name
                                name = fileDetails.Name.Substring(fileDetails.Name.IndexOf("__") + 2),
                                // convert size from bytes (original) to KB
                                size = fileDetails.Size,
                                serverrelativeurl = fileDetails.ServerRelativeUrl,
                                timecreated       = fileDetails.TimeCreated.ToDateTime(),
                                timelastmodified  = fileDetails.TimeLastModified.ToDateTime(),
                                documenttype      = fileDetails.DocumentType
                            };

                            fileSystemItemVMList.Add(fileSystemItemVM);
                        }

                        break;
                    }

                    _logger.LogError($"ERROR in getting folder files for entity {entityName}, entityId {entityId}, docuemnt type {documentType} ");
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Error getting SharePoint File List");
                }
            }
            return(fileSystemItemVMList);
        }
Example #18
0
        private async Task CreateAccountDocumentLocation(IDynamicsClient _dynamicsClient, FileManagerClient _fileManagerClient, MicrosoftDynamicsCRMaccount account)
        {
            string name = "";

            try
            {
                string serverRelativeUrl = account.GetServerUrl();

                if (string.IsNullOrEmpty(account.Name))
                {
                    name = account.Accountid;
                }
                else
                {
                    name = account.Name;
                }

                name += " Account Files";

                string folderName = $"{account.Name}_{account.Accountid}";


                var createFolderRequest = new CreateFolderRequest()
                {
                    EntityName = "account",
                    FolderName = folderName
                };

                var createFolderResult = _fileManagerClient.CreateFolder(createFolderRequest);

                if (createFolderResult.ResultStatus == ResultStatus.Fail)
                {
                    _logger.LogError($"Error creating folder for account {name}. Error is {createFolderResult.ErrorDetail}");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error creating folder for account {name}");
            }


            /*
             * // now create a document location to link them.
             *
             * // Create the SharePointDocumentLocation entity
             * MicrosoftDynamicsCRMsharepointdocumentlocation mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation()
             * {
             *  Relativeurl = folderName,
             *  Description = "Account Files",
             *  Name = name
             * };
             *
             *
             * try
             * {
             *  mdcsdl = _dynamicsClient.Sharepointdocumentlocations.Create(mdcsdl);
             * }
             * catch (OdataerrorException odee)
             * {
             *  _logger.LogError("Error creating SharepointDocumentLocation");
             *  _logger.LogError("Request:");
             *  _logger.LogError(odee.Request.Content);
             *  _logger.LogError("Response:");
             *  _logger.LogError(odee.Response.Content);
             *  mdcsdl = null;
             * }
             * if (mdcsdl != null)
             * {
             *
             *  // set the parent document library.
             *  string parentDocumentLibraryReference = GetDocumentLocationReferenceByRelativeURL("account");
             *
             *  string accountUri = _dynamicsClient.GetEntityURI("accounts", account.Accountid);
             *  // add a regardingobjectid.
             *  var patchSharePointDocumentLocationIncident = new MicrosoftDynamicsCRMsharepointdocumentlocation()
             *  {
             *      RegardingobjectIdAccountODataBind = accountUri,
             *      ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference),
             *      Relativeurl = folderName,
             *      Description = "Account Files",
             *  };
             *
             *  try
             *  {
             *      _dynamicsClient.Sharepointdocumentlocations.Update(mdcsdl.Sharepointdocumentlocationid, patchSharePointDocumentLocationIncident);
             *  }
             *  catch (OdataerrorException odee)
             *  {
             *      _logger.LogError("Error adding reference SharepointDocumentLocation to account");
             *      _logger.LogError("Request:");
             *      _logger.LogError(odee.Request.Content);
             *      _logger.LogError("Response:");
             *      _logger.LogError(odee.Response.Content);
             *  }
             *
             *  string sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", mdcsdl.Sharepointdocumentlocationid);
             *
             *  OdataId oDataId = new OdataId()
             *  {
             *      OdataIdProperty = sharePointLocationData
             *  };
             *  try
             *  {
             *      _dynamicsClient.Accounts.AddReference(account.Accountid, "Account_SharepointDocumentLocation", oDataId);
             *  }
             *  catch (OdataerrorException odee)
             *  {
             *      _logger.LogError("Error adding reference to SharepointDocumentLocation");
             *      _logger.LogError("Request:");
             *      _logger.LogError(odee.Request.Content);
             *      _logger.LogError("Response:");
             *      _logger.LogError(odee.Response.Content);
             *  }
             * }
             */
        }
        /// <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;
            }
        }
        private void SetupServices(IServiceCollection services)
        {
            string dynamicsOdataUri = _configuration["DYNAMICS_ODATA_URI"];
            string aadTenantId      = _configuration["DYNAMICS_AAD_TENANT_ID"];
            string serverAppIdUri   = _configuration["DYNAMICS_SERVER_APP_ID_URI"];
            string clientKey        = _configuration["DYNAMICS_CLIENT_KEY"];
            string clientId         = _configuration["DYNAMICS_CLIENT_ID"];

            string ssgUsername = _configuration["SSG_USERNAME"];
            string ssgPassword = _configuration["SSG_PASSWORD"];

            AuthenticationResult authenticationResult = null;



            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost",
                                        "http://cannabis-licensing-dev.pathfinder.bcgov",
                                        "http://cannabis-licensing-test.pathfinder.bcgov",
                                        "http://cannabis-licensing-prod.pathfinder.bcgov",
                                        "https://dev.justice.gov.bc.ca",
                                        "https://test.justice.gov.bc.ca",
                                        "https://justice.gov.bc.ca");
                });
            });

            /*
             *
             * services.AddHttpClient("Dynamics", c =>
             *  {
             *
             *      c.BaseAddress = new Uri(dynamicsOdataUri);
             *  })
             *  .AddPolicyHandler(GetRetryPolicy())
             *  .AddPolicyHandler(GetCircuitBreakerPolicy());
             *
             * services.AddTransient(new Func<IServiceProvider, IDynamicsClient>((serviceProvider) =>
             * {
             *  var service = serviceProvider.GetRequiredService<System.Net.Http.IHttpClientFactory>();
             *  var httpClient = service.CreateClient("Dynamics");
             *
             *  IDynamicsClient client = new DynamicsClient(httpClient, _configuration);
             *
             *  return client;
             * }));
             */

            services.AddHttpClient <IDynamicsClient, DynamicsClient>();



            // add BCeID Web Services

            string bceidUrl    = _configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = _configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = _configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = _configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));

            // add BC Express Pay (Bambora) service
            services.AddHttpClient <IBCEPService, BCEPService>()
            .AddPolicyHandler(GetRetryPolicy())
            .AddPolicyHandler(GetCircuitBreakerPolicy());

            // add the PDF client.
            services.AddHttpClient <IPdfService, PdfService>()
            .AddPolicyHandler(GetRetryPolicy())
            .AddPolicyHandler(GetCircuitBreakerPolicy());

            // add the GeoCoder Client.
            services.AddHttpClient <IGeocoderService, GeocoderService>()
            .AddPolicyHandler(GetRetryPolicy())
            .AddPolicyHandler(GetCircuitBreakerPolicy());

            // add the file manager.
            string fileManagerURI = _configuration["FILE_MANAGER_URI"];

            if (!_env.IsProduction()) // needed for macOS TLS being turned off
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            }
            if (!string.IsNullOrEmpty(fileManagerURI))
            {
                var httpClientHandler = new HttpClientHandler();

                if (!_env.IsProduction()) // Ignore certificate errors in non-production modes.
                                          // This allows you to use OpenShift self-signed certificates for testing.
                {
                    // Return `true` to allow certificates that are untrusted/invalid
                    httpClientHandler.ServerCertificateCustomValidationCallback =
                        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }

                var httpClient = new HttpClient(httpClientHandler);
                // set default request version to HTTP 2.  Note that Dotnet Core does not currently respect this setting for all requests.
                httpClient.DefaultRequestVersion = HttpVersion.Version20;

                var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                var initialClient = new FileManagerClient(initialChannel);
                // call the token service to get a token.
                var tokenRequest = new TokenRequest()
                {
                    Secret = _configuration["FILE_MANAGER_SECRET"]
                };

                var tokenReply = initialClient.GetToken(tokenRequest);

                if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success)
                {
                    // Add the bearer token to the client.

                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}");

                    var channel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions()
                    {
                        HttpClient = httpClient
                    });

                    services.AddTransient <FileManagerClient>(_ => new FileManagerClient(channel));
                }
            }
        }
Example #21
0
 public FileUploadTest(FileManagerClient fileManagerClient)
 {
     this.testName = "文件上传";
     this.client   = fileManagerClient;
 }
Example #22
0
 public FileDownloadTest(FileManagerClient fileManagerClient)
 {
     this.testName = "文件下载";
     this.client   = fileManagerClient;
 }
        public static List <Public.ViewModels.FileSystemItem> GetFileDetailsListInFolder(this FileManagerClient _fileManagerClient, ILogger _logger, string entityName, string entityId, string folderName)
        {
            List <Public.ViewModels.FileSystemItem> fileSystemItemVMList = new List <Public.ViewModels.FileSystemItem>();


            try
            {
                // call the web service
                var request = new FolderFilesRequest()
                {
                    DocumentType = "",
                    EntityId     = entityId,
                    EntityName   = entityName,
                    FolderName   = folderName
                };

                var result = _fileManagerClient.FolderFiles(request);

                if (result.ResultStatus == ResultStatus.Success)
                {
                    // convert the results to the view model.
                    foreach (var fileDetails in result.Files)
                    {
                        Public.ViewModels.FileSystemItem fileSystemItemVM = new Public.ViewModels.FileSystemItem()
                        {
                            // remove the document type text from file name
                            name = fileDetails.Name.Substring(fileDetails.Name.IndexOf("__") + 2),
                            // convert size from bytes (original) to KB
                            size = fileDetails.Size,
                            serverrelativeurl = fileDetails.ServerRelativeUrl,
                            //timelastmodified = fileDetails.TimeLastModified.ToDateTime(),
                            documenttype = fileDetails.DocumentType
                        };

                        fileSystemItemVMList.Add(fileSystemItemVM);
                    }
                }
                else
                {
                    _logger.LogError($"ERROR in getting folder files for entity {entityName}");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error getting SharePoint File List");
            }

            return(fileSystemItemVMList);
        }
Example #24
0
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="fileManagerClient"></param>
        static void checkDownloadFile(FileManagerClient fileManagerClient)
        {
            FileDownloadTest test = new FileDownloadTest(fileManagerClient);

            test.runAllTest();
        }
        /// <summary>
        /// Process Authentication Request
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            // get siteminder headers
            _logger.Debug("Parsing the HTTP headers for SiteMinder authentication credential");


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

            try
            {
                ClaimsPrincipal principal;
                HttpContext     context      = Request.HttpContext;
                UserSettings    userSettings = new UserSettings();

                IConfiguration _configuration = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));
                _dynamicsClient = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient));
                FileManagerClient   _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient));
                IWebHostEnvironment hostingEnv         = (IWebHostEnvironment)context.RequestServices.GetService(typeof(IWebHostEnvironment));

                // Fail if login disabled
                if (!string.IsNullOrEmpty(_configuration["FEATURE_DISABLE_LOGIN"]))
                {
                    return(AuthenticateResult.Fail(_options.LoginDisabledError));
                }

                // Fail if coming from JS
                if (context.Request.GetDisplayUrl().ToLower().Contains(".js"))
                {
                    return(AuthenticateResult.NoResult());
                }

                // **************************************************
                // Check if the user session is already created
                // **************************************************
                try
                {
                    _logger.Debug("Checking user session");
                    userSettings = UserSettings.ReadUserSettings(context);
                    _logger.Debug("UserSettings found: " + userSettings.GetJson());
                }
                catch
                {
                    //do nothing
                    _logger.Debug("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.Debug("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)));
                }

                // **************************************************
                // Check if we have a Dev Environment Cookie
                // **************************************************
                if (!hostingEnv.IsProduction() &&
                    (!string.IsNullOrEmpty(context.Request.Cookies[_options.DevAuthenticationTokenKey]) ||
                     !string.IsNullOrEmpty(context.Request.Cookies[_options.DevBCSCAuthenticationTokenKey]) ||
                     !string.IsNullOrEmpty(context.Request.Headers[_options.DevAuthenticationTokenKey]) ||
                     !string.IsNullOrEmpty(context.Request.Headers[_options.DevBCSCAuthenticationTokenKey]))
                    )
                {
                    try
                    {
                        return(await LoginDevUser(context, _dynamicsClient));
                    }
                    catch (Exception ex)
                    {
                        _logger.Information(ex.Message);
                        _logger.Information("Couldn't successfully login as dev user - continuing as regular user");
                    }
                }

                // **************************************************
                // Authenticate based on SiteMinder Headers
                // **************************************************
                _logger.Debug("Parsing the HTTP headers for SiteMinder authentication credential");
                _logger.Debug("Getting user data from headers");

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

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

                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.Debug(_options.MissingSiteMinderUserIdError);
                    return(AuthenticateResult.Fail(_options.MissingSiteMinderGuidError));
                }

                if (string.IsNullOrEmpty(siteMinderGuid))
                {
                    _logger.Debug(_options.MissingSiteMinderGuidError);
                    return(AuthenticateResult.Fail(_options.MissingSiteMinderGuidError));
                }
                if (string.IsNullOrEmpty(siteMinderUserType))
                {
                    _logger.Debug(_options.MissingSiteMinderUserTypeError);
                    return(AuthenticateResult.Fail(_options.MissingSiteMinderUserTypeError));
                }

                _logger.Debug("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, _ms_logger);

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

                // set the usertype to siteminder
                if (userSettings.AuthenticatedUser != null &&
                    !string.IsNullOrEmpty(siteMinderUserType))
                {
                    userSettings.AuthenticatedUser.UserType = siteMinderUserType;
                }

                userSettings.UserType = siteMinderUserType;

                // Get the various claims for the current user.
                ClaimsPrincipal userPrincipal = userSettings.AuthenticatedUser.ToClaimsPrincipal(_options.Scheme, userSettings.UserType);

                // **************************************************
                // Create authenticated user
                // **************************************************
                _logger.Debug("Authentication successful: " + userId);
                _logger.Debug("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.Debug("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.GetActiveContactByExternalId(userSettings.ContactId);
                        if (contact == null)
                        {
                            // try by other means.
                            var contactVM = new Contact();
                            contactVM.CopyHeaderValues(context.Request.Headers);
                            contact = _dynamicsClient.GetContactByContactVmBlankSmGuid(contactVM);
                        }
                        if (contact != null && contact.Contactid != null)
                        {
                            await CreateSharePointContactDocumentLocation(_fileManagerClient, contact);
                        }

                        // Note that this will search for active accounts
                        var account = await _dynamicsClient.GetActiveAccountBySiteminderBusinessGuid(siteMinderBusinessGuid);

                        if (account == null)
                        {
                            // try by other means.
                            account = _dynamicsClient.GetActiveAccountByLegalName(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 CreateSharePointAccountDocumentLocation(_fileManagerClient, account);
                        }
                        else  // force the new user process if contact exists but account does not.
                        {
                            userSettings.AuthenticatedUser     = null;
                            userSettings.IsNewUserRegistration = true;
                        }
                    }
                }

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

                    userSettings.NewContact = new Contact();
                    userSettings.NewContact.CopyHeaderValues(context.Request.Headers);
                }
                else if (siteMinderUserType == "VerifiedIndividual")
                {
                    await HandleVerifiedIndividualLogin(userSettings, context);

                    if (HttpUtility.ParseQueryString(context.Request.QueryString.ToString()).Get("path") != "cannabis-associate-screening")
                    {
                        await HandleWorkerLogin(userSettings, context);
                    }
                }

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

                return(AuthenticateResult.Success(new AuthenticationTicket(userPrincipal, null, Options.Scheme)));
            }
            catch (Exception exception)
            {
                _logger.Error(exception.Message);
                throw;
            }
        }
        private async Task CreateContactDocumentLocation(IDynamicsClient _dynamicsClient, FileManagerClient _fileManagerClient, MicrosoftDynamicsCRMcontact contact)
        {
            string folderName;
            string logFolderName = "";

            try
            {
                folderName    = contact.GetDocumentFolderName();
                logFolderName = WordSanitizer.Sanitize(folderName);

                var createFolderRequest = new CreateFolderRequest()
                {
                    EntityName = "contact",
                    FolderName = folderName
                };

                var createFolderResult = _fileManagerClient.CreateFolder(createFolderRequest);

                if (createFolderResult.ResultStatus == ResultStatus.Fail)
                {
                    _logger.Error($"Error creating folder for contact {logFolderName}. Error is {createFolderResult.ErrorDetail}");
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Error creating folder for contact {logFolderName}");
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <Microsoft.Extensions.Logging.ILogger>(_loggerFactory.CreateLogger("FederalReportingService"));

            services.AddHangfire(config =>
            {
                // Change this line if you wish to have Hangfire use persistent storage.
                config.UseMemoryStorage();
                // enable console logs for jobs
                config.UseConsole();
            });

            // health checks.
            services.AddHealthChecks()
            .AddCheck("Federal Reporting Service", () => HealthCheckResult.Healthy());

            // add the file manager.
            string fileManagerURI = Configuration["FILE_MANAGER_URI"];

            if (!_env.IsProduction()) // needed for macOS TLS being turned off
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            }
            if (!string.IsNullOrEmpty(fileManagerURI))
            {
                var httpClientHandler = new HttpClientHandler();

                if (!_env.IsProduction()) // Ignore certificate errors in non-production modes.
                                          // This allows you to use OpenShift self-signed certificates for testing.
                {
                    // Return `true` to allow certificates that are untrusted/invalid
                    httpClientHandler.ServerCertificateCustomValidationCallback =
                        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }

                var httpClient = new HttpClient(httpClientHandler);
                // set default request version to HTTP 2.  Note that Dotnet Core does not currently respect this setting for all requests.
                httpClient.DefaultRequestVersion = HttpVersion.Version20;

                var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                var initialClient = new FileManagerClient(initialChannel);
                // call the token service to get a token.
                var tokenRequest = new TokenRequest()
                {
                    Secret = Configuration["FILE_MANAGER_SECRET"]
                };

                var tokenReply = initialClient.GetToken(tokenRequest);

                if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success)
                {
                    // Add the bearer token to the client.

                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}");

                    var channel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions()
                    {
                        HttpClient = httpClient
                    });
                    _fileManagerClient = new FileManagerClient(channel);
                    services.AddTransient <FileManagerClient>(_ => _fileManagerClient);
                }
            }
        }
        private async Task <AuthenticateResult> HandleLegacyAuthentication(UserSettings userSettings, HttpContext context)
        {
            // **************************************************
            // Authenticate based on SiteMinder Headers
            // **************************************************
            _logger.Debug("Parsing the HTTP headers for SiteMinder authentication credential");
            _logger.Debug("Getting user data from headers");

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

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

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

            var userId = context.Request.Headers[_options.SiteMinderUserNameKey];

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

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


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

            if (string.IsNullOrEmpty(siteMinderGuid))
            {
                _logger.Debug(_options.MissingSiteMinderGuidError);
                return(AuthenticateResult.Fail(_options.MissingSiteMinderGuidError));
            }
            if (string.IsNullOrEmpty(siteMinderUserType))
            {
                _logger.Debug(_options.MissingSiteMinderUserTypeError);
                return(AuthenticateResult.Fail(_options.MissingSiteMinderUserTypeError));
            }

            _logger.Debug("Loading user external id = " + siteMinderGuid);
            // 3/18/2020 - Note that LoadUserLegacy 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.LoadUserLegacy(siteMinderGuid, context.Request.Headers, _ms_logger);

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

            // set the usertype to siteminder
            if (userSettings.AuthenticatedUser != null &&
                !string.IsNullOrEmpty(siteMinderUserType))
            {
                userSettings.AuthenticatedUser.UserType = siteMinderUserType;
            }

            userSettings.UserType = siteMinderUserType;

            // Get the various claims for the current user.
            ClaimsPrincipal userPrincipal = userSettings.AuthenticatedUser.ToClaimsPrincipal(_options.Scheme, userSettings.UserType);

            // **************************************************
            // Create authenticated user
            // **************************************************
            _logger.Debug("Authentication successful: " + userId);
            _logger.Debug("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.Debug("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.GetActiveContactByExternalId(userSettings.ContactId);
                    if (contact == null)
                    {
                        // try by other means.
                        var contactVM = new ViewModels.Contact();
                        contactVM.CopyHeaderValues(context.Request.Headers);
                        contact = _dynamicsClient.GetContactByContactVmBlankSmGuid(contactVM);
                    }
                    if (contact != null && contact.Contactid != null)
                    {
                        await CreateSharePointContactDocumentLocation(_fileManagerClient, contact);
                    }

                    // Note that this will search for active accounts
                    var account = await _dynamicsClient.GetActiveAccountBySiteminderBusinessGuid(siteMinderBusinessGuid);

                    if (account == null)
                    {
                        // try by other means.
                        account = _dynamicsClient.GetActiveAccountByLegalName(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 CreateSharePointAccountDocumentLocation(_fileManagerClient, account);
                    }
                    else  // force the new user process if contact exists but account does not.
                    {
                        userSettings.AuthenticatedUser     = null;
                        userSettings.IsNewUserRegistration = true;
                    }

                    // handle cases where Contact was deleted.
                    if (contact == null)
                    {
                        userSettings.IsNewUserRegistration = true;
                    }
                }
            }

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

                userSettings.NewContact = new ViewModels.Contact();
                userSettings.NewContact.CopyHeaderValues(context.Request.Headers);
            }
            else if (siteMinderUserType == "VerifiedIndividual")
            {
                await HandleVerifiedIndividualLogin(userSettings, context);

                if (HttpUtility.ParseQueryString(context.Request.QueryString.ToString()).Get("path") != "cannabis-associate-screening")
                {
                    await HandleWorkerLogin(userSettings, context);
                }
            }

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

            return(AuthenticateResult.Success(new AuthenticationTicket(userPrincipal, null, Options.Scheme)));
        }