Browse Source

登录

master
DESKTOP-G961P6V\Zhh 2 years ago
parent
commit
3e517b0f96
  1. 12
      src/Shentun.WebPeis.Application.Contracts/UserTokenDto.cs
  2. 11
      src/Shentun.WebPeis.Application/PatientRegisters/PatientRegisterAppService.cs
  3. 127
      src/Shentun.WebPeis.Application/Persons/PersonAppService.cs
  4. 1
      src/Shentun.WebPeis.Application/Shentun.WebPeis.Application.csproj
  5. 45
      src/Shentun.WebPeis.Application/WeChatHelper.cs
  6. 13
      src/Shentun.WebPeis.Domain.Shared/Enums/WeChatGrant.cs
  7. 220
      src/Shentun.WebPeis.Domain/Data/CustomerAuditPropertySetter.cs
  8. 2
      src/Shentun.WebPeis.Domain/Models/PatientRegister.cs
  9. 4
      src/Shentun.WebPeis.Domain/Models/Person.cs
  10. 4
      src/Shentun.WebPeis.Domain/Models/PersonKinship.cs
  11. 49
      src/Shentun.WebPeis.Domain/OpenIddict/OpenIddictDataSeedContributor.cs
  12. 4
      src/Shentun.WebPeis.EntityFrameworkCore/Configures/PatientRegisterConfigure.cs
  13. 6
      src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonConfigure.cs
  14. 6
      src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonKinshipConfigure.cs
  15. 27
      src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs
  16. 18
      src/Shentun.WebPeis.HttpApi.Host/WebPeisHttpApiHostModule.cs
  17. 4
      src/Shentun.WebPeis.HttpApi.Host/appsettings.json
  18. 12
      test/Shentun.WebPeis.Application.Tests/PersonAppServiceTest.cs

12
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; }
}
}

