Ejemplo n.º 1
0
        private static async ValueTask <Certificate> AcquireCertificateAsync(this IAuthority authority, CancellationToken cancellation = default)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            var response = await Paying.HttpClientFactory.GetHttpClient(authority.Certificate).GetAsync("https://api.mch.weixin.qq.com/v3/certificates", cancellation);

            if (!response.IsSuccessStatusCode)
            {
                return(_certificate);
            }

            //更新获取的时间
            _timestamp = DateTime.Now;

            var infos = (await response.Content.ReadFromJsonAsync <CertificateResult>(null, cancellation)).Value;

            if (infos == null || infos.Length == 0)
            {
                return(_certificate ?? _transitory);
            }

            if (infos.Length == 1)
            {
                return(_certificate = Create(authority, infos[0]));
            }

            var sequences = infos.OrderBy(p => p.Expiration);

            _transitory = Create(authority, sequences.FirstOrDefault());
            return(_certificate = Create(authority, sequences.LastOrDefault()));
Ejemplo n.º 2
0
        public static PaymentManager Get(IAuthority authority)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            if (string.IsNullOrEmpty(authority.Code) || authority.Certificate == null)
            {
                throw new ArgumentException("Invalid authority of the wechat.");
            }

            if (authority.Certificate == null || string.IsNullOrEmpty(authority.Certificate.Code) || authority.Certificate.PrivateKey == null)
            {
                throw new ArgumentException($"Invalid certificate of the '{authority.Code}' wechat authority.");
            }

            return(_services.GetOrAdd(authority.Code, (key, authority) =>
            {
                return new PaymentManager()
                {
                    Payment = new PaymentService.DirectPaymentService(authority),
                    Refundment = new RefundmentService.DirectRefundmentService(authority),
                };
            }, authority));
        }
 public SystemManagerController(ISystemUser systemUser, ISystemRole systemRole, IRoleRelationship roleRelationship, IAuthority authority)
 {
     this._authority        = authority;
     this._systemRole       = systemRole;
     this._systemUser       = systemUser;
     this._roleRelationship = roleRelationship;
 }
Ejemplo n.º 4
0
        public static async ValueTask <IEnumerable <BankBranch> > GetBranchesAsync(this IAuthority authority, string id, string city, Paging page = null, CancellationToken cancellation = default)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            var offset = page == null || page.PageIndex < 1 ? 0 : (page.PageIndex - 1) * page.PageSize;
            var limit  = page == null || page.PageSize < 1 ? 100 : page.PageSize;

            var response = await Paying.HttpClientFactory.GetHttpClient(authority.Certificate).GetAsync($"capital/capitallhh/banks/{id}/branches?city_code={city}&offset={offset}&limit={limit}", cancellation);

            var result = await response.GetResultAsync <Result <BankBranch> >(cancellation);

            if (result.Succeed)
            {
                if (page != null)
                {
                    page.TotalCount = result.Value.Total;
                }

                return(result.Value.Data);
            }

            return(null);
        }
