using Furion.DataEncryption; using Furion.EventBus; using Furion.FriendlyException; using Furion; using GDZZ.Application.Entity; using GDZZ.Core; using GDZZ.Core.Entity; using GDZZ.Core.Service; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using GDZZ.Core.OAuth; using Furion.DependencyInjection; using Furion.DynamicApiController; using System.Linq.Dynamic.Core.Tokenizer; using Microsoft.AspNetCore.Http; using GDZZ.Application.Help; using Mapster; namespace GDZZ.Application.Service.Auth { public class AuthService : IAuthService, IDynamicApiController, ITransient { #region 仓储 private readonly SqlSugarRepository Baseuser; // wx用户仓储 private readonly SqlSugarRepository _sysUserRep; // 用户表仓储 private readonly SqlSugarRepository _sysTenantRep; //租户仓储 private readonly SqlSugarRepository Self; //职业仓储 #endregion #region 服务 private readonly ICacheService cacheService; // private readonly WechatOAuth _wechatOAuth; //微信权限服务 private readonly IHttpContextAccessor _httpContextAccessor; //http服务 private readonly IEventPublisher _eventPublisher; //事件写入服务 #endregion /// /// 获取配置文件 /// private readonly ThirdParty _oauthConfig; public AuthService( IOptions options, SqlSugarRepository Baseuser, SqlSugarRepository sysTenantRep, SqlSugarRepository sysUserRep, SqlSugarRepository Self, ICacheService cacheService, WechatOAuth wechatOAuth, IEventPublisher eventPublisher, IHttpContextAccessor httpContextAccessor) { this._eventPublisher= eventPublisher; this._sysUserRep = sysUserRep; this._sysTenantRep = sysTenantRep; this.Baseuser = Baseuser; this._httpContextAccessor = httpContextAccessor; this.cacheService= cacheService; this.Self = Self; _wechatOAuth = wechatOAuth; _oauthConfig = options.Value.Wechat; } /// /// 手机端登录 /// /// [HttpPost("Mini/SignIn")] [AllowAnonymous] public async Task SignInAsync(PhoneModel phoneModel) { AuthUserOut authUserOut = new AuthUserOut(); //读取凭证 var tokenModel = await this._wechatOAuth.GetAccessTokenAsync(phoneModel.code); //解析电话 var phoneInfo = MiniProgramUtil.AESDecrypt(phoneModel.encryptedDataStr, tokenModel.SessionKey, phoneModel.iv); //查询系统用户 var sysUser = this._sysUserRep.AsQueryable() .Filter("TenantId", true) .First(x => x.Phone == phoneInfo.PhoneNumber); if (sysUser.IsEmpty()) { sysUser = await this._sysUserRep.InsertReturnEntityAsync(new SysUser() { Account = phoneInfo.PurePhoneNumber, AdminType = AdminType.None, Avatar = "https://gdzongzhi.com/assets/img/logo.png", Birthday = DateTime.Now, CreatedTime = DateTime.Now, CreatedUserId = null, CreatedUserName = null, Sex = Gender.UNKNOWN, Status = CommonStatus.ENABLE, Email = null, IsDeleted = false, Name = phoneInfo.PhoneNumber, Password = MD5Encryption.Encrypt("123456"), TenantId = 392820661919813, Phone = phoneInfo.PhoneNumber, NickName = "", Tel = null, }); } var wxUser = await this.Baseuser.AsQueryable() .Filter("TenantId", true) .Where(x => x.OpenID == tokenModel.OpenId).SingleAsync(); if (wxUser.IsEmpty()) { wxUser = await this.Baseuser.InsertReturnEntityAsync(new BaseUser() { UnionId = tokenModel.Unionid, CreatedUserId = sysUser.Id, CreatedTime = DateTime.Now, CreatedUserName = sysUser.Name, AvatarUrl = "https://gdzongzhi.com/assets/img/logo.png", Status = CommonStatus.ENABLE, OpenID = tokenModel.OpenId, TenantId = 392820661919813, Type = UserEnum.JOB, UserName = phoneInfo.PhoneNumber, }); } if(wxUser.IsEmpty()|| sysUser.IsEmpty()) throw Oops.Oh(ErrorCode.xg1002); var Self = await this.Self.FirstOrDefaultAsync(x => x.CreatedUserId == sysUser.Id); // 获取加密后的密码 var encryptPassword = MD5Encryption.Encrypt(sysUser.Password); // 验证账号是否被冻结 if (sysUser.Status == CommonStatus.DISABLE) throw Oops.Oh(ErrorCode.D1017); //获取对应租户 var tenant = this._sysTenantRep.Single(sysUser.TenantId); if (tenant.IsNullOrZero()) throw Oops.Oh(ErrorCode.F1001); // 生成Token令牌 authUserOut.Token = JWTEncryption.Encrypt(new Dictionary { {ClaimConst.CLAINM_USERID, sysUser.Id}, {ClaimConst.TENANT_ID, sysUser.TenantId}, {ClaimConst.CLAINM_ACCOUNT, sysUser.Account}, {ClaimConst.CLAINM_NAME, sysUser.Name}, {ClaimConst.CLAINM_SUPERADMIN, sysUser.AdminType}, { ClaimConst.CLAINM_TENANT_TYPE, tenant.TenantType }, { ClaimConst.CLAINM_TENANT_NAME, tenant.Name }, }); // 设置Swagger自动登录 _httpContextAccessor.HttpContext.SigninToSwagger(authUserOut.Token); // 生成刷新Token令牌 var refreshToken = JWTEncryption.GenerateRefreshToken(authUserOut.Token, 30); // 设置刷新Token令牌 _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken; var httpContext = App.HttpContext; await _eventPublisher.PublishAsync(new ChannelEventSource("Update:UserLoginInfo", new SysUser { Id = sysUser.Id, LastLoginIp = httpContext.GetLocalIpAddressToIPv4(), LastLoginTime = DateTime.Now })); authUserOut.Avatar = sysUser.Avatar; authUserOut.Phone = sysUser.Phone; authUserOut.Sex = sysUser.Sex; authUserOut.UserId = sysUser.Id; authUserOut.UserName = sysUser.Name; authUserOut.Self = Self.IsEmpty() ? "未填写" : Self.Name; authUserOut.Type = UserEnum.JOB; await this.cacheService.SetUserInfoAsync(authUserOut, authUserOut.UserId); return authUserOut; } /// /// 获取当前登录用户信息 /// /// [HttpGet("Mini/GetLoginUser")] public async Task GetLoginUserAsync() { return await this.cacheService.GetUserInfoAsync(UserManager.UserId); } ///// ///// 微信支付 ///// ///// ///// //[Transaction] //public async Task WxPay(long productId) //{ // //ProductInfoEntity entity = await _productInfoRepository.GetAsync(productId); // RechargeIntroEntity entity = await _rechargeIntroRepository.GetAsync(productId); // if (entity.IsNotNull()) // { // //订单信息 // OrderEntity order = await _orderRepository.InsertAsync(new OrderEntity // { // OrderSn = StringHelper.GetOrderSn(productId), // UserId = _user.Id, // ShippingUser = "", // Province = 0, // City = 0, // District = 0, // Address = "", // PaymentMethod = (int)PaymentMethodEnum.WX, // OrderMoney = entity.Price, // DistrictMoney = 0, // PaymentMoney = entity.Price, // ShippingCompName = "", // ShippingSn = "", // ShippingTime = null, // PayTime = DateTime.Now, // ReceiveTime = null, // OrderStatus = (int)OrderStatusEnum.NotPaying, // OrderPoint = 0, // InvoiceTitle = "" // }); // //明细 // await _orderDetailRepository.InsertAsync(new OrderDetailEntity // { // OrderId = order.Id, // ProductId = productId, // ProductName = entity.ProductName, // ProductPrice = entity.Price // }); // //付款记录 // PaymentRecordEntity paymentRecord = await _paymentRecordRepository.InsertAsync(new PaymentRecordEntity // { // UserId = _user.Id, // OrderId = order.Id, // PaySn = "", // PayStatus = (int)PayStatusEnum.NotPaying, // PayPlatform = (int)PaymentMethodEnum.WX, // PaymentMoney = order.PaymentMoney // }); // return await TenPayHelper.UniOrderAsync(_user.OpenId, entity.ProductName, order.PaymentMoney.ToInt(), // paymentRecord.Id); // } // return ResponseOutput.Fail("商品信息不存在"); //} } }