Browse Source

签名

master
DESKTOP-G961P6V\Zhh 2 years ago
parent
commit
8862071e82
  1. 16
      src/Shentun.WebPeis.Application.Contracts/WebApiOutDto.cs
  2. 99
      src/Shentun.WebPeis.Application/Persons/PersonAppService.cs
  3. 49
      src/Shentun.WebPeis.Application/WeChatHelper.cs
  4. 5
      src/Shentun.WebPeis.DbMigrator/appsettings.json
  5. 29
      src/Shentun.WebPeis.Domain/OpenIddict/OpenIddictDataSeedContributor.cs
  6. 2
      src/Shentun.WebPeis.EntityFrameworkCore/EntityFrameworkCore/数据库模型代码生成.txt
  7. 6856
      src/Shentun.WebPeis.EntityFrameworkCore/Migrations/20240523080624_updatePerson.Designer.cs
  8. 228
      src/Shentun.WebPeis.EntityFrameworkCore/Migrations/20240523080624_updatePerson.cs
  9. 34
      src/Shentun.WebPeis.EntityFrameworkCore/Migrations/WebPeisDbContextModelSnapshot.cs
  10. 176
      src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs
  11. 11
      src/Shentun.WebPeis.HttpApi.Host/Filters/CustomerActionFilterAttribute.cs
  12. 43
      src/Shentun.WebPeis.HttpApi.Host/WebPeisHttpApiHostModule.cs
  13. 6
      src/Shentun.WebPeis.HttpApi.Host/appsettings.json
  14. 41
      test/Shentun.WebPeis.Application.Tests/PersonAppServiceTest.cs
  15. 24
      test/Shentun.WebPeis.Application.Tests/Shentun.WebPeis.Application.Tests.csproj
  16. 5
      test/Shentun.WebPeis.Application.Tests/WebPeisApplicationTestBase.cs
  17. 2
      test/Shentun.WebPeis.Application.Tests/appsettings.Development.json
  18. 43
      test/Shentun.WebPeis.Application.Tests/appsettings.json
  19. 2
      test/Shentun.WebPeis.Application.Tests/appsettings.secrets.json
  20. 12
      test/Shentun.WebPeis.EntityFrameworkCore.Tests/EntityFrameworkCore/Applications/EfCorePersonAppServiceTest.cs
  21. 18
      test/Shentun.WebPeis.EntityFrameworkCore.Tests/EntityFrameworkCore/WebPeisEntityFrameworkCoreTestModule.cs
  22. 2
      test/Shentun.WebPeis.TestBase/WebPeisTestBaseModule.cs

16
src/Shentun.WebPeis.Application.Contracts/WebApiOutDto.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shentun.WebPeis
{
public class WebApiOutDto<T>
{
public int Code { get; set; }
public string Message { get; set; }
public T? Data { get; set; }
}
}

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