Ejemplo n.º 5
0
        public static async ValueTask <IEnumerable <Bank> > GetBanksAsync(this IAuthority authority, BankKind kind, Paging page = null, CancellationToken cancellation = default)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            var offset = page == null || page.PageIndex < 1 ? 0 : (page.PageIndex - 1) * page.PageSize;
            var limit  = page == null || page.PageSize < 1 ? 100 : page.PageSize;

            var response = kind == BankKind.Personal ?
                           await Paying.HttpClientFactory.GetHttpClient(authority.Certificate).GetAsync($"capital/capitallhh/banks/personal-banking?offset={offset}&limit={limit}", cancellation) :
                           await Paying.HttpClientFactory.GetHttpClient(authority.Certificate).GetAsync($"capital/capitallhh/banks/corporate-banking?offset={offset}&limit={limit}", cancellation);

            var result = await response.GetResultAsync <Result <Bank> >(cancellation);

            if (result.Succeed)
            {
                if (page != null)
                {
                    page.TotalCount = result.Value.Total;
                }

                return(result.Value.Data);
            }

            return(null);
        }
    /// <summary>
    ///   <para>Specifies federal authority.</para>
    /// </summary>
    /// <param name="call">API call instance to use.</param>
    /// <param name="authority">Instance of authority.</param>
    /// <returns>Back reference to the provided <paramref name="call"/> instance.</returns>
    /// <exception cref="ArgumentNullException">If either <paramref name="call"/> or <paramref name="authority"/> is a <c>null</c> reference.</exception>
    public static ILawsLawApiCall FederalAuthority(this ILawsLawApiCall call, IAuthority authority)
    {
      Assertion.NotNull(call);
      Assertion.NotNull(authority);

      return call.FederalAuthority(authority.Id);
    }
        /// <summary>
        /// Get WebAuthority from Authority.
        /// </summary>
        /// <param name="userContext">User context.</param>
        /// <param name="authority">Authority.</param>
        /// <returns>WebAuthority.</returns>
        public WebAuthority GetAuthority(IUserContext userContext,
                                         IAuthority authority)
        {
            WebAuthority webAuthority;

            webAuthority = new WebAuthority();

            webAuthority.ActionGUIDs   = authority.ActionGUIDs;
            webAuthority.FactorGUIDs   = authority.FactorGUIDs;
            webAuthority.LocalityGUIDs = authority.LocalityGUIDs;
            webAuthority.ProjectGUIDs  = authority.ProjectGUIDs;
            webAuthority.RegionGUIDs   = authority.RegionGUIDs;
            webAuthority.TaxonGUIDs    = authority.TaxonGUIDs;

            webAuthority.ReadPermission   = authority.ReadPermission;
            webAuthority.CreatePermission = authority.CreatePermission;
            webAuthority.UpdatePermission = authority.UpdatePermission;
            webAuthority.DeletePermission = authority.DeletePermission;

            webAuthority.MaxProtectionLevel = authority.MaxProtectionLevel;
            webAuthority.ShowNonPublicData  = authority.ReadNonPublicPermission;

            webAuthority.RoleId = authority.RoleId;

            if (authority.AdministrationRoleId.HasValue)
            {
                webAuthority.AdministrationRoleId = authority.AdministrationRoleId.Value;
            }
            webAuthority.Identifier  = authority.Identifier;
            webAuthority.CreatedBy   = authority.UpdateInformation.CreatedBy;
            webAuthority.CreatedDate = authority.UpdateInformation.CreatedDate;
            webAuthority.Description = authority.Description;
            webAuthority.GUID        = authority.GUID;
            webAuthority.Id          = authority.Id;
            webAuthority.IsAdministrationRoleIdSpecified = authority.AdministrationRoleId.HasValue;
            webAuthority.ModifiedBy    = authority.UpdateInformation.ModifiedBy;
            webAuthority.ModifiedDate  = authority.UpdateInformation.ModifiedDate;
            webAuthority.Name          = authority.Name;
            webAuthority.Obligation    = authority.Obligation;
            webAuthority.ValidFromDate = authority.ValidFromDate;
            webAuthority.ValidToDate   = authority.ValidToDate;
            webAuthority.AuthorityType = authority.AuthorityType;
            // If authority is of type data type the id and identifier must be set,
            // otherwise the autority is associated with an application.
            // if(authority.AuthorityType.Equals(AuthorityType.DataType))
            if (authority.AuthorityDataType.IsNotNull())
            {
                WebAuthorityDataType webAuthorityDataType = new WebAuthorityDataType();
                webAuthorityDataType.Id         = authority.AuthorityDataType.Id;
                webAuthorityDataType.Identifier = authority.AuthorityDataType.Identifier;
                webAuthority.AuthorityDataType  = webAuthorityDataType;
            }
            else
            {
                webAuthority.ApplicationId = authority.ApplicationId;
            }
            return(webAuthority);
        }
