From 3e517b0f967e67651a514e8526d203f9913e8d53 Mon Sep 17 00:00:00 2001 From: "DESKTOP-G961P6V\\Zhh" <839860190@qq.com> Date: Fri, 24 May 2024 23:54:42 +0800 Subject: [PATCH] =?UTF-8?q?=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UserTokenDto.cs | 12 + .../PatientRegisterAppService.cs | 11 +- .../Persons/PersonAppService.cs | 127 +++++----- .../Shentun.WebPeis.Application.csproj | 1 + .../WeChatHelper.cs | 45 ++++ .../Enums/WeChatGrant.cs | 13 ++ .../Data/CustomerAuditPropertySetter.cs | 220 ++++++++++++++++++ .../Models/PatientRegister.cs | 2 +- src/Shentun.WebPeis.Domain/Models/Person.cs | 4 +- .../Models/PersonKinship.cs | 4 +- .../OpenIddictDataSeedContributor.cs | 49 +++- .../Configures/PatientRegisterConfigure.cs | 4 +- .../Configures/PersonConfigure.cs | 6 +- .../Configures/PersonKinshipConfigure.cs | 6 +- .../Controllers/WeChatController.cs | 27 ++- .../WebPeisHttpApiHostModule.cs | 18 ++ .../appsettings.json | 4 +- .../PersonAppServiceTest.cs | 12 + 18 files changed, 482 insertions(+), 83 deletions(-) create mode 100644 src/Shentun.WebPeis.Application.Contracts/UserTokenDto.cs create mode 100644 src/Shentun.WebPeis.Application/WeChatHelper.cs create mode 100644 src/Shentun.WebPeis.Domain.Shared/Enums/WeChatGrant.cs create mode 100644 src/Shentun.WebPeis.Domain/Data/CustomerAuditPropertySetter.cs create mode 100644 test/Shentun.WebPeis.Application.Tests/PersonAppServiceTest.cs diff --git a/src/Shentun.WebPeis.Application.Contracts/UserTokenDto.cs b/src/Shentun.WebPeis.Application.Contracts/UserTokenDto.cs new file mode 100644 index 0000000..e343f60 --- /dev/null +++ b/src/Shentun.WebPeis.Application.Contracts/UserTokenDto.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Shentun.WebPeis +{ + public class UserTokenDto + { + public string AccessToken { get; set; } + public string RefreshToken { get; set; } + } +} diff --git a/src/Shentun.WebPeis.Application/PatientRegisters/PatientRegisterAppService.cs b/src/Shentun.WebPeis.Application/PatientRegisters/PatientRegisterAppService.cs index 03bff4d..d9397b6 100644 --- a/src/Shentun.WebPeis.Application/PatientRegisters/PatientRegisterAppService.cs +++ b/src/Shentun.WebPeis.Application/PatientRegisters/PatientRegisterAppService.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Shentun.Utilities; @@ -15,9 +16,10 @@ using Volo.Abp.Domain.Repositories; using Volo.Abp.Identity; namespace Shentun.WebPeis.PatientRegisters { - [Authorize] + //[Authorize] public class PatientRegisterAppService : ApplicationService { + private readonly IConfiguration _configuration; private readonly IRepository _patientRegisterRepository; public PatientRegisterAppService(IRepository patientRegisterRepository, @@ -33,6 +35,7 @@ namespace Shentun.WebPeis.PatientRegisters /// /// [HttpPost("api/app/PatientRegister/UploadReportBase64")] + [AllowAnonymous] public async Task UploadReportBase64Async(TransReportInputDto input) { var patientRegister = await _patientRegisterRepository.GetAsync(o=>o.PatientRegisterId == input.PatientRegisterId); @@ -58,8 +61,8 @@ namespace Shentun.WebPeis.PatientRegisters var requestPath = virtualPathsHelper.GetReportRequestPath(); var physicsPath = virtualPathsHelper.GetReportPhysicsPath(); - requestPath = $"{requestPath}\\{DateTime.Now.Year}\\{DateTime.Now.Month}\\{DateTime.Now.Day}"; - physicsPath = $"{physicsPath}\\{DateTime.Now.Year}\\{DateTime.Now.Month}\\{DateTime.Now.Day}"; + requestPath = $"{requestPath}\\{DateTime.Now.Year}\\{DateTime.Now.Month}\\{DateTime.Now.Day}\\"; + physicsPath = $"{physicsPath}\\{DateTime.Now.Year}\\{DateTime.Now.Month}\\{DateTime.Now.Day}\\"; @@ -72,6 +75,8 @@ namespace Shentun.WebPeis.PatientRegisters physicsPath = physicsPath + fileName; File.Copy(tempPdf, physicsPath, true);//true允许覆盖 patientRegister.ReportFile = requestPath + fileName; + patientRegister.LastModifierId = new Guid("3a12a8a6-beb9-fc29-b4e7-4acfb00d8370"); + patientRegister.LastModificationTime = DateTime.Now; await _patientRegisterRepository.UpdateAsync(patientRegister); } diff --git a/src/Shentun.WebPeis.Application/Persons/PersonAppService.cs b/src/Shentun.WebPeis.Application/Persons/PersonAppService.cs index a8ef30e..151e8f7 100644 --- a/src/Shentun.WebPeis.Application/Persons/PersonAppService.cs +++ b/src/Shentun.WebPeis.Application/Persons/PersonAppService.cs @@ -16,17 +16,27 @@ using System.Security.Claims; using System.Text.Json; using Volo.Abp.Identity; using Microsoft.AspNetCore.Identity; +using OpenIddict.Server.AspNetCore; +using Polly; +using Volo.Abp; +using Shentun.WebPeis.Enums; +using System.Net.Http.Headers; +using IdentityModel.Client; +using static Volo.Abp.Identity.Settings.IdentitySettingNames; +using Microsoft.AspNetCore.Mvc; namespace Shentun.WebPeis.Persons { - public class PersonAppService: ApplicationService + + public class PersonAppService : ApplicationService { + private SignInManager _signInManager; private readonly IConfiguration _configuration; - private readonly IRepository _identityUserRepository; + private readonly IRepository _identityUserRepository; private readonly IdentityUserManager _userManager; private readonly IRepository _repository; public PersonAppService(IRepository repository, IConfiguration configuration, - IRepository identityUserRepository, + IRepository identityUserRepository, IdentityUserManager userManager) { _repository = repository; @@ -37,68 +47,81 @@ namespace Shentun.WebPeis.Persons public async Task GetByIdAsync(PersonIdInputDto input) { - var entity = await _repository.GetAsync(o=>o.PersonId == input.PersonId); + var entity = await _repository.GetAsync(o=>o.UserId == input.PersonId); var entityDto = ObjectMapper.Map(entity); return entityDto; } - - public async Task GetWechatUserAsync(WechatUserJsCodeInputDto input) + [HttpPost("api/app/Person/GetWechatUserTokenAsync")] + public async Task GetWechatUserTokenAsync(WechatUserJsCodeInputDto input) { - IConfigurationSection configSection = _configuration.GetSection("Wechat"); - string url = configSection.GetValue("SessionUrl", "https://api.weixin.qq.com/sns/jscode2session?"); - string appId = configSection.GetValue("AppID", ""); - string appSecret = configSection.GetValue("AppSecret", ""); - - url = url + "appid=" + appId + "&secret=" + appSecret + "&js_code=" + input.JsCode + "&grant_type=authorization_code"; - - var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; - using (var httpClient = new HttpClient(handler)) + var wechatSession = await WeChatHelper.GetWechatSession(_configuration, input.JsCode); + if (wechatSession == null) { - //await异步等待回应 - - var responseResult = await httpClient.GetAsync(url); - //确保HTTP成功状态值 - if (!responseResult.IsSuccessStatusCode) - { - throw new Exception("获取微信小程序数据失败," + responseResult.StatusCode); - } + throw new Exception("微信会话返回空值"); + } + if (wechatSession.ErrCode != 0) + { + throw new Exception("微信账户登陆失败"); + } - //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) - string responseContent = await responseResult.Content.ReadAsStringAsync(); - var resultModel = JsonSerializer.Deserialize(responseContent); - var wechatUser = new WechatUserDto(); - if (resultModel.ErrCode == 0 && !string.IsNullOrWhiteSpace(resultModel.OpenId) && !string.IsNullOrWhiteSpace(resultModel.Session_Key)) - { - //将openid,session_key存入到缓存中; - string openIdKey = "openIdKey_" + Guid.NewGuid().ToString(); - string sessionKey = "sessionKey_" + Guid.NewGuid().ToString(); - wechatUser.OpenId = resultModel.OpenId; - wechatUser.OpenIdKey = openIdKey; - wechatUser.SessionKey = sessionKey; - } - else - { - throw new Exception("微信账户登陆失败"); - } + var client = new HttpClient(); + var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value; + var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value; - var person = (await _repository.GetQueryableAsync()).Where(o => o.WechatOpenId == resultModel.OpenId).FirstOrDefault(); - if(person == null) + var dic = new Dictionary { - wechatUser.IsNewUser = true; - return wechatUser; - } - using(var userHttpClient = new HttpClient()) + {"client_id",weChatClientId}, + {"client_secret",secret}, + {"grant_type",WeChatGrant.GrantType}, + + }; + var tokenRequest = new TokenRequest() + { + ClientId = weChatClientId, + ClientSecret = secret, + GrantType = WeChatGrant.GrantType + + }; + var token = await client.RequestTokenAsync(tokenRequest); + if (token.HttpResponse != null && token.HttpResponse.StatusCode == HttpStatusCode.OK) + { + var userTokenDto = new UserTokenDto { - wechatUser.IsNewUser = false; - var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId).Single(); - // var principal = await SignInManager.CreateUserPrincipalAsync(user); - } + AccessToken = token.AccessToken, + RefreshToken = token.RefreshToken + }; + return userTokenDto; + } + else + { + //msg = new UserLoginDto { code = 1, msg = "登录成功", peisid = PeisId }; + throw new UserFriendlyException("获取token失败"); + } - return wechatUser; + + //var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n); + //HttpContent httpContent = new StringContent(dicStr); + //httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); + //var tokenResult = await client.PostAsync("connect/token", httpContent); + //var tokenResultStr = await tokenResult.Content.ReadAsStringAsync(); + //if (tokenResult.IsSuccessStatusCode) + //{ + // if (!string.IsNullOrEmpty(tokenResultStr)) + // { + // dynamic signResult = JsonSerializer.Deserialize(tokenResultStr); + // } + + //} + //else + //{ + // if (string.IsNullOrEmpty(tokenResultStr)) + // throw new BusinessException(tokenResult.ReasonPhrase); + //} + + //return tokenResultStr; - } } diff --git a/src/Shentun.WebPeis.Application/Shentun.WebPeis.Application.csproj b/src/Shentun.WebPeis.Application/Shentun.WebPeis.Application.csproj index 167dfad..637b929 100644 --- a/src/Shentun.WebPeis.Application/Shentun.WebPeis.Application.csproj +++ b/src/Shentun.WebPeis.Application/Shentun.WebPeis.Application.csproj @@ -19,6 +19,7 @@ + diff --git a/src/Shentun.WebPeis.Application/WeChatHelper.cs b/src/Shentun.WebPeis.Application/WeChatHelper.cs new file mode 100644 index 0000000..fdb5770 --- /dev/null +++ b/src/Shentun.WebPeis.Application/WeChatHelper.cs @@ -0,0 +1,45 @@ +using Microsoft.Extensions.Configuration; +using Shentun.WebPeis.Wechats; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +namespace Shentun.WebPeis +{ + public class WeChatHelper + { + public static async Task GetWechatSession(IConfiguration configSection1,string jsCode) + { + IConfigurationSection wechatconfigSection = configSection1.GetSection("Wechat"); + string url = wechatconfigSection.GetValue("SessionUrl", "https://api.weixin.qq.com/sns/jscode2session?"); + string appId = wechatconfigSection.GetValue("AppID", ""); + string appSecret = wechatconfigSection.GetValue("AppSecret", ""); + + url = url + "appid=" + appId + "&secret=" + appSecret + "&js_code=" + jsCode + "&grant_type=authorization_code"; + + var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; + + using (var httpClient = new HttpClient(handler)) + { + //await异步等待回应 + + var responseResult = await httpClient.GetAsync(url); + //确保HTTP成功状态值 + if (!responseResult.IsSuccessStatusCode) + { + throw new Exception("获取微信小程序数据失败," + responseResult.StatusCode); + } + + //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) + string responseContent = await responseResult.Content.ReadAsStringAsync(); + var wechatSession = JsonSerializer.Deserialize(responseContent); + return wechatSession; + } + } + } +} diff --git a/src/Shentun.WebPeis.Domain.Shared/Enums/WeChatGrant.cs b/src/Shentun.WebPeis.Domain.Shared/Enums/WeChatGrant.cs new file mode 100644 index 0000000..89208b7 --- /dev/null +++ b/src/Shentun.WebPeis.Domain.Shared/Enums/WeChatGrant.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; + +namespace Shentun.WebPeis.Enums +{ + public class WeChatGrant + { + public const string GrantType = "WeChat"; + public static readonly ImmutableArray Scopes = ImmutableArray.Create("offline_access", "audience"); + } +} diff --git a/src/Shentun.WebPeis.Domain/Data/CustomerAuditPropertySetter.cs b/src/Shentun.WebPeis.Domain/Data/CustomerAuditPropertySetter.cs new file mode 100644 index 0000000..fd2ab89 --- /dev/null +++ b/src/Shentun.WebPeis.Domain/Data/CustomerAuditPropertySetter.cs @@ -0,0 +1,220 @@ +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Volo.Abp; +using Volo.Abp.Auditing; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.Entities.Auditing; +using Volo.Abp.MultiTenancy; +using Volo.Abp.Timing; +using Volo.Abp.Users; + +namespace Shentun.Peis.Data +{ + + //public class CustomerAuditPropertySetter + //{ + + //} + /// + /// 生成默认ID + /// + public class CustomerAuditPropertySetter : IAuditPropertySetter, ITransientDependency + { + protected ICurrentUser CurrentUser { get; } + protected ICurrentTenant CurrentTenant { get; } + + private readonly IConfiguration _configuration; + protected IClock Clock { get; } + + public CustomerAuditPropertySetter( + ICurrentUser currentUser, + ICurrentTenant currentTenant, + IClock clock, + IConfiguration configuration) + { + CurrentUser = currentUser; + CurrentTenant = currentTenant; + Clock = clock; + _configuration = configuration; + } + + public void SetCreationProperties(object targetObject) + { + SetCreationTime(targetObject); + SetCreatorId(targetObject); + } + + public void SetModificationProperties(object targetObject) + { + SetLastModificationTime(targetObject); + SetLastModifierId(targetObject); + } + + public void SetDeletionProperties(object targetObject) + { + SetDeletionTime(targetObject); + SetDeleterId(targetObject); + } + + protected virtual void SetCreationTime(object targetObject) + { + if (!(targetObject is IHasCreationTime objectWithCreationTime)) + { + return; + } + + if (objectWithCreationTime.CreationTime == default) + { + ObjectHelper.TrySetProperty(objectWithCreationTime, x => x.CreationTime, () => Clock.Now); + } + } + + protected virtual void SetCreatorId(object targetObject) + { + if (!CurrentUser.Id.HasValue) + { + var defaultCreatorId = _configuration.GetValue("AdminId"); + + #region 无登录操作 + if (targetObject is IMayHaveCreator mayHaveCreatorObjectNoLogin) + { + ObjectHelper.TrySetProperty(mayHaveCreatorObjectNoLogin, x => x.CreatorId, () => Guid.Parse(defaultCreatorId)); + } + #endregion + return; + } + + if (targetObject is IMultiTenant multiTenantEntity) + { + if (multiTenantEntity.TenantId != CurrentUser.TenantId) + { + return; + } + } + + /* TODO: The code below is from old ABP, not implemented yet + if (tenantId.HasValue && MultiTenancyHelper.IsHostEntity(entity)) + { + //Tenant user created a host entity + return; + } + */ + + if (targetObject is IMayHaveCreator mayHaveCreatorObject) + { + if (mayHaveCreatorObject.CreatorId.HasValue && mayHaveCreatorObject.CreatorId.Value != default) + { + return; + } + + ObjectHelper.TrySetProperty(mayHaveCreatorObject, x => x.CreatorId, () => CurrentUser.Id); + } + else if (targetObject is IMustHaveCreator mustHaveCreatorObject) + { + if (mustHaveCreatorObject.CreatorId != default) + { + return; + } + + ObjectHelper.TrySetProperty(mustHaveCreatorObject, x => x.CreatorId, () => CurrentUser.Id.Value); + } + } + + protected virtual void SetLastModificationTime(object targetObject) + { + if (targetObject is AuditedEntity objectWithModificationTime) + { + objectWithModificationTime.LastModificationTime = Clock.Now; + } + } + + protected virtual void SetLastModifierId(object targetObject) + { + if (!(targetObject is AuditedEntity modificationAuditedObject)) + { + return; + } + + if (!CurrentUser.Id.HasValue) + { + //modificationAuditedObject.LastModifierId = null; + //return; + var defaultCreatorId = _configuration.GetValue("AdminId"); + #region 无登录操作 + modificationAuditedObject.LastModifierId = Guid.Parse(defaultCreatorId); + return; + #endregion + } + + if (modificationAuditedObject is IMultiTenant multiTenantEntity) + { + if (multiTenantEntity.TenantId != CurrentUser.TenantId) + { + modificationAuditedObject.LastModifierId = null; + return; + } + } + + /* TODO: The code below is from old ABP, not implemented yet + if (tenantId.HasValue && MultiTenancyHelper.IsHostEntity(entity)) + { + //Tenant user modified a host entity + modificationAuditedObject.LastModifierId = null; + return; + } + */ + + modificationAuditedObject.LastModifierId = CurrentUser.Id; + } + + protected virtual void SetDeletionTime(object targetObject) + { + //if (targetObject is AuditedEntity objectWithDeletionTime) + //{ + // if (objectWithDeletionTime.DeletionTime == null) + // { + // objectWithDeletionTime.DeletionTime = Clock.Now; + // } + //} + } + + protected virtual void SetDeleterId(object targetObject) + { + //if (!(targetObject is IDeletionAuditedObject deletionAuditedObject)) + //{ + // return; + //} + + //if (deletionAuditedObject.DeleterId != null) + //{ + // return; + //} + + //if (!CurrentUser.Id.HasValue) + //{ + // deletionAuditedObject.DeleterId = null; + // return; + //} + + //if (deletionAuditedObject is IMultiTenant multiTenantEntity) + //{ + // if (multiTenantEntity.TenantId != CurrentUser.TenantId) + // { + // deletionAuditedObject.DeleterId = null; + // return; + // } + //} + + //deletionAuditedObject.DeleterId = CurrentUser.Id; + } + + public void IncrementEntityVersionProperty(object targetObject) + { + //throw new NotImplementedException(); + } + } +} diff --git a/src/Shentun.WebPeis.Domain/Models/PatientRegister.cs b/src/Shentun.WebPeis.Domain/Models/PatientRegister.cs index 5a4e64c..add3cac 100644 --- a/src/Shentun.WebPeis.Domain/Models/PatientRegister.cs +++ b/src/Shentun.WebPeis.Domain/Models/PatientRegister.cs @@ -190,7 +190,7 @@ public partial class PatientRegister : AuditedEntity, IHasConcurrencyStamp public string? HisPatientId { get; set; } - public string? ThirdId { get; set; } + public string? ThirdRegisterId { get; set; } public string? ReportFile { get; set; } diff --git a/src/Shentun.WebPeis.Domain/Models/Person.cs b/src/Shentun.WebPeis.Domain/Models/Person.cs index bca66ea..01b7923 100644 --- a/src/Shentun.WebPeis.Domain/Models/Person.cs +++ b/src/Shentun.WebPeis.Domain/Models/Person.cs @@ -10,7 +10,7 @@ namespace Shentun.WebPeis.Models; /// public partial class Person: AuditedEntity,IHasConcurrencyStamp { - public Guid PersonId { get; set; } + public Guid UserId { get; set; } /// /// 档案号 @@ -88,6 +88,6 @@ public partial class Person: AuditedEntity,IHasConcurrencyStamp public override object?[] GetKeys() { - return [PersonId]; + return [UserId]; } } diff --git a/src/Shentun.WebPeis.Domain/Models/PersonKinship.cs b/src/Shentun.WebPeis.Domain/Models/PersonKinship.cs index a77f950..26e47ac 100644 --- a/src/Shentun.WebPeis.Domain/Models/PersonKinship.cs +++ b/src/Shentun.WebPeis.Domain/Models/PersonKinship.cs @@ -5,9 +5,9 @@ namespace Shentun.WebPeis.Models; public partial class PersonKinship { - public Guid PersonId { get; set; } + public Guid UserId { get; set; } - public Guid ParentPersonId { get; set; } + public Guid ParentUserId { get; set; } public string KinshipId { get; set; } = null!; } diff --git a/src/Shentun.WebPeis.Domain/OpenIddict/OpenIddictDataSeedContributor.cs b/src/Shentun.WebPeis.Domain/OpenIddict/OpenIddictDataSeedContributor.cs index 295387f..e6e9afe 100644 --- a/src/Shentun.WebPeis.Domain/OpenIddict/OpenIddictDataSeedContributor.cs +++ b/src/Shentun.WebPeis.Domain/OpenIddict/OpenIddictDataSeedContributor.cs @@ -1,12 +1,16 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Intrinsics.Arm; +using System.Security.Cryptography; +using System.Text; using System.Text.Json; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Localization; using OpenIddict.Abstractions; +using Shentun.WebPeis.Enums; using Volo.Abp; using Volo.Abp.Authorization.Permissions; using Volo.Abp.Data; @@ -38,7 +42,7 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep IOpenIddictScopeRepository openIddictScopeRepository, IOpenIddictScopeManager scopeManager, IPermissionDataSeeder permissionDataSeeder, - IStringLocalizer l ) + IStringLocalizer l) { _configuration = configuration; _openIddictApplicationRepository = openIddictApplicationRepository; @@ -60,8 +64,11 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep { if (await _openIddictScopeRepository.FindByNameAsync("WebPeis") == null) { - await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor { - Name = "WebPeis", DisplayName = "WebPeis API", Resources = { "WebPeis" } + await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor + { + Name = "WebPeis", + DisplayName = "WebPeis API", + Resources = { "WebPeis" } }); } } @@ -101,6 +108,24 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep clientUri: swaggerRootUrl ); } + var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value; + var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value; + secret = GetSha256Hash(secret); + if (!string.IsNullOrWhiteSpace(weChatClientId)) + { + var swaggerRootUrl = configurationSection["WebPeis_Swagger:RootUrl"]?.TrimEnd('/'); + await CreateApplicationAsync( + name: weChatClientId!, + type: OpenIddictConstants.ClientTypes.Public, + consentType: OpenIddictConstants.ConsentTypes.Implicit, + displayName: "WeChat Application", + secret: secret, + grantTypes: new List { WeChatGrant.GrantType, }, + scopes: commonScopes, + redirectUri: $"{swaggerRootUrl}/swagger/oauth2-redirect.html", + clientUri: swaggerRootUrl + ); + } } private async Task CreateApplicationAsync( @@ -130,7 +155,8 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep var client = await _openIddictApplicationRepository.FindByClientIdAsync(name); - var application = new AbpApplicationDescriptor { + var application = new AbpApplicationDescriptor + { ClientId = name, ClientType = type, ClientSecret = secret, @@ -323,4 +349,19 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep { return existingClient.Permissions == JsonSerializer.Serialize(application.Permissions.Select(q => q.ToString().TrimEnd('/'))); } + + private static string GetSha256Hash(string input) + { + using (SHA256 sha256Hash = SHA256.Create()) + { + byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); + + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < bytes.Length; i++) + { + builder.Append(bytes[i].ToString("x2")); + } + return builder.ToString(); + } + } } diff --git a/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PatientRegisterConfigure.cs b/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PatientRegisterConfigure.cs index 1a7723f..ccc364b 100644 --- a/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PatientRegisterConfigure.cs +++ b/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PatientRegisterConfigure.cs @@ -174,10 +174,10 @@ namespace Shentun.WebPeis.Configures .HasComment("附加第三方信息") .HasColumnName("third_info"); - entity.Property(e => e.ThirdId) + entity.Property(e => e.ThirdRegisterId) .HasMaxLength(40) .HasComment("第三方ID") - .HasColumnName("third_id"); + .HasColumnName("third_register_id"); entity.Property(e => e.ReportFile) .HasMaxLength(255) diff --git a/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonConfigure.cs b/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonConfigure.cs index fdb4deb..d92da37 100644 --- a/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonConfigure.cs +++ b/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonConfigure.cs @@ -14,7 +14,7 @@ namespace Shentun.WebPeis.Configures { public void Configure(EntityTypeBuilder entity) { - entity.HasKey(e => e.PersonId).HasName("PK_patient"); + entity.HasKey(e => e.UserId).HasName("PK_patient"); entity.ToTable("person", tb => tb.HasComment("体检人员档案")); @@ -23,9 +23,9 @@ namespace Shentun.WebPeis.Configures entity.HasIndex(e => e.IdNo, "ix_person_id_no").IsUnique(); - entity.Property(e => e.PersonId) + entity.Property(e => e.UserId) .ValueGeneratedNever() - .HasColumnName("person_id"); + .HasColumnName("user_id"); entity.Property(e => e.Address) .HasMaxLength(100) .HasComment("地址") diff --git a/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonKinshipConfigure.cs b/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonKinshipConfigure.cs index f3287dd..8b16f20 100644 --- a/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonKinshipConfigure.cs +++ b/src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonKinshipConfigure.cs @@ -14,12 +14,12 @@ namespace Shentun.WebPeis.Configures { public void Configure(EntityTypeBuilder entity) { - entity.HasKey(e => new { e.PersonId, e.ParentPersonId, e.KinshipId }).HasName("person_kinship_pkey"); + entity.HasKey(e => new { e.UserId, e.ParentUserId, e.KinshipId }).HasName("person_kinship_pkey"); entity.ToTable("person_kinship"); - entity.Property(e => e.PersonId).HasColumnName("person_id"); - entity.Property(e => e.ParentPersonId).HasColumnName("parent_person_id"); + entity.Property(e => e.UserId).HasColumnName("user_id"); + entity.Property(e => e.ParentUserId).HasColumnName("parent_user_id"); entity.Property(e => e.KinshipId) .HasMaxLength(2) .IsFixedLength() diff --git a/src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs b/src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs index 5e46432..668deec 100644 --- a/src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs +++ b/src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs @@ -18,9 +18,12 @@ using OpenIddict.Server.AspNetCore; using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.DependencyInjection; +using System.Collections.Generic; +using IdentityModel; namespace Shentun.WebPeis.Controllers { + //[IgnoreAntiforgeryToken] //[ApiExplorerSettings(IgnoreApi = true)] public class WeChatController : AbpOpenIdDictControllerBase, ITokenExtensionGrant @@ -58,30 +61,34 @@ namespace Shentun.WebPeis.Controllers } var person = (await _personRepository.GetQueryableAsync()).Where(o => o.WechatOpenId == wechatSession.OpenId).FirstOrDefault(); var wechatUser = new WechatUserDto(); + var principal = new ClaimsPrincipal(); + var claimsIdentity = new ClaimsIdentity(); if (person == null) { + claimsIdentity.AddClaim(new Claim("IsNewUser", "N")); + claimsIdentity.AddClaim(new Claim("OpenId", wechatSession.OpenId)); wechatUser.IsNewUser = true; - return Ok(wechatUser); + principal.AddIdentity(claimsIdentity); + return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); } - var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId).Single(); - var principal = await SignInManager.CreateUserPrincipalAsync(user); - var claimsIdentity = new ClaimsIdentity(); - var claim = new Claim("PersonId",person.PersonId.ToString()); + var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.UserId).Single(); + if (user == null) + { + throw new Exception("用户不存在"); + } + principal = await SignInManager.CreateUserPrincipalAsync(user); + var claim = new Claim("IsNewUser","N"); claimsIdentity.AddClaim(claim); principal.AddIdentity(claimsIdentity); - principal.AddClaim("PersonId", person.PersonId.ToString());//测试 var scopes = context.Request.GetScopes(); principal.SetScopes(scopes); var resources = await GetResourcesAsync(scopes); principal.SetResources(resources); + return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); } - //public async Task CreateAsync() - //{ - - //} private async Task GetWechatSession(string jsCode) { diff --git a/src/Shentun.WebPeis.HttpApi.Host/WebPeisHttpApiHostModule.cs b/src/Shentun.WebPeis.HttpApi.Host/WebPeisHttpApiHostModule.cs index fd5428e..31016de 100644 --- a/src/Shentun.WebPeis.HttpApi.Host/WebPeisHttpApiHostModule.cs +++ b/src/Shentun.WebPeis.HttpApi.Host/WebPeisHttpApiHostModule.cs @@ -36,6 +36,11 @@ using Shentun.Utilities; using Volo.Abp.Json; using Microsoft.Extensions.FileProviders; using Shentun.WebPeis.VirtualPaths; +using Shentun.WebPeis.Enums; +using Volo.Abp.OpenIddict.ExtensionGrantTypes; +using OpenIddict.Server; +using Shentun.WebPeis.Controllers; +using Autofac.Core; namespace Shentun.WebPeis; @@ -63,6 +68,14 @@ public class WebPeisHttpApiHostModule : AbpModule options.UseAspNetCore(); }); }); + PreConfigure(builder => + { + //ԶITokenExtensionGrant + builder.Configure(openIddictServerOptions => + { + openIddictServerOptions.GrantTypes.Add(WeChatGrant.GrantType); + }); + }); } public override void ConfigureServices(ServiceConfigurationContext context) @@ -102,6 +115,11 @@ public class WebPeisHttpApiHostModule : AbpModule x.InputDateTimeFormats.Add( "yyyy-MM-dd HH:mm:ss"); x.OutputDateTimeFormat = "yyyy-MM-dd HH:mm:ss"; }); + context.Services.AddSingleton(); + Configure(options => + { + options.Grants.Add(WeChatGrant.GrantType, (IExtensionGrant)context.Services.GetServiceLazy()); + }); //context.Services.AddSingleton(new MyFileProvider(configuration["VirtualPath:PhysicsPath"], configuration["VirtualPath:Alias"])); } diff --git a/src/Shentun.WebPeis.HttpApi.Host/appsettings.json b/src/Shentun.WebPeis.HttpApi.Host/appsettings.json index 1780545..bc85fc7 100644 --- a/src/Shentun.WebPeis.HttpApi.Host/appsettings.json +++ b/src/Shentun.WebPeis.HttpApi.Host/appsettings.json @@ -21,7 +21,9 @@ "AuthServer": { "Authority": "https://localhost:44382", "RequireHttpsMetadata": false, - "SwaggerClientId": "WebPeis_Swagger" + "SwaggerClientId": "WebPeis_Swagger", + "WeChatClientId": "WeChatApp", + "WeChatClientSecret": "1234*^@" }, "StringEncryption": { "DefaultPassPhrase": "rBfozS7zkeTYat2k" diff --git a/test/Shentun.WebPeis.Application.Tests/PersonAppServiceTest.cs b/test/Shentun.WebPeis.Application.Tests/PersonAppServiceTest.cs new file mode 100644 index 0000000..5c89e8a --- /dev/null +++ b/test/Shentun.WebPeis.Application.Tests/PersonAppServiceTest.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shentun.WebPeis +{ + internal class PersonAppServiceTest + { + } +}