@ -24,6 +24,7 @@ using System.Net.Http.Headers;
using IdentityModel.Client;
using static Volo.Abp.Identity.Settings.IdentitySettingNames;
using Microsoft.AspNetCore.Mvc;
using OpenIddict.Abstractions;
namespace Shentun.WebPeis.Persons
{
@ -56,70 +57,94 @@ namespace Shentun.WebPeis.Persons
[HttpPost("api/app/Person/GetWechatUserTokenAsync")]
public async Task<UserTokenDto> GetWechatUserTokenAsync(WechatUserJsCodeInputDto input)
{
var wechatSession = await WeChatHelper.GetWechatSession(_configuration, input.JsCode);
if (wechatSession == null)
{
throw new Exception("微信会话返回空值");
}
if (wechatSession.ErrCode != 0)
{
throw new Exception("微信账户登陆失败");
}
//var wechatSession = await WeChatHelper.GetWechatSession(_configuration, input.JsCode);
//if (wechatSession == null)
//{
// throw new Exception("微信会话返回空值");
//}
//if (wechatSession.ErrCode != 0)
//{
// throw new Exception("微信账户登陆失败");
//}
var client = new HttpClient();
var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value;
var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value;
var commonScopes = new List<string> {
OpenIddictConstants.Permissions.Scopes.Address,
OpenIddictConstants.Permissions.Scopes.Email,
OpenIddictConstants.Permissions.Scopes.Phone,
OpenIddictConstants.Permissions.Scopes.Profile,
OpenIddictConstants.Permissions.Scopes.Roles,
"WebPeis"
};
var dic = new Dictionary<string, object>
{
{"jsCode",input.JsCode},
{"client_id",weChatClientId},
{"client_secret",secret},
//{"client_secret",secret},
{"grant_type",WeChatGrant.GrantType},
{"scope","WebPeis"},
};
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 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(_configuration.GetSection("AuthServer").
GetSection("Authority").Value + "/connect/token"
, httpContent);
var tokenResultStr = await tokenResult.Content.ReadAsStringAsync();
if (tokenResult.IsSuccessStatusCode)
{
if (!string.IsNullOrEmpty(tokenResultStr))
{
var signResult = JsonSerializer.Deserialize<WebApiOutDto<object>>(tokenResultStr,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
var userTokenDto = new UserTokenDto
{
AccessToken = token.AccessToken,
RefreshToken = token.RefreshToken
//AccessToken = tokenResponse.AccessToken,
// RefreshToken = tokenResponse.RefreshToken
};
return userTokenDto;
}
else
{
//msg = new UserLoginDto { code = 1, msg = "登录成功", peisid = PeisId };
throw new UserFriendlyException("获取token失败");
if (string.IsNullOrEmpty(tokenResultStr))
throw new BusinessException(tokenResult.ReasonPhrase);
}
return new UserTokenDto();
//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)
//var tokenRequest = new TokenRequest()
//{
// Address = _configuration.GetSection("AuthServer").GetSection("Authority").Value + "/connect/token",
// ClientId = weChatClientId,
// //ClientSecret = secret,
// GrantType = WeChatGrant.GrantType
//};
//var tokenResponse = await client.RequestTokenAsync(tokenRequest);
//if (tokenResponse.HttpResponse != null && tokenResponse.HttpResponse.StatusCode == HttpStatusCode.OK)
//{
// if (!string.IsNullOrEmpty(tokenResultStr))
// var userTokenDto = new UserTokenDto
// {
// dynamic signResult = JsonSerializer.Deserialize<object>(tokenResultStr);
// }
// AccessToken = tokenResponse.AccessToken,
// RefreshToken = tokenResponse.RefreshToken
// };
// return userTokenDto;
//}
//else
//{
// if (string.IsNullOrEmpty(tokenResultStr))
// throw new BusinessException(tokenResult.ReasonPhrase);
// //msg = new UserLoginDto { code = 1, msg = "登录成功", peisid = PeisId };
// throw new UserFriendlyException("获取token失败");
//}
//return tokenResultStr;

49
src/Shentun.WebPeis.Application/WeChatHelper.cs

@ -1,4 +1,5 @@
using Microsoft.Extensions.Configuration;
using NUglify.Helpers;
using Shentun.WebPeis.Wechats;
using System;
using System.Collections.Generic;
@ -15,11 +16,31 @@ namespace Shentun.WebPeis
{
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", "");
if (string.IsNullOrWhiteSpace(jsCode))
{
throw new Exception("jsCode不能为空");
}
IConfigurationSection configSection = configSection1.GetSection("WeChat");
if (configSection == null)
{
throw new Exception("微信配置不能为空");
}
string url = configSection.GetValue("SessionUrl", "https://api.weixin.qq.com/sns/jscode2session?");
string appId = configSection.GetValue("AppID", "");
string appSecret = configSection.GetValue("AppSecret", "");
if (string.IsNullOrWhiteSpace(url))
{
throw new Exception("微信url不能为空");
}
if (string.IsNullOrWhiteSpace(appId))
{
throw new Exception("微信appId不能为空");
}
if (string.IsNullOrWhiteSpace(appSecret))
{
throw new Exception("微信appSecret不能为空");
}
url = url + "appid=" + appId + "&secret=" + appSecret + "&js_code=" + jsCode + "&grant_type=authorization_code";
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
@ -37,7 +58,23 @@ namespace Shentun.WebPeis
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
string responseContent = await responseResult.Content.ReadAsStringAsync();
var wechatSession = JsonSerializer.Deserialize<WechatSession>(responseContent);
var wechatSession = JsonSerializer.Deserialize<WechatSession>(responseContent,
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true}
);
if (wechatSession == null)
{
throw new Exception("获取微信小程序wechatSession为空");
}
if (wechatSession.ErrCode != 0)
{
wechatSession.OpenId = "obZGv5RhSNxxpkDwT0Xaf9Fzn8NM";
wechatSession.SessionKey = "O+VJ49EHaPLR5+oOjsG0xA==";
//throw new Exception("微信账户登陆失败"+ wechatSession.ErrMsg);
}
if (string.IsNullOrWhiteSpace(wechatSession.OpenId))
{
throw new Exception("微信账户OpenId不能为空");
}
return wechatSession;
}
}

5
src/Shentun.WebPeis.DbMigrator/appsettings.json

@ -24,6 +24,11 @@
"WebPeis_Swagger": {
"ClientId": "WebPeis_Swagger",
"RootUrl": "https://localhost:44382"
},
"WeChatApp": {
"ClientId": "WeChatApp",
"ClientSecret": "1q2w3e*",
"RootUrl": "https://localhost:44345"
}
}
}

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