Ejemplo n.º 8
0
 public HomeController(IMailDemonDatabaseProvider dbProvider, IMailCreator mailCreator, IMailSender mailSender,
                       IBulkMailSender bulkMailSender, IAuthority authority)
 {
     this.dbProvider     = dbProvider;
     this.mailCreator    = mailCreator ?? throw new ArgumentNullException(nameof(mailCreator));
     this.mailSender     = mailSender ?? throw new ArgumentNullException(nameof(mailSender));
     this.bulkMailSender = bulkMailSender;
     this.authority      = authority;
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 获取微信平台的数字证书。
        /// </summary>
        /// <param name="authority">获取凭证证书的机构,即指定以哪个机构的身份来获取平台证书。</param>
        /// <param name="cancellation">异步任务的取消标记。</param>
        /// <returns>返回的微信平台的数字证书。</returns>
        public static ValueTask <Certificate> GetCertificateAsync(this IAuthority authority, CancellationToken cancellation = default)
        {
            if (_certificate != null && _certificate.Validity.IsValidate(DateTime.UtcNow) && _certificate.Validity.Final > DateTime.UtcNow.AddHours(36))
            {
                return(ValueTask.FromResult(_certificate));
            }

            return(AcquireCertificateAsync(authority, cancellation));
        }
Ejemplo n.º 10
0
 public AdminController(IExamRepository examRepository, IUserRepository userRepository, IAnswerRepository answerRepository, IAuthority authority, IStatistics statistics, AppConfig config)
 {
     this.userRepository   = userRepository;
     this.answerRepository = answerRepository;
     this.examRepository   = examRepository;
     this.authority        = authority;
     this.statistics       = statistics;
     this.config           = config;
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Test constructor which allows for using fake credential stores.
 /// </summary>
 internal AadAuthentication(
     RuntimeContext context,
     ICredentialStore personalAccessTokenStore,
     ITokenStore vstsIdeTokenCache,
     IAuthority vstsAuthority)
     : base(context,
            personalAccessTokenStore,
            vstsIdeTokenCache,
            vstsAuthority)
 {
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Test constructor which allows for using fake credential stores
 /// </summary>
 /// <param name="personalAccessTokenStore"></param>
 /// <param name="adaRefreshTokenStore"></param>
 /// <param name="ideTokenCache"></param>
 /// <param name="msaAuthority"></param>
 internal MsaAuthentication(
     RuntimeContext context,
     ICredentialStore personalAccessTokenStore,
     ITokenStore ideTokenCache,
     IAuthority msaAuthority)
     : base(context,
            personalAccessTokenStore,
            ideTokenCache,
            msaAuthority)
 {
 }
Ejemplo n.º 13
0
 public DeviceAssignmentController(IMapper mapper,
                                   IAssignmentRepository repo,
                                   IAuthority auth,
                                   IDeviceRepository deviceRepo,
                                   IAssigneeRepository assigneeRepo)
 {
     _mapper       = mapper;
     _repo         = repo;
     _auth         = auth;
     _deviceRepo   = deviceRepo;
     _assigneeRepo = assigneeRepo;
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref = "Allocation"/> class.
 /// </summary>
 /// <param name = "authority" >
 /// The authority.
 /// </param>
 public Allocation(IAuthority authority)
 {
     Authority           = authority;
     BudgetFiscalYear    = Authority?.GetBudgetFiscalYear();
     Data                = Authority?.ToDictionary();
     Funds               = GetFunds();
     ProgramResultCodes  = GetProgramResultsCodes();
     FullTimeEquivalents = GetFullTimeEquivalents();
     Organizations       = GetOrganizations();
     AllowanceHolders    = GetAllowanceHolders();
     Accounts            = GetAccounts();
     ObjectClasses       = GetBudgetObjectClasses();
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref = "ExcelBudget"/> class.
 /// </summary>
 /// <param name = "authority" >
 /// The authority.
 /// </param>
 public ExcelBudget(IAuthority authority)
 {
     Excel      = new ExcelPackage(new FileInfo(FilePath));
     Workbook   = Excel.Workbook;
     SheetCount = Workbook.Worksheets.Count;
     Authority  = authority;
     Allocation = Authority.GetAllocation();
     Data       = Allocation.GetData();
     BFY        = Authority.GetBudgetFiscalYear();
     RPIO       = Authority.GetResourcePlanningOffice();
     Fund       = Authority.GetFund();
     AH         = Authority.GetAllowanceHolder();
     ORG        = Authority.GetOrganization();
     RC         = Authority.GetResponsibilityCenter();
     Division   = new Division(RC);
 }
        internal Authentication(
            RuntimeContext context,
            ICredentialStore personalAccessTokenStore,
            ITokenStore ideTokenCache,
            IAuthority authority)
            : this(context, TokenScope.ProfileRead, personalAccessTokenStore)
        {
            if (ideTokenCache is null)
            {
                throw new ArgumentNullException(nameof(ideTokenCache));
            }
            if (authority is null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            IdeTokenCache = ideTokenCache;
            Authority     = authority;
        }
Ejemplo n.º 17
0
        public static async ValueTask <Bank?> FindAsync(this IAuthority authority, string code, CancellationToken cancellation = default)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException(nameof(code));
            }

            var account  = Convert.ToBase64String(authority.Certificate.Encrypt(code));
            var response = await Paying.HttpClientFactory.GetHttpClient(authority.Certificate).GetAsync($"capital/capitallhh/banks/search-banks-by-bank-account?account_number={account}", cancellation);

            var result = await Paying.HttpUtility.GetResultAsync <Result <Bank> >(response, cancellation);

            return(result.Succeed && result.Value.Data != null && result.Value.Data.Length > 0 ? result.Value.Data[0] : null);
        }
Ejemplo n.º 18
0
        private static async ValueTask <OperationResult <string> > UploadFileAsync(this IAuthority authority, string filePath, string url, CancellationToken cancellation = default)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            byte[] data;

            using var fileStream = FileSystem.File.Open(filePath, FileMode.Open, FileAccess.Read);
            {
                using var stream = new MemoryStream();
                await fileStream.CopyToAsync(stream);

                data = stream.ToArray();
            }

            var client   = HttpClientFactory.GetHttpClient(authority.Certificate);
            var fileName = System.IO.Path.GetFileName(filePath);

            string boundary = Guid.NewGuid().ToString("N");
            var    form     = new MultipartFormDataContent(boundary);

            //注意:.NET默认会为boundary值加上双引号,这会导致微信服务器处理异常,故而必须手动指定一个不带双引号的boundary值
            form.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data; boundary=" + boundary);

            var digest = _sha256.ComputeHash(data);
            var json   = JsonContent.Create(new { filename = fileName, sha256 = System.Convert.ToHexString(digest) });

            form.Add(json, "\"meta\"");                                               //注意:必须加上双引号
            form.Add(new ByteArrayContent(data), "\"file\"", "\"" + fileName + "\""); //注意:必须加上双引号

            var response = await client.PostAsync(url, form, cancellation);

            var result = await response.GetResultAsync <UploaderResult>(cancellation);

            return(result.Succeed ? OperationResult.Success(result.Value.Identifier) : result.Failure);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="personalAccessTokenStore">where to store validated credentials</param>
        /// <param name="acquireCredentialsCallback">
        /// what to call to promot the user for Basic Auth credentials
        /// </param>
        /// <param name="acquireAuthenticationOAuthCallback">
        /// what to call to prompt the user to run the OAuth process
        /// </param>
        public Authentication(
            RuntimeContext context,
            ICredentialStore personalAccessTokenStore,
            AcquireCredentialsDelegate acquireCredentialsCallback,
            AcquireAuthenticationOAuthDelegate acquireAuthenticationOAuthCallback,
            IAuthority authority = null)
            : base(context)
        {
            if (personalAccessTokenStore == null)
            {
                throw new ArgumentNullException(nameof(personalAccessTokenStore), $"The parameter `{nameof(personalAccessTokenStore)}` is null or invalid.");
            }

            PersonalAccessTokenStore = personalAccessTokenStore;

            BitbucketAuthority = authority ?? new Authority(context);
            TokenScope         = TokenScope.SnippetWrite | TokenScope.RepositoryWrite;

            AcquireCredentialsCallback         = acquireCredentialsCallback;
            AcquireAuthenticationOAuthCallback = acquireAuthenticationOAuthCallback;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 获取微信平台的数字证书。
        /// </summary>
        /// <param name="authority">获取凭证证书的机构,即指定以哪个机构的身份来获取平台证书。</param>
        /// <param name="cancellation">异步任务的取消标记。</param>
        /// <returns>返回的微信平台的数字证书。</returns>
        public static async ValueTask <Certificate> GetCertificateAsync(this IAuthority authority, string code, CancellationToken cancellation = default)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(await GetCertificateAsync(authority, cancellation));
            }

            //在现有缓存中查找指定的凭证
            var found = Find(code);

            //如果找到或者凭证刷新时间距离此刻小于特定时长则直接返回
            if (found != null || (DateTime.Now - _timestamp).TotalHours < 4)
            {
                return(found);
            }

            //刷新获取最新的微信平台数字证书
            await AcquireCertificateAsync(authority, cancellation);

            //从最新的缓存中查找指定的凭证
            return(Find(code));
        }
Ejemplo n.º 21
0
        public static PaymentManager Get(string name, IAuthority authority)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            if (string.IsNullOrEmpty(authority.Code))
            {
                throw new ArgumentException("Invalid authority of the wechat.");
            }

            var master = AuthorityFactory.GetAuthority(name) ??
                         throw new InvalidOperationException($"The specified '{name}' authority does not exist.");

            return(_services.GetOrAdd(name + ':' + authority.Code, (key, state) =>
            {
                return new PaymentManager()
                {
                    Payment = new PaymentService.BrokerPaymentService(state.master, state.authority),
                    Refundment = new RefundmentService.BrokerRefundmentService(state.master, state.authority),
                };
            }, new { master, authority }));
        }
Ejemplo n.º 22
0
        public static ValueTask <OperationResult <string> > UploadAsync(this IAuthority authority, string filePath, CancellationToken cancellation = default)
        {
            if (authority == null)
            {
                throw new ArgumentNullException(nameof(authority));
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            var extension = System.IO.Path.GetExtension(filePath);

            switch (extension.ToLowerInvariant())
            {
            case ".png":
            case ".jpg":
            case ".jpeg":
                return(UploadFileAsync(authority, filePath, "merchant/media/upload", cancellation));

            case ".avi":
            case ".wmv":
            case ".mp4":
            case ".mov":
            case ".mkv":
            case ".flv":
            case ".f4v":
            case ".m4v":
            case ".rmvb":
            case ".mpeg":
                return(UploadFileAsync(authority, filePath, "merchant/media/video_upload", cancellation));
            }

            return(ValueTask.FromResult((OperationResult <string>)OperationResult.Fail("InvalidFileFormat", $"Unsupported '{extension}' file format.")));
        }
Ejemplo n.º 23
0
 public SimCardController(IMapper mapper, ISimCardRepository repo, IAuthority auth)
 {
     _mapper = mapper;
     _repo   = repo;
     _auth   = auth;
 }
Ejemplo n.º 24
0
 public SlackController(AppConfig config, IUserRepository userRepository, IAuthority authority)
 {
     this.config         = config;
     this.userRepository = userRepository;
     this.authority      = authority;
 }
Ejemplo n.º 25
0
 public ProductCapacityController(IMapper mapper, IProductCapacityRepository repo, IAuthority auth)
 {
     _auth   = auth;
     _repo   = repo;
     _mapper = mapper;
 }
Ejemplo n.º 26
0
 public DeviceStatusController(IMapper mapper, IDeviceStatusRepository repo, IAuthority auth)
 {
     _mapper = mapper;
     _repo   = repo;
     _auth   = auth;
 }
Ejemplo n.º 27
0
        public static async Task <DnsServer> Create(string ip, int port, IRecordResolver recordResolver, IAuthority areWeAuthority, IExceptionHandler onError)
        {
            var networkInterface = Network.Interfaces.FirstOrDefault(x => x.IpAddress == ip);

            var udpReceiver = new UdpSocketReceiver();

            var observerUdpReceiver = await udpReceiver.ObservableUnicastListener(
                port : port,
                communicationInterface : networkInterface,
                allowMultipleBindToSamePort : false);

            var subscriberUpdReceiver = observerUdpReceiver.Subscribe(
                async udpMsg =>
            {
                var req      = Reader.ReadRequest(new MemoryStream(udpMsg.ByteData));
                var response = new Response(req);

                foreach (var q in req)
                {
                    var record = recordResolver.Resolve(q.Class, q.Type, q.Name);
                    if (record == null)
                    {
                        continue;
                    }

                    if (areWeAuthority?.AreWeAuthority(q.Name) ?? false)
                    {
                        response.Authorities.Add(record);
                    }
                    else
                    {
                        response.Answers.Add(record);
                    }
                }
                await udpReceiver.SendToAsync(Writer.Serialize(response), udpMsg.RemoteAddress, int.Parse(udpMsg.RemotePort));
            },
                x => onError?.OnError(x));

            return(new UDPServer
            {
                udpReceiver = udpReceiver,
                observerUdpReceiver = observerUdpReceiver,
                subscriberUpdReceiver = subscriberUpdReceiver,
                RecordResolver = recordResolver
            });
        }
Ejemplo n.º 28
0
 public static Task <DnsServer> Create(string ip, IRecordResolver recordResolver, IAuthority areWeAuthority, IExceptionHandler onError)
 {
     return(Create(ip, 53, recordResolver, areWeAuthority, onError));
 }
Ejemplo n.º 29
0
 public virtual void Visit(TContext context, IAuthority authority)
 {
     authority.Accept(this, context);
 }
Ejemplo n.º 30
0
 public AssigneeController(IMapper mapper, IAssigneeRepository repo, IAuthority auth)
 {
     _mapper = mapper;
     _repo   = repo;
     _auth   = auth;
 }
Ejemplo n.º 31
0
 public MerchantService(IAuthority authority)
 {
     _authority = authority ?? throw new ArgumentNullException(nameof(authority));
 }