11
src/Shentun.WebPeis.Application/PatientRegisters/PatientRegisterAppService.cs

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Shentun.Utilities; using Shentun.Utilities;
@ -15,9 +16,10 @@ using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity; using Volo.Abp.Identity;
namespace Shentun.WebPeis.PatientRegisters namespace Shentun.WebPeis.PatientRegisters
{ {
[Authorize]
//[Authorize]
public class PatientRegisterAppService : ApplicationService public class PatientRegisterAppService : ApplicationService
{ {
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly IRepository<PatientRegister> _patientRegisterRepository; private readonly IRepository<PatientRegister> _patientRegisterRepository;
public PatientRegisterAppService(IRepository<PatientRegister> patientRegisterRepository, public PatientRegisterAppService(IRepository<PatientRegister> patientRegisterRepository,
@ -33,6 +35,7 @@ namespace Shentun.WebPeis.PatientRegisters
/// <param name="input"></param> /// <param name="input"></param>
/// <returns></returns> /// <returns></returns>
[HttpPost("api/app/PatientRegister/UploadReportBase64")] [HttpPost("api/app/PatientRegister/UploadReportBase64")]
[AllowAnonymous]
public async Task UploadReportBase64Async(TransReportInputDto input) public async Task UploadReportBase64Async(TransReportInputDto input)
{ {
var patientRegister = await _patientRegisterRepository.GetAsync(o=>o.PatientRegisterId == input.PatientRegisterId); var patientRegister = await _patientRegisterRepository.GetAsync(o=>o.PatientRegisterId == input.PatientRegisterId);
@ -58,8 +61,8 @@ namespace Shentun.WebPeis.PatientRegisters
var requestPath = virtualPathsHelper.GetReportRequestPath(); var requestPath = virtualPathsHelper.GetReportRequestPath();
var physicsPath = virtualPathsHelper.GetReportPhysicsPath(); 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; physicsPath = physicsPath + fileName;
File.Copy(tempPdf, physicsPath, true);//true允许覆盖 File.Copy(tempPdf, physicsPath, true);//true允许覆盖
patientRegister.ReportFile = requestPath + fileName; patientRegister.ReportFile = requestPath + fileName;
patientRegister.LastModifierId = new Guid("3a12a8a6-beb9-fc29-b4e7-4acfb00d8370");
patientRegister.LastModificationTime = DateTime.Now;
await _patientRegisterRepository.UpdateAsync(patientRegister); await _patientRegisterRepository.UpdateAsync(patientRegister);
} }

127
src/Shentun.WebPeis.Application/Persons/PersonAppService.cs

@ -16,17 +16,27 @@ using System.Security.Claims;
using System.Text.Json; using System.Text.Json;
using Volo.Abp.Identity; using Volo.Abp.Identity;
using Microsoft.AspNetCore.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 namespace Shentun.WebPeis.Persons
{ {
public class PersonAppService: ApplicationService
public class PersonAppService : ApplicationService
{ {
private SignInManager<Volo.Abp.Identity.IdentityUser> _signInManager;
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
private readonly IRepository<Volo.Abp.Identity.IdentityUser, Guid> _identityUserRepository;
private readonly IdentityUserManager _userManager; private readonly IdentityUserManager _userManager;
private readonly IRepository<Person> _repository; private readonly IRepository<Person> _repository;
public PersonAppService(IRepository<Person> repository, public PersonAppService(IRepository<Person> repository,
IConfiguration configuration, IConfiguration configuration,
IRepository<IdentityUser, Guid> identityUserRepository,
IRepository<Volo.Abp.Identity.IdentityUser, Guid> identityUserRepository,
IdentityUserManager userManager) IdentityUserManager userManager)
{ {
_repository = repository; _repository = repository;
@ -37,68 +47,81 @@ namespace Shentun.WebPeis.Persons
public async Task<PersonDto> GetByIdAsync(PersonIdInputDto input) public async Task<PersonDto> 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<Person, PersonDto>(entity); var entityDto = ObjectMapper.Map<Person, PersonDto>(entity);
return entityDto; return entityDto;
} }
public async Task<WechatUserDto> GetWechatUserAsync(WechatUserJsCodeInputDto input)
[HttpPost("api/app/Person/GetWechatUserTokenAsync")]
public async Task<UserTokenDto> 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<WechatSession>(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<string, object>
{ {
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<object>(tokenResultStr);
// }
//}
//else
//{
// if (string.IsNullOrEmpty(tokenResultStr))
// throw new BusinessException(tokenResult.ReasonPhrase);
//}
//return tokenResultStr;
}
} }

1
src/Shentun.WebPeis.Application/Shentun.WebPeis.Application.csproj

@ -19,6 +19,7 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Volo.Abp.Account.Application" Version="8.1.3" /> <PackageReference Include="Volo.Abp.Account.Application" Version="8.1.3" />
<PackageReference Include="Volo.Abp.Identity.Application" Version="8.1.3" /> <PackageReference Include="Volo.Abp.Identity.Application" Version="8.1.3" />
<PackageReference Include="Volo.Abp.OpenIddict.AspNetCore" Version="8.1.3" />
<PackageReference Include="Volo.Abp.PermissionManagement.Application" Version="8.1.3" /> <PackageReference Include="Volo.Abp.PermissionManagement.Application" Version="8.1.3" />
<PackageReference Include="Volo.Abp.TenantManagement.Application" Version="8.1.3" /> <PackageReference Include="Volo.Abp.TenantManagement.Application" Version="8.1.3" />
<PackageReference Include="Volo.Abp.FeatureManagement.Application" Version="8.1.3" /> <PackageReference Include="Volo.Abp.FeatureManagement.Application" Version="8.1.3" />

45
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<WechatSession> 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<WechatSession>(responseContent);
return wechatSession;
}
}
}
}

13
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<string> Scopes = ImmutableArray.Create("offline_access", "audience");
}
}

220
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
//{
//}
/// <summary>
/// 生成默认ID
/// </summary>
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<string>("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<string>("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();
}
}
}

2
src/Shentun.WebPeis.Domain/Models/PatientRegister.cs

@ -190,7 +190,7 @@ public partial class PatientRegister : AuditedEntity, IHasConcurrencyStamp
public string? HisPatientId { get; set; } public string? HisPatientId { get; set; }
public string? ThirdId { get; set; }
public string? ThirdRegisterId { get; set; }
public string? ReportFile { get; set; } public string? ReportFile { get; set; }

4
src/Shentun.WebPeis.Domain/Models/Person.cs

@ -10,7 +10,7 @@ namespace Shentun.WebPeis.Models;
/// </summary> /// </summary>
public partial class Person: AuditedEntity,IHasConcurrencyStamp public partial class Person: AuditedEntity,IHasConcurrencyStamp
{ {
public Guid PersonId { get; set; }
public Guid UserId { get; set; }
/// <summary> /// <summary>
/// 档案号 /// 档案号
@ -88,6 +88,6 @@ public partial class Person: AuditedEntity,IHasConcurrencyStamp
public override object?[] GetKeys() public override object?[] GetKeys()
{ {
return [PersonId];
return [UserId];
} }
} }

4
src/Shentun.WebPeis.Domain/Models/PersonKinship.cs

@ -5,9 +5,9 @@ namespace Shentun.WebPeis.Models;
public partial class PersonKinship 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!; public string KinshipId { get; set; } = null!;
} }

