//        public static bool InitUserPermission(string reason)
//        {
//            try
//            {
//                // init dicRoleMapping trước
//                var lstRole = MemoryInfo.GetAllRole();
//                foreach (var role in lstRole)
//                {
//                    Memory.Memory.DicRoleMapping[role.Id] = new List<Permission>();
//                    // lay ra list rolepermission
//                    var lstRolePermission = MemoryInfo.GetListRolePermissionByField(role.Id.ToString(),
//                        RolePermission.RolePermissionFields.IdRole);
//                    if(lstRolePermission.Count == 0)continue;
//                    foreach (var rolePermission in lstRolePermission)
//                    {
//                        var permission = MemoryInfo.GetPermission(rolePermission.IdPermission);
//                        Memory.Memory.DicRoleMapping[role.Id].Add(permission);
//                    }
//                }
//                // init bang memory
//                // lay tat ca user cua he thong
//                var lstUserInfo = MemoryInfo.GetAllUserInfo();
//                foreach (var userInfo in lstUserInfo)
//                {
//                    Memory.Memory.DicUserPermission[userInfo.IdUserLogin] = new List<Permission>(); // khoi tao
//                    // check xem user thuoc nhom quyen nao
//                    var lstUserRole =
//                        MemoryInfo.GetListUserRoleByField(userInfo.IdUserLogin.ToString(), UserRole.UserRoleFields.IdUserLogin);
//                    if (lstUserRole.Count == 0)
//                        continue;//chua dc gan quyen
//                    var userRole = lstUserRole.FirstOrDefault(x => x.IdUserLogin == userInfo.IdUserLogin);
//                    if (userRole == null)
//                        continue; // chua duoc gan quyen
//                    var lstPermission = Memory.Memory.DicRoleMapping[userRole.IdRole];
//                    if (lstPermission.Count == 0)
//                        continue; // khong co permission nao ca
//                    Memory.Memory.DicUserPermission[userInfo.IdUserLogin].AddRange(lstPermission);
//                }
//            }
//            catch (Exception ex)
//            {
//                Logger.Write(string.Format("Init Permission voi resson:{0} that bai", reason),true);
//                Logger.Write(ex.ToString(),true);
//                return false;
//            }
//            return true;
//        }



        public static bool InitConfig()
        {
            try
            {
                #region Lay WebapiCnf
                var path = GetAppPath() + DEFAULT_FOLDER_CONFIG + NexusConfig.FileName() + EXTENSION_FILE_NAME;
                if (!File.Exists(path))
                {
                    var strMsg = "Not found file in path:" + path;
                    throw new Exception(strMsg);
                }
                var fullText = File.ReadAllText(path);
                NexusConfig = JsonConvert.DeserializeObject <NexusConfig>(fullText);
                if (NexusConfig == null)
                {
                    Logger.Write("Not get ElectricConfig");
                    Process.GetCurrentProcess().Kill();
                    return(false);
                }

                if (NexusConfig.FolderSaveImages != null && !Directory.Exists(NexusConfig.FolderSaveImages))
                {
                    Directory.CreateDirectory(NexusConfig.FolderSaveImages);
                }
                Logger.Write("Get config CashTranferWebAPi success!");
                #endregion
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Write(ex.ToString(), true);
            }
            return(false);
        }
        private HMACSHA1 GetSignatureKey(NexusConfig nexusConfig)
        {
            byte[] key = Encoding.UTF8.GetBytes(nexusConfig.HmacKey ?? throw new InvalidOperationException(
                                                    $"{nameof(nexusConfig.HmacKey)} is required"));

            return(new HMACSHA1(key));
        }
        private async Task <NexusConfig> GetSignatureKeyAsync(CancellationToken cancellationToken)
        {
            ApplicationSettings applicationSettings =
                await _applicationSettingsStore.GetApplicationSettings(cancellationToken);

            NexusConfig nexusConfig = applicationSettings.NexusConfig;

            return(nexusConfig);
        }
        public async Task <PackageUpdatedEvent?> TryGetWebHookNotification(
            HttpRequest request,
            string content,
            CancellationToken cancellationToken)
        {
            if (request.ContentType.IsNullOrWhiteSpace())
            {
                return(null);
            }

            if (!request.ContentType.Contains("application/json", StringComparison.OrdinalIgnoreCase))
            {
                _logger.Debug("Web hook request is not json");
                return(null);
            }

            if (!request.Headers.TryGetValue(NexusSignatureHeader, out var signature))
            {
                _logger.Debug("Web hook request does not contain nexus signature header");
                return(null);
            }

            if (string.IsNullOrWhiteSpace(signature))
            {
                _logger.Debug("Nexus web hook request does not contain a valid signature");
                return(null);
            }

            byte[] jsonBytes = Encoding.UTF8.GetBytes(content);

            NexusConfig nexusConfig = await GetSignatureKeyAsync(cancellationToken);

            if (string.IsNullOrWhiteSpace(nexusConfig.HmacKey))
            {
                _logger.Warning("HMAC Key for {Config} is empty, cannot process Nexus web hook request",
                                nameof(NexusConfig));
                return(null);
            }

            using HMACSHA1 hasher = GetSignatureKey(nexusConfig);
            byte[] computedHash  = hasher.ComputeHash(jsonBytes);
            byte[] expectedBytes = ((string)signature).FromHexToByteArray();

            if (!computedHash.SequenceEqual(expectedBytes))
            {
                _logger.Error("Nexus web hook signature validation failed");
                return(null);
            }

            NexusWebHookNotification?webHookNotification =
                JsonConvert.DeserializeObject <NexusWebHookNotification>(content);

            if (string.IsNullOrWhiteSpace(webHookNotification?.Audit?.Attributes?.Name))
            {
                _logger.Debug("Nexus web hook notification does not contain audit attribute name");
                return(null);
            }

            string[] split =
                webHookNotification.Audit.Attributes.Name.Split('/', StringSplitOptions.RemoveEmptyEntries);

            if (split.Length != 2)
            {
                _logger.Debug("Unexpected attribute name value '{Name}' in Nexus JSON {Json}",
                              webHookNotification.Audit.Attributes.Name, content);
                return(null);
            }

            string name    = split[0];
            string version = split[1];

            if (!SemanticVersion.TryParse(version, out SemanticVersion semanticVersion))
            {
                _logger.Debug("Could not parse semantic version from Nexus web hook notification, '{Version}'",
                              version);
                return(null);
            }

            var packageVersion = new PackageVersion(name, semanticVersion);

            _logger.Information("Successfully received Nexus web hook notification for package {Package}",
                                packageVersion);

            return(new PackageUpdatedEvent(packageVersion, nexusConfig.NuGetSource, nexusConfig.NuGetConfig));
        }