|
|
using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Caching.Distributed;using Microsoft.Extensions.Configuration;using OpenIddict.Abstractions;using Shentun.Peis.Enums;using Shentun.Peis.Models;using Shentun.Peis.SysParmValues;using SqlSugar;using System;using System.Collections.Generic;using System.Linq;using System.Net.Http;using System.Net.Http.Headers;using System.Security.Claims;using System.Text;using System.Text.Json;using System.Threading.Tasks;using Volo.Abp;using Volo.Abp.Application.Services;using Volo.Abp.Caching;using Volo.Abp.Domain.Repositories;using Volo.Abp.Identity;
namespace Shentun.Peis.ThirdUsers{ /// <summary>
/// 第三方用户
/// </summary>
[ApiExplorerSettings(GroupName = "Work")] [Authorize] public class ThirdUserAppService : ApplicationService {
private readonly IConfiguration _configuration; private readonly IDistributedCache<string, string> _cache; private readonly IRepository<ThirdUser, Guid> _thirdUserRepository; private readonly CacheService _cacheService; private readonly IRepository<IdentityUser, Guid> _identityUserRepository; public ThirdUserAppService( IConfiguration configuration, IDistributedCache<string, string> cache, IRepository<ThirdUser, Guid> thirdUserRepository, CacheService cacheService, IRepository<IdentityUser, Guid> identityUserRepository) { _configuration = configuration; _cache = cache; _thirdUserRepository = thirdUserRepository; _cacheService = cacheService; _identityUserRepository = identityUserRepository; }
/// <summary>
/// 微信用户登录
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AllowAnonymous] [HttpPost("api/app/ThirdUser/WeChatUserLogin")] public async Task<ThirdLoginDto> WeChatUserLoginAsync(WeChatUserLoginInputDto input) { var dic = new Dictionary<string, object> { {"jsCode",input.JsCode}, {"client_id","Peis_MiniProgram"}, {"mobile_phone",input.MobilePhone}, {"grant_type","mini_program"}, {"scope","Peis"} }; //
var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n); var token = await GetTokenAsync(dicStr); var options = new DistributedCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromDays(3)); var sessionKey = CacheKeys.SessionKey + Guid.NewGuid().ToString(); var sessionKeyValue = Guid.NewGuid().ToString(); _cache.Set(sessionKey, sessionKeyValue, options); token.SessionKey = sessionKey; token.SessionKeyValue = sessionKeyValue;
return token;
}
/// <summary>
/// 获取第三方用户信息
/// </summary>
/// <returns></returns>
[HttpPost("api/app/ThirdUser/GetList")] public async Task<List<ThirdUserDto>> GetListAsync(ThirdUserInputDto input) { var query = await _thirdUserRepository.GetQueryableAsync(); if (input.AbpUserId != null) { query = query.Where(m => m.AbpUserId == input.AbpUserId); } if (input.UserRegisterFlag != null) { query = query.Where(m => m.UserRegisterFlag == input.UserRegisterFlag); } if (input.IsActive != null) { query = query.Where(m => m.IsActive == input.IsActive); } if (!string.IsNullOrWhiteSpace(input.MobilePhone)) { query = query.Where(m => m.MobilePhone == input.MobilePhone); } if (!string.IsNullOrWhiteSpace(input.WechatOpenId)) { query = query.Where(m => m.WechatOpenId == input.WechatOpenId); }
var entListDto = query.OrderByDescending(o => o.CreationTime).ToList().Select(s => new ThirdUserDto { AbpUserId = s.AbpUserId, CreationTime = s.CreationTime, CreatorId = s.CreatorId, CreatorName = _cacheService.GetSurnameAsync(s.CreatorId).GetAwaiter().GetResult(), Id = s.Id, IsActive = s.IsActive, LastModificationTime = s.LastModificationTime, LastModifierId = s.LastModifierId, LastModifierName = _cacheService.GetSurnameAsync(s.LastModifierId).GetAwaiter().GetResult(), MobilePhone = s.MobilePhone, UserRegisterFlag = s.UserRegisterFlag, WechatOpenId = s.WechatOpenId }).ToList();
return entListDto; }
/// <summary>
/// 绑定第三方用户归属到系统用户
/// </summary>
/// <returns></returns>
[HttpPost("api/app/ThirdUser/BindThirdUserInAbpUser")] public async Task BindThirdUserInAbpUserAsync(BindThirdUserInAbpUserInputDto input) { var identityUser = await _identityUserRepository.FirstOrDefaultAsync(f => f.Id == input.AbpUserId); if (identityUser == null) { throw new UserFriendlyException("系统用户不存在"); }
var thirdUser = await _thirdUserRepository.FirstOrDefaultAsync(f => f.Id == input.ThirdUserId); if (thirdUser == null) { throw new UserFriendlyException("第三方用户不存在"); }
thirdUser.AbpUserId = input.AbpUserId;
await _thirdUserRepository.UpdateAsync(thirdUser);
}
private async Task<ThirdLoginDto> GetTokenAsync(string request) { using var client = new HttpClient(); HttpContent httpContent = new StringContent(request); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var url = _configuration.GetSection("AuthServer"). GetSection("Authority").Value + "/connect/token"; var tokenResult = await client.PostAsync(url , httpContent); var tokenResultStr = await tokenResult.Content.ReadAsStringAsync(); if (tokenResult.IsSuccessStatusCode) { var thirdLoginDto = new ThirdLoginDto();
if (!string.IsNullOrEmpty(tokenResultStr)) {
if (tokenResultStr.ToLower().Contains("openid")) { thirdLoginDto = JsonSerializer.Deserialize<ThirdLoginDto>(tokenResultStr, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); } else { var signResult = JsonSerializer.Deserialize<SignInResultDto>(tokenResultStr, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); thirdLoginDto = new ThirdLoginDto { IsToken = "Y", ExpiresIn = signResult.expires_in, AccessToken = signResult.access_token, RefreshToken = signResult.refresh_token }; }
return thirdLoginDto; } else { throw new UserFriendlyException("token值为空"); }
} else { throw new UserFriendlyException("获取token失败:" + tokenResultStr); } } }}
|