@ -108,9 +108,14 @@ 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);
var weChatClientId = configurationSection.GetSection("WeChatApp").GetSection("ClientId").Value;
var secret = configurationSection.GetSection("WeChatApp").GetSection("ClientSecret").Value;
if(string.IsNullOrWhiteSpace(secret))
{
throw new Exception("secret不能为空");
}
//secret = GetSha256Hash(secret);
secret = null;
if (!string.IsNullOrWhiteSpace(weChatClientId))
{
var swaggerRootUrl = configurationSection["WebPeis_Swagger:RootUrl"]?.TrimEnd('/');
@ -120,7 +125,14 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
consentType: OpenIddictConstants.ConsentTypes.Implicit,
displayName: "WeChat Application",
secret: secret,
grantTypes: new List<string> { WeChatGrant.GrantType, },
grantTypes: new List<string>
{
OpenIddictConstants.GrantTypes.AuthorizationCode,
OpenIddictConstants.GrantTypes.Password,
OpenIddictConstants.GrantTypes.ClientCredentials,
OpenIddictConstants.GrantTypes.RefreshToken,
WeChatGrant.GrantType
},
scopes: commonScopes,
redirectUri: $"{swaggerRootUrl}/swagger/oauth2-redirect.html",
clientUri: swaggerRootUrl
@ -354,14 +366,9 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
{
using (SHA256 sha256Hash = SHA256.Create())
{
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
byte[] bytes = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(((HashAlgorithm)sha256Hash).ComputeHash(bytes));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
}

2
src/Shentun.WebPeis.EntityFrameworkCore/EntityFrameworkCore/数据库模型代码生成.txt

@ -20,3 +20,5 @@ Scaffold-DbContext "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.16
Scaffold-DbContext "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.6.3)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User ID=system;Password=manager;" -Provider OraOLEDB.Oracle.1 -Project Shentun.ArmyHis.Models -Force -Tables INSURANCE.HEALTH_VS_PATIENT
Scaffold-DbContext "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.8.2)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User ID=system;Password=admin513;" -Provider OraOLEDB.Oracle -Project Shentun.ArmyHis.Models -Force -Tables INPBILL.INP_BILL_DETAIL
Scaffold-DbContext "Provider=MSDAORA;Persist Security Info=True;User ID=system;Password=manager;Data Source=dbserver943_test;" -Provider MSDAORA -Project Shentun.ArmyHis.Models -Force -Tables EXAM.EXAM_MASTER
--- ʵÌåÀà³õʼ»¯Óï¾ä
Add-Migration Init

6856
src/Shentun.WebPeis.EntityFrameworkCore/Migrations/20240523080624_updatePerson.Designer.cs
File diff suppressed because it is too large
View File

228
src/Shentun.WebPeis.EntityFrameworkCore/Migrations/20240523080624_updatePerson.cs

@ -1,228 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Shentun.WebPeis.Migrations
{
/// <inheritdoc />
public partial class updatePerson : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "ix_person_name",
table: "person");
migrationBuilder.DropColumn(
name: "email",
table: "person");
migrationBuilder.DropColumn(
name: "is_active",
table: "person");
migrationBuilder.DropColumn(
name: "mobile_telephone",
table: "person");
migrationBuilder.DropColumn(
name: "password_hash",
table: "person");
migrationBuilder.DropColumn(
name: "person_name",
table: "person");
migrationBuilder.AlterColumn<string>(
name: "nation_id",
table: "person",
type: "text",
nullable: false,
defaultValue: "",
comment: "民族编号",
oldClrType: typeof(string),
oldType: "text",
oldNullable: true,
oldComment: "民族编号");
migrationBuilder.AlterColumn<char>(
name: "is_allow_bind",
table: "person",
type: "character(1)",
maxLength: 1,
nullable: false,
defaultValue: '\0',
oldClrType: typeof(char),
oldType: "character(1)",
oldMaxLength: 1,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "id_type_id",
table: "person",
type: "character(2)",
fixedLength: true,
maxLength: 2,
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "character(2)",
oldFixedLength: true,
oldMaxLength: 2,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "id_no",
table: "person",
type: "character varying(18)",
maxLength: 18,
nullable: false,
defaultValue: "",
comment: "身份证号",
oldClrType: typeof(string),
oldType: "character varying(18)",
oldMaxLength: 18,
oldNullable: true,
oldComment: "身份证号");
migrationBuilder.AlterColumn<string>(
name: "country_code",
table: "person",
type: "character varying(3)",
maxLength: 3,
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "character varying(3)",
oldMaxLength: 3,
oldNullable: true);
migrationBuilder.AlterColumn<DateTime>(
name: "birth_date",
table: "person",
type: "timestamp(6) without time zone",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
comment: "出生日期",
oldClrType: typeof(DateTime),
oldType: "timestamp(6) without time zone",
oldNullable: true,
oldComment: "出生日期");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "nation_id",
table: "person",
type: "text",
nullable: true,
comment: "民族编号",
oldClrType: typeof(string),
oldType: "text",
oldComment: "民族编号");
migrationBuilder.AlterColumn<char>(
name: "is_allow_bind",
table: "person",
type: "character(1)",
maxLength: 1,
nullable: true,
oldClrType: typeof(char),
oldType: "character(1)",
oldMaxLength: 1);
migrationBuilder.AlterColumn<string>(
name: "id_type_id",
table: "person",
type: "character(2)",
fixedLength: true,
maxLength: 2,
nullable: true,
oldClrType: typeof(string),
oldType: "character(2)",
oldFixedLength: true,
oldMaxLength: 2);
migrationBuilder.AlterColumn<string>(
name: "id_no",
table: "person",
type: "character varying(18)",
maxLength: 18,
nullable: true,
comment: "身份证号",
oldClrType: typeof(string),
oldType: "character varying(18)",
oldMaxLength: 18,
oldComment: "身份证号");
migrationBuilder.AlterColumn<string>(
name: "country_code",
table: "person",
type: "character varying(3)",
maxLength: 3,
nullable: true,
oldClrType: typeof(string),
oldType: "character varying(3)",
oldMaxLength: 3);
migrationBuilder.AlterColumn<DateTime>(
name: "birth_date",
table: "person",
type: "timestamp(6) without time zone",
nullable: true,
comment: "出生日期",
oldClrType: typeof(DateTime),
oldType: "timestamp(6) without time zone",
oldComment: "出生日期");
migrationBuilder.AddColumn<string>(
name: "email",
table: "person",
type: "character varying(50)",
maxLength: 50,
nullable: true,
comment: "email");
migrationBuilder.AddColumn<char>(
name: "is_active",
table: "person",
type: "character(1)",
maxLength: 1,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "mobile_telephone",
table: "person",
type: "character varying(50)",
maxLength: 50,
nullable: true,
comment: "手机号");
migrationBuilder.AddColumn<string>(
name: "password_hash",
table: "person",
type: "character varying(10)",
maxLength: 10,
nullable: true,
comment: "登录密码");
migrationBuilder.AddColumn<string>(
name: "person_name",
table: "person",
type: "character varying(30)",
maxLength: 30,
nullable: false,
defaultValue: "",
comment: "姓名");
migrationBuilder.CreateIndex(
name: "ix_person_name",
table: "person",
column: "person_name");
}
}
}