49
src/Shentun.WebPeis.Domain/OpenIddict/OpenIddictDataSeedContributor.cs

@ -1,12 +1,16 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Intrinsics.Arm;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using OpenIddict.Abstractions; using OpenIddict.Abstractions;
using Shentun.WebPeis.Enums;
using Volo.Abp; using Volo.Abp;
using Volo.Abp.Authorization.Permissions; using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Data; using Volo.Abp.Data;
@ -38,7 +42,7 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
IOpenIddictScopeRepository openIddictScopeRepository, IOpenIddictScopeRepository openIddictScopeRepository,
IOpenIddictScopeManager scopeManager, IOpenIddictScopeManager scopeManager,
IPermissionDataSeeder permissionDataSeeder, IPermissionDataSeeder permissionDataSeeder,
IStringLocalizer<OpenIddictResponse> l )
IStringLocalizer<OpenIddictResponse> l)
{ {
_configuration = configuration; _configuration = configuration;
_openIddictApplicationRepository = openIddictApplicationRepository; _openIddictApplicationRepository = openIddictApplicationRepository;
@ -60,8 +64,11 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
{ {
if (await _openIddictScopeRepository.FindByNameAsync("WebPeis") == null) 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 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<string> { WeChatGrant.GrantType, },
scopes: commonScopes,
redirectUri: $"{swaggerRootUrl}/swagger/oauth2-redirect.html",
clientUri: swaggerRootUrl
);
}
} }
private async Task CreateApplicationAsync( private async Task CreateApplicationAsync(
@ -130,7 +155,8 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
var client = await _openIddictApplicationRepository.FindByClientIdAsync(name); var client = await _openIddictApplicationRepository.FindByClientIdAsync(name);
var application = new AbpApplicationDescriptor {
var application = new AbpApplicationDescriptor
{
ClientId = name, ClientId = name,
ClientType = type, ClientType = type,
ClientSecret = secret, ClientSecret = secret,
@ -323,4 +349,19 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
{ {
return existingClient.Permissions == JsonSerializer.Serialize(application.Permissions.Select(q => q.ToString().TrimEnd('/'))); 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();
}
}
} }

4
src/Shentun.WebPeis.EntityFrameworkCore/Configures/PatientRegisterConfigure.cs

@ -174,10 +174,10 @@ namespace Shentun.WebPeis.Configures
.HasComment("附加第三方信息") .HasComment("附加第三方信息")
.HasColumnName("third_info"); .HasColumnName("third_info");
entity.Property(e => e.ThirdId)
entity.Property(e => e.ThirdRegisterId)
.HasMaxLength(40) .HasMaxLength(40)
.HasComment("第三方ID") .HasComment("第三方ID")
.HasColumnName("third_id");
.HasColumnName("third_register_id");
entity.Property(e => e.ReportFile) entity.Property(e => e.ReportFile)
.HasMaxLength(255) .HasMaxLength(255)

6
src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonConfigure.cs

@ -14,7 +14,7 @@ namespace Shentun.WebPeis.Configures
{ {
public void Configure(EntityTypeBuilder<Person> entity) public void Configure(EntityTypeBuilder<Person> entity)
{ {
entity.HasKey(e => e.PersonId).HasName("PK_patient");
entity.HasKey(e => e.UserId).HasName("PK_patient");
entity.ToTable("person", tb => tb.HasComment("体检人员档案")); 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.HasIndex(e => e.IdNo, "ix_person_id_no").IsUnique();
entity.Property(e => e.PersonId)
entity.Property(e => e.UserId)
.ValueGeneratedNever() .ValueGeneratedNever()
.HasColumnName("person_id");
.HasColumnName("user_id");
entity.Property(e => e.Address) entity.Property(e => e.Address)
.HasMaxLength(100) .HasMaxLength(100)
.HasComment("地址") .HasComment("地址")

6
src/Shentun.WebPeis.EntityFrameworkCore/Configures/PersonKinshipConfigure.cs

@ -14,12 +14,12 @@ namespace Shentun.WebPeis.Configures
{ {
public void Configure(EntityTypeBuilder<PersonKinship> entity) public void Configure(EntityTypeBuilder<PersonKinship> 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.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) entity.Property(e => e.KinshipId)
.HasMaxLength(2) .HasMaxLength(2)
.IsFixedLength() .IsFixedLength()

27
src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs

@ -18,9 +18,12 @@ using OpenIddict.Server.AspNetCore;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using System.Collections.Generic;
using IdentityModel;
namespace Shentun.WebPeis.Controllers namespace Shentun.WebPeis.Controllers
{ {
//[IgnoreAntiforgeryToken] //[IgnoreAntiforgeryToken]
//[ApiExplorerSettings(IgnoreApi = true)] //[ApiExplorerSettings(IgnoreApi = true)]
public class WeChatController : AbpOpenIdDictControllerBase, ITokenExtensionGrant 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 person = (await _personRepository.GetQueryableAsync()).Where(o => o.WechatOpenId == wechatSession.OpenId).FirstOrDefault();
var wechatUser = new WechatUserDto(); var wechatUser = new WechatUserDto();
var principal = new ClaimsPrincipal();
var claimsIdentity = new ClaimsIdentity();
if (person == null) if (person == null)
{ {
claimsIdentity.AddClaim(new Claim("IsNewUser", "N"));
claimsIdentity.AddClaim(new Claim("OpenId", wechatSession.OpenId));
wechatUser.IsNewUser = true; 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); claimsIdentity.AddClaim(claim);
principal.AddIdentity(claimsIdentity); principal.AddIdentity(claimsIdentity);
principal.AddClaim("PersonId", person.PersonId.ToString());//测试
var scopes = context.Request.GetScopes(); var scopes = context.Request.GetScopes();
principal.SetScopes(scopes); principal.SetScopes(scopes);
var resources = await GetResourcesAsync(scopes); var resources = await GetResourcesAsync(scopes);
principal.SetResources(resources); principal.SetResources(resources);
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
} }
//public async Task<IActionResult> CreateAsync()
//{
//}
private async Task<WechatSession> GetWechatSession(string jsCode) private async Task<WechatSession> GetWechatSession(string jsCode)
{ {

18
src/Shentun.WebPeis.HttpApi.Host/WebPeisHttpApiHostModule.cs

@ -36,6 +36,11 @@ using Shentun.Utilities;
using Volo.Abp.Json; using Volo.Abp.Json;
using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders;
using Shentun.WebPeis.VirtualPaths; 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; namespace Shentun.WebPeis;
@ -63,6 +68,14 @@ public class WebPeisHttpApiHostModule : AbpModule
options.UseAspNetCore(); options.UseAspNetCore();
}); });
}); });
PreConfigure<OpenIddictServerBuilder>(builder =>
{
//Ìí¼Ó×Ô¶¨ÒåITokenExtensionGrant
builder.Configure(openIddictServerOptions =>
{
openIddictServerOptions.GrantTypes.Add(WeChatGrant.GrantType);
});
});
} }
public override void ConfigureServices(ServiceConfigurationContext context) public override void ConfigureServices(ServiceConfigurationContext context)
@ -102,6 +115,11 @@ public class WebPeisHttpApiHostModule : AbpModule
x.InputDateTimeFormats.Add( "yyyy-MM-dd HH:mm:ss"); x.InputDateTimeFormats.Add( "yyyy-MM-dd HH:mm:ss");
x.OutputDateTimeFormat = "yyyy-MM-dd HH:mm:ss"; x.OutputDateTimeFormat = "yyyy-MM-dd HH:mm:ss";
}); });
context.Services.AddSingleton<WeChatController>();
Configure<AbpOpenIddictExtensionGrantsOptions>(options =>
{
options.Grants.Add(WeChatGrant.GrantType, (IExtensionGrant)context.Services.GetServiceLazy<WeChatController>());
});
//context.Services.AddSingleton(new MyFileProvider(configuration["VirtualPath:PhysicsPath"], configuration["VirtualPath:Alias"])); //context.Services.AddSingleton(new MyFileProvider(configuration["VirtualPath:PhysicsPath"], configuration["VirtualPath:Alias"]));
} }

4
src/Shentun.WebPeis.HttpApi.Host/appsettings.json

@ -21,7 +21,9 @@
"AuthServer": { "AuthServer": {
"Authority": "https://localhost:44382", "Authority": "https://localhost:44382",
"RequireHttpsMetadata": false, "RequireHttpsMetadata": false,
"SwaggerClientId": "WebPeis_Swagger"
"SwaggerClientId": "WebPeis_Swagger",
"WeChatClientId": "WeChatApp",
"WeChatClientSecret": "1234*^@"
}, },
"StringEncryption": { "StringEncryption": {
"DefaultPassPhrase": "rBfozS7zkeTYat2k" "DefaultPassPhrase": "rBfozS7zkeTYat2k"

12
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
{
}
}
Loading…
Cancel
Save