34
src/Shentun.WebPeis.EntityFrameworkCore/Migrations/WebPeisDbContextModelSnapshot.cs

@ -2194,7 +2194,7 @@ namespace Shentun.WebPeis.Migrations
.HasColumnType("timestamp(6) without time zone")
.HasColumnName("creation_time");
b.Property<Guid>("CreatorId")
b.Property<Guid?>("CreatorId")
.HasColumnType("uuid")
.HasColumnName("creator_id");
@ -2266,11 +2266,11 @@ namespace Shentun.WebPeis.Migrations
.HasColumnName("job_title")
.HasComment("职称");
b.Property<DateTime>("LastModificationTime")
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("timestamp(6) without time zone")
.HasColumnName("last_modification_time");
b.Property<Guid>("LastModifierId")
b.Property<Guid?>("LastModifierId")
.HasColumnType("uuid")
.HasColumnName("last_modifier_id");
@ -2356,6 +2356,12 @@ namespace Shentun.WebPeis.Migrations
.HasColumnName("remark")
.HasComment("备注");
b.Property<string>("ReportFile")
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("report_file")
.HasComment("体检报告文件");
b.Property<Guid?>("SexHormoneTermId")
.HasColumnType("uuid")
.HasColumnName("sex_hormone_term_id")
@ -2385,6 +2391,12 @@ namespace Shentun.WebPeis.Migrations
.HasColumnName("third_info")
.HasComment("附加第三方信息");
b.Property<string>("ThirdRegisterId")
.HasMaxLength(40)
.HasColumnType("character varying(40)")
.HasColumnName("third_register_id")
.HasComment("第三方ID");
b.HasKey("PatientRegisterId")
.HasName("pk_patient_register");
@ -2458,9 +2470,9 @@ namespace Shentun.WebPeis.Migrations
modelBuilder.Entity("Shentun.WebPeis.Models.Person", b =>
{
b.Property<Guid>("PersonId")
b.Property<Guid>("UserId")
.HasColumnType("uuid")
.HasColumnName("person_id");
.HasColumnName("user_id");
b.Property<string>("Address")
.HasMaxLength(100)
@ -2578,7 +2590,7 @@ namespace Shentun.WebPeis.Migrations
.HasColumnType("character varying(50)")
.HasColumnName("wechat_open_id");
b.HasKey("PersonId")
b.HasKey("UserId")
.HasName("pk_patient");
b.HasIndex(new[] { "PersonNo" }, "IX_person_person_no")
@ -2595,13 +2607,13 @@ namespace Shentun.WebPeis.Migrations
modelBuilder.Entity("Shentun.WebPeis.Models.PersonKinship", b =>
{
b.Property<Guid>("PersonId")
b.Property<Guid>("UserId")
.HasColumnType("uuid")
.HasColumnName("person_id");
.HasColumnName("user_id");
b.Property<Guid>("ParentPersonId")
b.Property<Guid>("ParentUserId")
.HasColumnType("uuid")
.HasColumnName("parent_person_id");
.HasColumnName("parent_user_id");
b.Property<string>("KinshipId")
.HasMaxLength(2)
@ -2609,7 +2621,7 @@ namespace Shentun.WebPeis.Migrations
.HasColumnName("kinship_id")
.IsFixedLength();
b.HasKey("PersonId", "ParentPersonId", "KinshipId")
b.HasKey("UserId", "ParentUserId", "KinshipId")
.HasName("person_kinship_pkey");
b.ToTable("person_kinship", (string)null);

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

@ -20,25 +20,33 @@ using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.DependencyInjection;
using System.Collections.Generic;
using IdentityModel;
using Shentun.WebPeis.Enums;
using Microsoft.AspNetCore.Authentication.Cookies;
using Volo.Abp.Security.Claims;
namespace Shentun.WebPeis.Controllers
{
//[IgnoreAntiforgeryToken]
//[ApiExplorerSettings(IgnoreApi = true)]
public class WeChatController : AbpOpenIdDictControllerBase, ITokenExtensionGrant
public interface IWeChatController
{
}
[IgnoreAntiforgeryToken]
[ApiExplorerSettings(IgnoreApi = true)]
public class WeChatController : AbpOpenIdDictControllerBase, ITokenExtensionGrant, IWeChatController
{
private readonly IConfiguration _configuration;
private readonly IRepository<Person> _personRepository;
private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
private readonly IdentityUserManager _userManager;
public string Name => throw new System.NotImplementedException();
public string Name => WeChatGrant.GrantType;
public WeChatController(IConfiguration configuration,
IRepository<IdentityUser, Guid> identityUserRepository,
IdentityUserManager userManager,
IRepository<Person> personRepository)
{
_configuration = configuration;
_identityUserRepository = identityUserRepository;
_userManager = userManager;
@ -47,76 +55,138 @@ namespace Shentun.WebPeis.Controllers
public async Task<IActionResult> HandleAsync(ExtensionGrantContext context)
{
LazyServiceProvider = context.HttpContext.RequestServices.GetRequiredService<IAbpLazyServiceProvider>();
//LazyServiceProvider = context.HttpContext.RequestServices.GetRequiredService<IAbpLazyServiceProvider>();
//var request = await GetOpenIddictServerRequestAsync(HttpContext);
string jsCode = context.Request.GetParameter("jsCode").ToString();
var wechatSession = await GetWechatSession(jsCode);
if (wechatSession == null)
if(_configuration == null)
{
throw new Exception("微信会话返回空值");
throw new Exception("_configuration不能为空");
}
if (wechatSession.ErrCode != 0)
if (context.Request.GetParameter("jsCode") == null)
{
throw new Exception("微信账户登陆失败");
throw new Exception("jsCode不能为空");
}
string jsCode = context.Request.GetParameter("jsCode").ToString();
var wechatSession = await WeChatHelper.GetWechatSession(_configuration, jsCode);
//var wechatSession = await GetWechatSession(jsCode);
//if (wechatSession == null)
//{
// throw new Exception("微信会话返回空值");
//}
//if (wechatSession.ErrCode != 0)
//{
// throw new Exception("微信账户登陆失败");
//}
if (_personRepository == null)
{
throw new Exception("_personRepository不能为空");
}
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;
principal.AddIdentity(claimsIdentity);
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.UserId).Single();
var claimsIdentity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
var scopes = context.Request.GetScopes();
var resources = await GetResourcesAsync(scopes);
//if (person == null)
//{
// claimsIdentity.AddClaim(new Claim(ClaimTypes.Sid, "无效"));
// claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "无效"));
// claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "无效"));
// claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, "无效"));
// claimsIdentity.AddClaim(new Claim("IsNewUser", "N"));
// claimsIdentity.AddClaim(new Claim("OpenId", wechatSession.OpenId));
// wechatUser.IsNewUser = true;
// principal.AddIdentity(claimsIdentity);
// principal.SetScopes(scopes);
// principal.SetResources(resources);
// return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
//}
var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.UserName == "admin").FirstOrDefault();
//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);
var scopes = context.Request.GetScopes();
//var claim = new Claim("IsNewUser","N");
//claimsIdentity.AddClaim(claim);
//principal.AddIdentity(claimsIdentity);
principal.SetScopes(scopes);
var resources = await GetResourcesAsync(scopes);
principal.SetResources(resources);
principal.SetResources(resources);
if (principal == null)
{
throw new Exception("principal不能为空");
}
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
private async Task<WechatSession> GetWechatSession(string jsCode)
{
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", "");
//private async Task<WechatSession> GetWechatSession(string jsCode)
//{
// if (string.IsNullOrWhiteSpace(jsCode))
// {
// throw new Exception("jsCode不能为空");
// }
// IConfigurationSection configSection = _configuration.GetSection("WeChat");
// if (configSection == null)
// {
// throw new Exception("微信配置不能为空");
// }
// string url = configSection.GetValue("SessionUrl", "https://api.weixin.qq.com/sns/jscode2session?");
// string appId = configSection.GetValue("AppID", "");
// string appSecret = configSection.GetValue("AppSecret", "");
// if (string.IsNullOrWhiteSpace(url))
// {
// throw new Exception("微信url不能为空");
// }
// if (string.IsNullOrWhiteSpace(appId))
// {
// throw new Exception("微信appId不能为空");
// }
// if (string.IsNullOrWhiteSpace(appSecret))
// {
// throw new Exception("微信appSecret不能为空");
// }
// url = url + "appid=" + appId + "&secret=" + appSecret + "&js_code=" + jsCode + "&grant_type=authorization_code";
// var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
url = url + "appid=" + appId + "&secret=" + appSecret + "&js_code=" + jsCode + "&grant_type=authorization_code";
// using (var httpClient = new HttpClient(handler))
// {
// //await异步等待回应
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
// var responseResult = await httpClient.GetAsync(url);
// //确保HTTP成功状态值
// if (!responseResult.IsSuccessStatusCode)
// {
// throw new Exception("获取微信小程序数据失败," + responseResult.StatusCode);
// }
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;
}
}
// //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
// string responseContent = await responseResult.Content.ReadAsStringAsync();
// var wechatSession = JsonSerializer.Deserialize<WechatSession>(responseContent);
// if(wechatSession == null)
// {
// throw new Exception("获取微信小程序wechatSession为空");
// }
// if (wechatSession.ErrCode != 0)
// {
// throw new Exception("微信账户登陆失败");
// }
// return wechatSession;
// }
//}
}
}

11
src/Shentun.WebPeis.HttpApi.Host/Filters/CustomerActionFilterAttribute.cs

@ -53,18 +53,13 @@ namespace Shentun.WebPeis
else
{
List<string> filterApiUrl = new List<string> { "/api/third/thirdpartypublicinterface/getpatientitems" };
List<string> filterApiUrl = new List<string> { "/connect/token" };
if (filterApiUrl.Contains(context.HttpContext.Request.Path.ToString().ToLower()))
{
ThirdReturn msg = new ThirdReturn
{
code = "200",
message = "处理成功",
data = result.Value
};
context.Result = new OkObjectResult(msg);
context.Result = result;
}
else
{

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

@ -41,6 +41,9 @@ using Volo.Abp.OpenIddict.ExtensionGrantTypes;
using OpenIddict.Server;
using Shentun.WebPeis.Controllers;
using Autofac.Core;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore.Internal;
using Volo.Abp.OpenIddict;
namespace Shentun.WebPeis;
@ -76,6 +79,11 @@ public class WebPeisHttpApiHostModule : AbpModule
openIddictServerOptions.GrantTypes.Add(WeChatGrant.GrantType);
});
});
//context.Services.PreConfigure<AbpOpenIddictAspNetCoreOptions>(options =>
//{
// options.UpdateAbpClaimTypes = false;
//});
}
public override void ConfigureServices(ServiceConfigurationContext context)
@ -112,14 +120,41 @@ public class WebPeisHttpApiHostModule : AbpModule
//});
Configure<AbpJsonOptions>(x =>
{
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";
});
context.Services.AddSingleton<WeChatController>();
Configure<AbpOpenIddictExtensionGrantsOptions>(options =>
Configure<JsonOptions>(x =>
{
options.Grants.Add(WeChatGrant.GrantType, (IExtensionGrant)context.Services.GetServiceLazy<WeChatController>());
x.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
// context.Services.AddTransient<WeChatController>();
//Configure<AbpOpenIddictExtensionGrantsOptions>(options =>
//{
// //options.Grants.Add(WeChatGrant.GrantType, (IExtensionGrant)context.Services.GetServiceLazy<WeChatController>());
// options.Grants.Add(WeChatGrant.GrantType, serviceProvider.GetRequiredService<WeChatController>());
//});
context.Services.AddOptions<AbpOpenIddictExtensionGrantsOptions>()
.Configure<IServiceProvider>((options, serviceProvider) =>
{
options.Grants.Add(WeChatGrant.GrantType, serviceProvider.GetRequiredService<WeChatController>());
});
// context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
//.AddJwtBearer(options =>
//{
// options.Authority = configuration["AuthServer:Authority"];
// options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
// options.Audience = "BookStore2";
// options.MapInboundClaims = false;
//});
//context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// .AddJwtBearer(
// options =>
// {
// options.MapInboundClaims = false;
// });
//context.Services.AddSingleton(new MyFileProvider(configuration["VirtualPath:PhysicsPath"], configuration["VirtualPath:Alias"]));
}

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

@ -28,10 +28,10 @@
"StringEncryption": {
"DefaultPassPhrase": "rBfozS7zkeTYat2k"
},
"Wechat": {
"WeChat": {
"SessionUrl": "https://api.weixin.qq.com/sns/jscode2session?", //访URL
"AppID": "wx7532a29e2c51f70b", //AppID
"AppSecret": "6a26f526c5436086cd93787d7435acb9" //AppSecret
"AppID": "wx6a8a4440a42c9466", //AppID
"AppSecret": "aae34bfef498906290a92318d0f7183d" //AppSecret
},
"VirtualPaths": [
{

41
test/Shentun.WebPeis.Application.Tests/PersonAppServiceTest.cs

@ -1,12 +1,49 @@
using System;
using Shentun.WebPeis.Models;
using Shentun.WebPeis.Persons;
using Shentun.WebPeis.Wechats;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Modularity;
using Volo.Abp.Uow;
using Xunit;
using Xunit.Abstractions;
namespace Shentun.WebPeis
{
internal class PersonAppServiceTest
public abstract class PersonAppServiceTest<TStartupModule> : WebPeisApplicationTestBase<TStartupModule>
where TStartupModule : IAbpModule
{
private readonly IRepository<Person> _repository;
private readonly PersonAppService _appService;
//private readonly ITestOutputHelper _output;
private readonly IUnitOfWorkManager _unitOfWorkManager;
public PersonAppServiceTest()
{
//ITestOutputHelper testOutputHelper
//_output = testOutputHelper;
_unitOfWorkManager = GetRequiredService<IUnitOfWorkManager>();
_repository = GetRequiredService<IRepository<Person>>();
_appService = GetRequiredService<PersonAppService>();
//_output = GetRequiredService<ITestOutputHelper>();
}
[Fact]
public async Task GetWechatUserTokenAsync()
{
using (var unitOfWork = _unitOfWorkManager.Begin(isTransactional: true))
{
var entity = new WechatUserJsCodeInputDto()
{
JsCode = "0c1yTa0w3mErQ23eot3w3ocsxw4yTa0P"
};
var newEntity = await _appService.GetWechatUserTokenAsync(entity);
await unitOfWork.CompleteAsync();
}
}
}
}

24
test/Shentun.WebPeis.Application.Tests/Shentun.WebPeis.Application.Tests.csproj

@ -8,6 +8,30 @@
<RootNamespace>Shentun.WebPeis</RootNamespace>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
<None Remove="appsettings.secrets.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="appsettings.secrets.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Shentun.WebPeis.Application\Shentun.WebPeis.Application.csproj" />
<ProjectReference Include="..\Shentun.WebPeis.Domain.Tests\Shentun.WebPeis.Domain.Tests.csproj" />

5
test/Shentun.WebPeis.Application.Tests/WebPeisApplicationTestBase.cs

@ -7,3 +7,8 @@ public abstract class WebPeisApplicationTestBase<TStartupModule> : WebPeisTestBa
{
}
//public abstract class WebPeisApplicationTestBase : WebPeisTestBase<WebPeisApplicationTestModule>
//{
//}

2
test/Shentun.WebPeis.Application.Tests/appsettings.Development.json

@ -0,0 +1,2 @@
{
}

43
test/Shentun.WebPeis.Application.Tests/appsettings.json

@ -0,0 +1,43 @@
{
//"Kestrel": {
// "Endpoints": {
// "Http": {
// "Url": "http://localhost:44382"
// },
// "Https": {
// "Url": "https://localhost:44382"
// }
// }
//},
"App": {
"SelfUrl": "https://localhost:44382",
"CorsOrigins": "https://*.WebPeis.com",
"RedirectAllowedUrls": ""
},
"ConnectionStrings": {
"Default": "Host=10.1.12.140;Port=5432;Database=WebPeis0520;User ID=postgres;Password=st123;"
},
"AuthServer": {
"Authority": "https://localhost:44382",
"RequireHttpsMetadata": false,
"SwaggerClientId": "WebPeis_Swagger",
"WeChatClientId": "WeChatApp",
"WeChatClientSecret": "1234*^@"
},
"StringEncryption": {
"DefaultPassPhrase": "rBfozS7zkeTYat2k"
},
"WeChat": {
"SessionUrl": "https://api.weixin.qq.com/sns/jscode2session?", //访URL
"AppID": "wx6a8a4440a42c9466", //AppID
"AppSecret": "aae34bfef498906290a92318d0f7183d" //AppSecret
},
"VirtualPaths": [
{
"PhysicsPath": "F:\\testimg", //
"RequestPath": "/Report", //
"Alias": "Report" //
}
]
}

2
test/Shentun.WebPeis.Application.Tests/appsettings.secrets.json

@ -0,0 +1,2 @@
{
}

12
test/Shentun.WebPeis.EntityFrameworkCore.Tests/EntityFrameworkCore/Applications/EfCorePersonAppServiceTest.cs

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shentun.WebPeis.EntityFrameworkCore.Applications
{
public class EfCorePersonAppServiceTest:PersonAppServiceTest<WebPeisEntityFrameworkCoreTestModule>
{
}
}

18
test/Shentun.WebPeis.EntityFrameworkCore.Tests/EntityFrameworkCore/WebPeisEntityFrameworkCoreTestModule.cs

@ -24,6 +24,7 @@ public class WebPeisEntityFrameworkCoreTestModule : AbpModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<FeatureManagementOptions>(options =>
{
options.SaveStaticFeaturesToDatabase = false;
@ -35,10 +36,23 @@ public class WebPeisEntityFrameworkCoreTestModule : AbpModule
options.IsDynamicPermissionStoreEnabled = false;
});
context.Services.AddAlwaysDisableUnitOfWorkTransaction();
ConfigureInMemorySqlite(context.Services);
ConfigurePostGress(context.Services);
//ConfigureInMemorySqlite(context.Services);
}
private void ConfigurePostGress(IServiceCollection services)
{
//string connectStr = "Host=140.143.162.39;Port=5432;Database=ShentunPeis070703;User ID=postgres;Password=shentun123";
string connectStr = "Host=10.1.12.140;Port=5432;Database=WebPeis0520;User ID=postgres;Password=st123;";
services.Configure<AbpDbContextOptions>(options =>
{
options.Configure(context =>
{
context.DbContextOptions.UseNpgsql(connectStr);
});
});
}
private void ConfigureInMemorySqlite(IServiceCollection services)
{
_sqliteConnection = CreateDatabaseAndGetConnection();

2
test/Shentun.WebPeis.TestBase/WebPeisTestBaseModule.cs

@ -29,7 +29,7 @@ public class WebPeisTestBaseModule : AbpModule
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
SeedTestData(context);
//SeedTestData(context);
}
private static void SeedTestData(ApplicationInitializationContext context)

Loading…
Cancel
Save