From dead8cfc93d0c8b6efaf6e84164e0a62c62a4e57 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Thu, 12 Dec 2024 17:08:10 +0800 Subject: [PATCH 01/14] feat: Add WeChat User Dto --- .../Users/Models/WeChatUser.cs | 55 +++++++++++++ .../Collections/WeChatUserDocument.cs | 78 +++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs create mode 100644 src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs b/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs new file mode 100644 index 00000000..511ef236 --- /dev/null +++ b/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs @@ -0,0 +1,55 @@ +namespace BotSharp.Abstraction.Users.Models; + +public class WeChatUser +{ + public string Id { get; set; } = string.Empty; + + /// + /// User unique identifier (unique under the current application) + /// + public string OpenId { get; set; } = string.Empty; + + public string SessionKey { get; set; } = string.Empty; + + /// + /// User unique identifier (cross application unique, requiring open platform binding) + /// + public string UnionId { get; set; } = string.Empty; + + /// + /// User's gender: 1- Male, 2- Female, 0- Unknown + /// + public int Sex { get; set; } + + /// + /// The province where the user's personal information is filled in + /// + public string Province { get; set; } = string.Empty; + + public string City { get; set; } = string.Empty; + + public string NickName { get; set; } = string.Empty; + + /// + /// User avatar URL (46/64/96/132/0 pixels) + /// + public string Headimgurl { get; set; } = string.Empty; + + public string PhoneNumber { get; set; } = string.Empty; + + /// + /// The country where the user is located, such as China CN + /// + public string Country { get; set; } = "CN"; + + /// + /// User privilege information (such as WeChat membership, etc.) + /// + public string[] Privilege { get; set; } = Array.Empty(); + + //public string AppId { get; set; } = string.Empty; + + public DateTime? UpdatedAt { get; set; } + + public DateTime CreatedAt { get; set; } +} diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs new file mode 100644 index 00000000..6898cb9c --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs @@ -0,0 +1,78 @@ +using BotSharp.Abstraction.Users.Models; + +namespace BotSharp.Plugin.MongoStorage.Collections; + +public class WeChatUserDocument : MongoBase +{ + public string Id { get; set; } = string.Empty; + + /// + /// User unique identifier (unique under the current application) + /// + public string OpenId { get; set; } = string.Empty; + + public string SessionKey { get; set; } = string.Empty; + + /// + /// User unique identifier (cross application unique, requiring open platform binding) + /// + public string UnionId { get; set; } = string.Empty; + + /// + /// User's gender: 1- Male, 2- Female, 0- Unknown + /// + public int Sex { get; set; } + + /// + /// The province where the user's personal information is filled in + /// + public string Province { get; set; } = string.Empty; + + public string City { get; set; } = string.Empty; + + public string NickName { get; set; } = string.Empty; + + /// + /// User avatar URL (46/64/96/132/0 pixels) + /// + public string Headimgurl { get; set; } = string.Empty; + + public string PhoneNumber { get; set; } = string.Empty; + + /// + /// The country where the user is located, such as China CN + /// + public string Country { get; set; } = "CN"; + + /// + /// User privilege information (such as WeChat membership, etc.) + /// + public string[] Privilege { get; set; } = Array.Empty(); + + //public string AppId { get; set; } = string.Empty; + + public DateTime? UpdatedAt { get; set; } + + public DateTime CreatedAt { get; set; } + + public WeChatUser ToWeChatUser() + { + return new WeChatUser + { + Id = Id, + OpenId = OpenId, + SessionKey = SessionKey, + UnionId = UnionId, + Sex = Sex, + Province = Province, + City = City, + NickName = NickName, + Headimgurl = Headimgurl, + PhoneNumber = PhoneNumber, + Country = Country, + Privilege = Privilege, + CreatedAt = CreatedAt, + UpdatedAt = UpdatedAt + }; + } +} From 1857cc66e4c31005f2d667a9a2083937bb792284 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Thu, 12 Dec 2024 17:09:46 +0800 Subject: [PATCH 02/14] feat: Add GetWeChatUser API --- .../BotSharp.Plugin.MongoStorage/MongoDbContext.cs | 5 ++++- .../Repository/MongoRepository.WeChatUser.cs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs index 89eb18ad..4c633dd9 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs @@ -36,7 +36,7 @@ public class MongoDbContext Key = x.Split("=")[0], Value = x.Split("=")[1] }).ToList(); - + var source = queries.FirstOrDefault(x => x.Key.IsEqualTo(DB_NAME_INDEX)); if (source != null) { @@ -168,4 +168,7 @@ public class MongoDbContext public IMongoCollection CrontabItems => Database.GetCollection($"{_collectionPrefix}_CronTabItems"); + + public IMongoCollection WeChatUsers + => Database.GetCollection($"{_collectionPrefix}_WeChatUsers"); } diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs new file mode 100644 index 00000000..81a325d4 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs @@ -0,0 +1,13 @@ +using BotSharp.Abstraction.Users.Models; + +namespace BotSharp.Plugin.MongoStorage.Repository; + +public partial class MongoRepository +{ + public WeChatUser? GetWeChatUser(string openId) + { + var weChatUser = _dc.WeChatUsers.AsQueryable().FirstOrDefault(x => x.OpenId == openId); + return weChatUser != null ? weChatUser.ToWeChatUser() : null; + } + +} From af95a6e1b2f2ad7704c0700a79f78a35409c92fb Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Thu, 12 Dec 2024 17:11:26 +0800 Subject: [PATCH 03/14] feat: Add CreateWeChatUser API --- .../Repository/MongoRepository.WeChatUser.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs index 81a325d4..e85cfebf 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs @@ -10,4 +10,31 @@ public partial class MongoRepository return weChatUser != null ? weChatUser.ToWeChatUser() : null; } + public WeChatUser? CreateWeChatUser(WeChatUser weChatUser) + { + if (weChatUser == null) return null; + + var weChatUserInfo = new WeChatUserDocument + { + Id = weChatUser.Id ?? Guid.NewGuid().ToString(), + OpenId = weChatUser.OpenId, + SessionKey = weChatUser.SessionKey, + UnionId = weChatUser.UnionId, + Sex = weChatUser.Sex, + Province = weChatUser.Province, + City = weChatUser.City, + NickName = weChatUser.NickName, + Headimgurl = weChatUser.Headimgurl, + PhoneNumber = weChatUser.PhoneNumber, + Country = weChatUser.Country, + Privilege = weChatUser.Privilege, + CreatedAt = DateTime.UtcNow, + }; + + _dc.WeChatUsers.InsertOne(weChatUserInfo); + + return weChatUserInfo.ToWeChatUser(); + } + + } From 541b7893da025756889f6723c94710dbe74c5a68 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Thu, 12 Dec 2024 17:12:07 +0800 Subject: [PATCH 04/14] feat: Add UpdateWeChatUser API --- .../Repository/MongoRepository.WeChatUser.cs | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs index e85cfebf..4399a5df 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs @@ -36,5 +36,27 @@ public partial class MongoRepository return weChatUserInfo.ToWeChatUser(); } - + public WeChatUser? UpdateWeChatUser(WeChatUser weChatUser) + { + if (weChatUser == null) return null; + + var filter = Builders.Filter.Eq(x => x.Id, weChatUser.Id); + var update = Builders.Update + .Set(x => x.OpenId, weChatUser.OpenId) + .Set(x => x.SessionKey, weChatUser.SessionKey) + .Set(x => x.UnionId, weChatUser.UnionId) + .Set(x => x.Sex, weChatUser.Sex) + .Set(x => x.Province, weChatUser.Province) + .Set(x => x.City, weChatUser.City) + .Set(x => x.NickName, weChatUser.NickName) + .Set(x => x.Headimgurl, weChatUser.Headimgurl) + .Set(x => x.PhoneNumber, weChatUser.PhoneNumber) + .Set(x => x.Country, weChatUser.Country) + .Set(x => x.Privilege, weChatUser.Privilege) + .Set(x => x.UpdatedAt, DateTime.UtcNow); + + _dc.WeChatUsers.UpdateOne(filter, update); + + return weChatUser; + } } From d11e91ca84ac9d7ece2544ea1b4a67328d3990c9 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Thu, 12 Dec 2024 20:58:22 +0800 Subject: [PATCH 05/14] feat: Add Create WeChat User Interface API --- .../Repositories/IBotSharpRepository.cs | 5 +++ .../Users/IWeChatUserService.cs | 12 +++++++ .../Users/Services/WeChatUserService.cs | 31 +++++++++++++++++++ .../Controllers/UserController.cs | 16 ++++++++-- 4 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs create mode 100644 src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs index 61982cc4..da5b2f3f 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs @@ -49,6 +49,11 @@ public interface IBotSharpRepository : IHaveServiceProvider PagedItems GetUsers(UserFilter filter) => throw new NotImplementedException(); User? GetUserDetails(string userId, bool includeAgent = false) => throw new NotImplementedException(); bool UpdateUser(User user, bool updateUserAgents = false) => throw new NotImplementedException(); + + WeChatUser? GetWeChatUser(string openId) => throw new NotImplementedException(); + WeChatUser? CreateWeChatUser(WeChatUser weChatUser) => throw new NotImplementedException(); + WeChatUser? UpdateWeChatUser(WeChatUser weChatUser) => throw new NotImplementedException(); + #endregion #region Agent diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs b/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs new file mode 100644 index 00000000..b25ba73d --- /dev/null +++ b/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs @@ -0,0 +1,12 @@ +using BotSharp.Abstraction.Users.Models; + +namespace BotSharp.Abstraction.Users; + +public interface IWeChatUserService +{ + Task GetWeChatUser(string openId); + + Task CreateWeChatUser(WeChatUser weChatUser); + + Task UpdateWeChatUser(WeChatUser weChatUser); +} diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs new file mode 100644 index 00000000..ab776b28 --- /dev/null +++ b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs @@ -0,0 +1,31 @@ +using BotSharp.Abstraction.Users.Models; + +namespace BotSharp.Core.Users.Services; + +public class WeChatUserService : IWeChatUserService +{ + private readonly IServiceProvider _services; + public WeChatUserService(IServiceProvider services) + { + _services = services; + } + + public async Task GetWeChatUser(string openId) + { + var db = _services.GetRequiredService(); + var weChatUser = db.GetWeChatUser(openId); + return weChatUser; + } + + public async Task CreateWeChatUser(WeChatUser weChatUser) + { + var db = _services.GetRequiredService(); + return db.CreateWeChatUser(weChatUser); + } + + public async Task UpdateWeChatUser(WeChatUser weChatUser) + { + var db = _services.GetRequiredService(); + return db.UpdateWeChatUser(weChatUser); + } +} diff --git a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs index 9d652a3e..b72888f3 100644 --- a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs +++ b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs @@ -1,4 +1,3 @@ -using BotSharp.Abstraction.Users.Enums; using BotSharp.Abstraction.Users.Settings; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; @@ -14,17 +13,20 @@ public class UserController : ControllerBase private readonly IUserService _userService; private readonly IUserIdentity _user; private readonly AccountSetting _setting; + private readonly IWeChatUserService _weChatUserService; public UserController( IUserService userService, IServiceProvider services, IUserIdentity user, - AccountSetting setting) + AccountSetting setting, + IWeChatUserService weChatUserService) { _services = services; _userService = userService; _user = user; _setting = setting; + _weChatUserService = weChatUserService; } [AllowAnonymous] @@ -72,6 +74,16 @@ public class UserController : ControllerBase return UserViewModel.FromUser(createdUser); } + [HttpPost("/user/wechat")] + public async Task CreateWeChatUser(string code) + { + // Get WeChat User Info + + + WeChatUser wechatUser = new(); + var user = await _weChatUserService.CreateWeChatUser(wechatUser); + } + [AllowAnonymous] [HttpPost("/user/activate")] public async Task> ActivateUser(UserActivationModel model) From d41d6eddd82ff4cec450b7a6d0d750f55cb8175a Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Fri, 13 Dec 2024 19:29:12 +0800 Subject: [PATCH 06/14] wip: Integrated WeChat login --- .../Repositories/IBotSharpRepository.cs | 2 +- .../Users/IWeChatUserService.cs | 2 + .../Users/Models/WeChatUser.cs | 22 ++++- .../Users/Services/WeChatUserService.cs | 88 ++++++++++++++++++- .../Controllers/UserController.cs | 15 +++- .../Collections/WeChatUserDocument.cs | 3 - .../Repository/MongoRepository.WeChatUser.cs | 6 +- src/WebStarter/appsettings.json | 10 +++ 8 files changed, 132 insertions(+), 16 deletions(-) diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs index da5b2f3f..aafb5b5f 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs @@ -51,7 +51,7 @@ public interface IBotSharpRepository : IHaveServiceProvider bool UpdateUser(User user, bool updateUserAgents = false) => throw new NotImplementedException(); WeChatUser? GetWeChatUser(string openId) => throw new NotImplementedException(); - WeChatUser? CreateWeChatUser(WeChatUser weChatUser) => throw new NotImplementedException(); + WeChatUser CreateWeChatUser(WeChatUser weChatUser) => throw new NotImplementedException(); WeChatUser? UpdateWeChatUser(WeChatUser weChatUser) => throw new NotImplementedException(); #endregion diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs b/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs index b25ba73d..a6b69865 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs @@ -9,4 +9,6 @@ public interface IWeChatUserService Task CreateWeChatUser(WeChatUser weChatUser); Task UpdateWeChatUser(WeChatUser weChatUser); + + Task WeChatUserLogin(string code); } diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs b/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs index 511ef236..165787a0 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs @@ -1,3 +1,5 @@ +using BotSharp.Abstraction.Users.Enums; + namespace BotSharp.Abstraction.Users.Models; public class WeChatUser @@ -9,8 +11,6 @@ public class WeChatUser /// public string OpenId { get; set; } = string.Empty; - public string SessionKey { get; set; } = string.Empty; - /// /// User unique identifier (cross application unique, requiring open platform binding) /// @@ -52,4 +52,22 @@ public class WeChatUser public DateTime? UpdatedAt { get; set; } public DateTime CreatedAt { get; set; } + + public User ToUser() + { + return new User + { + Id = Id, + Phone = PhoneNumber, + UserName = PhoneNumber, + FirstName = PhoneNumber, + LastName = PhoneNumber, + Email = null, + Password = string.Empty, + Role = UserRole.User, + Type = UserType.Client, + RegionCode = "CN", + ReferralCode = null, + }; + } } diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs index ab776b28..d79c1648 100644 --- a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs +++ b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs @@ -1,23 +1,30 @@ using BotSharp.Abstraction.Users.Models; +using Microsoft.Extensions.Configuration; +using Newtonsoft.Json.Linq; namespace BotSharp.Core.Users.Services; public class WeChatUserService : IWeChatUserService { private readonly IServiceProvider _services; - public WeChatUserService(IServiceProvider services) + private readonly ILogger _logger; + private readonly IConfiguration _configuration; + + public WeChatUserService(IServiceProvider services, ILogger logger, IConfiguration configuration) { _services = services; + _logger = logger; + _configuration = configuration; } public async Task GetWeChatUser(string openId) { - var db = _services.GetRequiredService(); + var db = _services.GetRequiredService(); var weChatUser = db.GetWeChatUser(openId); return weChatUser; } - public async Task CreateWeChatUser(WeChatUser weChatUser) + public async Task CreateWeChatUser(WeChatUser weChatUser) { var db = _services.GetRequiredService(); return db.CreateWeChatUser(weChatUser); @@ -28,4 +35,79 @@ public class WeChatUserService : IWeChatUserService var db = _services.GetRequiredService(); return db.UpdateWeChatUser(weChatUser); } + + #region 微信扫码登录(OAuth 2.0 网页授权) + + public async Task WeChatUserLogin(string code) + { + // 实现获取 access_token 和 openid,再获取用户信息 + if (string.IsNullOrEmpty(code)) + { + _logger.LogError("Create WeChatUser Error: code is empty, Please check if the code has been obtained correctly!"); + throw new Exception("code is empty"); + } + + var appId = _configuration["WeChatQtoss:AppId"] ?? throw new Exception("AppId is not configured."); + var appSecret = _configuration["WeChatQtoss:AppSecret"] ?? throw new Exception("AppSecret is not configured."); + + try + { + // Step 1: 使用 code 获取 access_token 和 openid + var tokenUrl = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code"; + + using var httpClient = new HttpClient(); + var tokenResponse = await httpClient.GetStringAsync(tokenUrl); + + var tokenData = JObject.Parse(tokenResponse); + var accessToken = tokenData["access_token"]?.ToString(); + var openId = tokenData["openid"]?.ToString(); + + if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(openId)) + { + _logger.LogError("Create WeChatUser Error: Failed to get access_token or openid"); + throw new Exception("Failed to get access_token or openid"); + } + + // Step 2: Retrieve user information using access_token and openid + var userInfoUrl = $"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}&lang=zh_CN"; + + var userInfoResponse = await httpClient.GetStringAsync(userInfoUrl); + var userInfo = JObject.Parse(userInfoResponse); + + // 提取用户信息 + var nickname = userInfo["nickname"]?.ToString() ?? string.Empty; + var avatar = userInfo["headimgurl"]?.ToString() ?? string.Empty; + var country = userInfo["country"]?.ToString() ?? string.Empty; + var province = userInfo["province"]?.ToString() ?? string.Empty; + var city = userInfo["city"]?.ToString() ?? string.Empty; + var sex = userInfo["sex"]?.ToString() ?? "0"; + var privilege = userInfo["privilege"]?.ToString() ?? string.Empty; + var unionId = userInfo["unionId"]?.ToString() ?? string.Empty; + + // 创建或更新 WeChatUser + var weChatUser = new WeChatUser + { + OpenId = openId, + NickName = nickname, + Sex = int.Parse(sex), + Province = province, + City = city, + Country = country, + Headimgurl = avatar, + Privilege = privilege.Split(','), + UnionId = unionId + }; + + return await CreateWeChatUser(weChatUser); + } + catch (Exception ex) + { + _logger.LogError($"Create WeChatUser Error: {ex.Message}"); + throw new Exception($"Failed to create WeChatUser: {ex.Message}", ex); + } + + } + + + #endregion 微信扫码登录(OAuth 2.0 网页授权) } diff --git a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs index b72888f3..a39200e2 100644 --- a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs +++ b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs @@ -78,10 +78,21 @@ public class UserController : ControllerBase public async Task CreateWeChatUser(string code) { // Get WeChat User Info + var wechatUser = await _weChatUserService.WeChatUserLogin(code); + if (wechatUser == null) + { + return; + } + var weChatUser = await _weChatUserService.CreateWeChatUser(wechatUser); - WeChatUser wechatUser = new(); - var user = await _weChatUserService.CreateWeChatUser(wechatUser); + if (wechatUser == null) + { + return; + } + + // Create User + var createdUser = await _userService.CreateUser(weChatUser.ToUser()); } [AllowAnonymous] diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs index 6898cb9c..c85c7f4e 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs @@ -11,8 +11,6 @@ public class WeChatUserDocument : MongoBase /// public string OpenId { get; set; } = string.Empty; - public string SessionKey { get; set; } = string.Empty; - /// /// User unique identifier (cross application unique, requiring open platform binding) /// @@ -61,7 +59,6 @@ public class WeChatUserDocument : MongoBase { Id = Id, OpenId = OpenId, - SessionKey = SessionKey, UnionId = UnionId, Sex = Sex, Province = Province, diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs index 4399a5df..91cca0bf 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs @@ -10,15 +10,12 @@ public partial class MongoRepository return weChatUser != null ? weChatUser.ToWeChatUser() : null; } - public WeChatUser? CreateWeChatUser(WeChatUser weChatUser) + public WeChatUser CreateWeChatUser(WeChatUser weChatUser) { - if (weChatUser == null) return null; - var weChatUserInfo = new WeChatUserDocument { Id = weChatUser.Id ?? Guid.NewGuid().ToString(), OpenId = weChatUser.OpenId, - SessionKey = weChatUser.SessionKey, UnionId = weChatUser.UnionId, Sex = weChatUser.Sex, Province = weChatUser.Province, @@ -43,7 +40,6 @@ public partial class MongoRepository var filter = Builders.Filter.Eq(x => x.Id, weChatUser.Id); var update = Builders.Update .Set(x => x.OpenId, weChatUser.OpenId) - .Set(x => x.SessionKey, weChatUser.SessionKey) .Set(x => x.UnionId, weChatUser.UnionId) .Set(x => x.Sex, weChatUser.Sex) .Set(x => x.Province, weChatUser.Province) diff --git a/src/WebStarter/appsettings.json b/src/WebStarter/appsettings.json index c3d4bdd5..3efc0b4d 100644 --- a/src/WebStarter/appsettings.json +++ b/src/WebStarter/appsettings.json @@ -273,6 +273,16 @@ "WeixinAppSecret": "#{WeixinAppSecret}#" }, + "WeChatQtoss": { + "AppId": "", + "AppSecret": "" + }, + + "WeChatQtossAI": { + "AppId": "", + "AppSecret": "" + }, + "KnowledgeBase": { "VectorDb": { "Provider": "Qdrant" From dedf6d740bbef319951cb1c7983f6d52e2622594 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Fri, 13 Dec 2024 19:37:47 +0800 Subject: [PATCH 07/14] wip: update CreateWeChatUser API --- .../Users/Services/WeChatUserService.cs | 8 ++++---- .../Controllers/UserController.cs | 19 +++++++------------ 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs index d79c1648..1da9b47e 100644 --- a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs +++ b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs @@ -40,7 +40,7 @@ public class WeChatUserService : IWeChatUserService public async Task WeChatUserLogin(string code) { - // 实现获取 access_token 和 openid,再获取用户信息 + // Implement obtaining access_token and openid, and then obtaining user information if (string.IsNullOrEmpty(code)) { _logger.LogError("Create WeChatUser Error: code is empty, Please check if the code has been obtained correctly!"); @@ -52,7 +52,7 @@ public class WeChatUserService : IWeChatUserService try { - // Step 1: 使用 code 获取 access_token 和 openid + // Step 1: Use the code to obtain the access_token and openid var tokenUrl = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code"; using var httpClient = new HttpClient(); @@ -74,7 +74,7 @@ public class WeChatUserService : IWeChatUserService var userInfoResponse = await httpClient.GetStringAsync(userInfoUrl); var userInfo = JObject.Parse(userInfoResponse); - // 提取用户信息 + // Retrieve user information var nickname = userInfo["nickname"]?.ToString() ?? string.Empty; var avatar = userInfo["headimgurl"]?.ToString() ?? string.Empty; var country = userInfo["country"]?.ToString() ?? string.Empty; @@ -84,7 +84,7 @@ public class WeChatUserService : IWeChatUserService var privilege = userInfo["privilege"]?.ToString() ?? string.Empty; var unionId = userInfo["unionId"]?.ToString() ?? string.Empty; - // 创建或更新 WeChatUser + // Create or update WeChatUser var weChatUser = new WeChatUser { OpenId = openId, diff --git a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs index a39200e2..964e8aee 100644 --- a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs +++ b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs @@ -74,25 +74,20 @@ public class UserController : ControllerBase return UserViewModel.FromUser(createdUser); } + [AllowAnonymous] [HttpPost("/user/wechat")] - public async Task CreateWeChatUser(string code) + public async Task CreateWeChatUser(string code) { // Get WeChat User Info - var wechatUser = await _weChatUserService.WeChatUserLogin(code); - if (wechatUser == null) - { - return; - } + var wechatUserInfo = await _weChatUserService.WeChatUserLogin(code); - var weChatUser = await _weChatUserService.CreateWeChatUser(wechatUser); - - if (wechatUser == null) - { - return; - } + // Create WeChatUser + var weChatUser = await _weChatUserService.CreateWeChatUser(wechatUserInfo); // Create User var createdUser = await _userService.CreateUser(weChatUser.ToUser()); + + return UserViewModel.FromUser(createdUser); } [AllowAnonymous] From 802401690b32532c4cd74554a076203cd73a892a Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Sat, 14 Dec 2024 10:44:35 +0800 Subject: [PATCH 08/14] fix: updated country --- .../BotSharp.Core/Users/Services/WeChatUserService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs index 1da9b47e..55b8e0e9 100644 --- a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs +++ b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs @@ -77,7 +77,7 @@ public class WeChatUserService : IWeChatUserService // Retrieve user information var nickname = userInfo["nickname"]?.ToString() ?? string.Empty; var avatar = userInfo["headimgurl"]?.ToString() ?? string.Empty; - var country = userInfo["country"]?.ToString() ?? string.Empty; + var country = userInfo["country"]?.ToString() ?? "CN"; var province = userInfo["province"]?.ToString() ?? string.Empty; var city = userInfo["city"]?.ToString() ?? string.Empty; var sex = userInfo["sex"]?.ToString() ?? "0"; @@ -92,7 +92,7 @@ public class WeChatUserService : IWeChatUserService Sex = int.Parse(sex), Province = province, City = city, - Country = country, + Country = ((country != "CN" && country.Contains("CN")) ? "CN" : country), Headimgurl = avatar, Privilege = privilege.Split(','), UnionId = unionId @@ -105,7 +105,7 @@ public class WeChatUserService : IWeChatUserService _logger.LogError($"Create WeChatUser Error: {ex.Message}"); throw new Exception($"Failed to create WeChatUser: {ex.Message}", ex); } - + } From d87afc7151e69b697f8f761754119469f4cd23a7 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Sat, 14 Dec 2024 15:55:16 +0800 Subject: [PATCH 09/14] revert: #57 --- .../Repositories/IBotSharpRepository.cs | 4 - .../Users/IWeChatUserService.cs | 14 --- .../Users/Models/WeChatUser.cs | 73 ----------- .../Users/Services/WeChatUserService.cs | 113 ------------------ .../Controllers/UserController.cs | 21 +--- .../Collections/WeChatUserDocument.cs | 75 ------------ .../MongoDbContext.cs | 2 - .../Repository/MongoRepository.WeChatUser.cs | 58 --------- src/WebStarter/appsettings.json | 10 -- 9 files changed, 1 insertion(+), 369 deletions(-) delete mode 100644 src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs delete mode 100644 src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs delete mode 100644 src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs delete mode 100644 src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs delete mode 100644 src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs index aafb5b5f..3fca7372 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs @@ -50,10 +50,6 @@ public interface IBotSharpRepository : IHaveServiceProvider User? GetUserDetails(string userId, bool includeAgent = false) => throw new NotImplementedException(); bool UpdateUser(User user, bool updateUserAgents = false) => throw new NotImplementedException(); - WeChatUser? GetWeChatUser(string openId) => throw new NotImplementedException(); - WeChatUser CreateWeChatUser(WeChatUser weChatUser) => throw new NotImplementedException(); - WeChatUser? UpdateWeChatUser(WeChatUser weChatUser) => throw new NotImplementedException(); - #endregion #region Agent diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs b/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs deleted file mode 100644 index a6b69865..00000000 --- a/src/Infrastructure/BotSharp.Abstraction/Users/IWeChatUserService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using BotSharp.Abstraction.Users.Models; - -namespace BotSharp.Abstraction.Users; - -public interface IWeChatUserService -{ - Task GetWeChatUser(string openId); - - Task CreateWeChatUser(WeChatUser weChatUser); - - Task UpdateWeChatUser(WeChatUser weChatUser); - - Task WeChatUserLogin(string code); -} diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs b/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs deleted file mode 100644 index 165787a0..00000000 --- a/src/Infrastructure/BotSharp.Abstraction/Users/Models/WeChatUser.cs +++ /dev/null @@ -1,73 +0,0 @@ -using BotSharp.Abstraction.Users.Enums; - -namespace BotSharp.Abstraction.Users.Models; - -public class WeChatUser -{ - public string Id { get; set; } = string.Empty; - - /// - /// User unique identifier (unique under the current application) - /// - public string OpenId { get; set; } = string.Empty; - - /// - /// User unique identifier (cross application unique, requiring open platform binding) - /// - public string UnionId { get; set; } = string.Empty; - - /// - /// User's gender: 1- Male, 2- Female, 0- Unknown - /// - public int Sex { get; set; } - - /// - /// The province where the user's personal information is filled in - /// - public string Province { get; set; } = string.Empty; - - public string City { get; set; } = string.Empty; - - public string NickName { get; set; } = string.Empty; - - /// - /// User avatar URL (46/64/96/132/0 pixels) - /// - public string Headimgurl { get; set; } = string.Empty; - - public string PhoneNumber { get; set; } = string.Empty; - - /// - /// The country where the user is located, such as China CN - /// - public string Country { get; set; } = "CN"; - - /// - /// User privilege information (such as WeChat membership, etc.) - /// - public string[] Privilege { get; set; } = Array.Empty(); - - //public string AppId { get; set; } = string.Empty; - - public DateTime? UpdatedAt { get; set; } - - public DateTime CreatedAt { get; set; } - - public User ToUser() - { - return new User - { - Id = Id, - Phone = PhoneNumber, - UserName = PhoneNumber, - FirstName = PhoneNumber, - LastName = PhoneNumber, - Email = null, - Password = string.Empty, - Role = UserRole.User, - Type = UserType.Client, - RegionCode = "CN", - ReferralCode = null, - }; - } -} diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs deleted file mode 100644 index 55b8e0e9..00000000 --- a/src/Infrastructure/BotSharp.Core/Users/Services/WeChatUserService.cs +++ /dev/null @@ -1,113 +0,0 @@ -using BotSharp.Abstraction.Users.Models; -using Microsoft.Extensions.Configuration; -using Newtonsoft.Json.Linq; - -namespace BotSharp.Core.Users.Services; - -public class WeChatUserService : IWeChatUserService -{ - private readonly IServiceProvider _services; - private readonly ILogger _logger; - private readonly IConfiguration _configuration; - - public WeChatUserService(IServiceProvider services, ILogger logger, IConfiguration configuration) - { - _services = services; - _logger = logger; - _configuration = configuration; - } - - public async Task GetWeChatUser(string openId) - { - var db = _services.GetRequiredService(); - var weChatUser = db.GetWeChatUser(openId); - return weChatUser; - } - - public async Task CreateWeChatUser(WeChatUser weChatUser) - { - var db = _services.GetRequiredService(); - return db.CreateWeChatUser(weChatUser); - } - - public async Task UpdateWeChatUser(WeChatUser weChatUser) - { - var db = _services.GetRequiredService(); - return db.UpdateWeChatUser(weChatUser); - } - - #region 微信扫码登录(OAuth 2.0 网页授权) - - public async Task WeChatUserLogin(string code) - { - // Implement obtaining access_token and openid, and then obtaining user information - if (string.IsNullOrEmpty(code)) - { - _logger.LogError("Create WeChatUser Error: code is empty, Please check if the code has been obtained correctly!"); - throw new Exception("code is empty"); - } - - var appId = _configuration["WeChatQtoss:AppId"] ?? throw new Exception("AppId is not configured."); - var appSecret = _configuration["WeChatQtoss:AppSecret"] ?? throw new Exception("AppSecret is not configured."); - - try - { - // Step 1: Use the code to obtain the access_token and openid - var tokenUrl = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code"; - - using var httpClient = new HttpClient(); - var tokenResponse = await httpClient.GetStringAsync(tokenUrl); - - var tokenData = JObject.Parse(tokenResponse); - var accessToken = tokenData["access_token"]?.ToString(); - var openId = tokenData["openid"]?.ToString(); - - if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(openId)) - { - _logger.LogError("Create WeChatUser Error: Failed to get access_token or openid"); - throw new Exception("Failed to get access_token or openid"); - } - - // Step 2: Retrieve user information using access_token and openid - var userInfoUrl = $"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}&lang=zh_CN"; - - var userInfoResponse = await httpClient.GetStringAsync(userInfoUrl); - var userInfo = JObject.Parse(userInfoResponse); - - // Retrieve user information - var nickname = userInfo["nickname"]?.ToString() ?? string.Empty; - var avatar = userInfo["headimgurl"]?.ToString() ?? string.Empty; - var country = userInfo["country"]?.ToString() ?? "CN"; - var province = userInfo["province"]?.ToString() ?? string.Empty; - var city = userInfo["city"]?.ToString() ?? string.Empty; - var sex = userInfo["sex"]?.ToString() ?? "0"; - var privilege = userInfo["privilege"]?.ToString() ?? string.Empty; - var unionId = userInfo["unionId"]?.ToString() ?? string.Empty; - - // Create or update WeChatUser - var weChatUser = new WeChatUser - { - OpenId = openId, - NickName = nickname, - Sex = int.Parse(sex), - Province = province, - City = city, - Country = ((country != "CN" && country.Contains("CN")) ? "CN" : country), - Headimgurl = avatar, - Privilege = privilege.Split(','), - UnionId = unionId - }; - - return await CreateWeChatUser(weChatUser); - } - catch (Exception ex) - { - _logger.LogError($"Create WeChatUser Error: {ex.Message}"); - throw new Exception($"Failed to create WeChatUser: {ex.Message}", ex); - } - - } - - - #endregion 微信扫码登录(OAuth 2.0 网页授权) -} diff --git a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs index 964e8aee..c893bcab 100644 --- a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs +++ b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs @@ -13,20 +13,17 @@ public class UserController : ControllerBase private readonly IUserService _userService; private readonly IUserIdentity _user; private readonly AccountSetting _setting; - private readonly IWeChatUserService _weChatUserService; public UserController( IUserService userService, IServiceProvider services, IUserIdentity user, - AccountSetting setting, - IWeChatUserService weChatUserService) + AccountSetting setting) { _services = services; _userService = userService; _user = user; _setting = setting; - _weChatUserService = weChatUserService; } [AllowAnonymous] @@ -74,22 +71,6 @@ public class UserController : ControllerBase return UserViewModel.FromUser(createdUser); } - [AllowAnonymous] - [HttpPost("/user/wechat")] - public async Task CreateWeChatUser(string code) - { - // Get WeChat User Info - var wechatUserInfo = await _weChatUserService.WeChatUserLogin(code); - - // Create WeChatUser - var weChatUser = await _weChatUserService.CreateWeChatUser(wechatUserInfo); - - // Create User - var createdUser = await _userService.CreateUser(weChatUser.ToUser()); - - return UserViewModel.FromUser(createdUser); - } - [AllowAnonymous] [HttpPost("/user/activate")] public async Task> ActivateUser(UserActivationModel model) diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs deleted file mode 100644 index c85c7f4e..00000000 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/WeChatUserDocument.cs +++ /dev/null @@ -1,75 +0,0 @@ -using BotSharp.Abstraction.Users.Models; - -namespace BotSharp.Plugin.MongoStorage.Collections; - -public class WeChatUserDocument : MongoBase -{ - public string Id { get; set; } = string.Empty; - - /// - /// User unique identifier (unique under the current application) - /// - public string OpenId { get; set; } = string.Empty; - - /// - /// User unique identifier (cross application unique, requiring open platform binding) - /// - public string UnionId { get; set; } = string.Empty; - - /// - /// User's gender: 1- Male, 2- Female, 0- Unknown - /// - public int Sex { get; set; } - - /// - /// The province where the user's personal information is filled in - /// - public string Province { get; set; } = string.Empty; - - public string City { get; set; } = string.Empty; - - public string NickName { get; set; } = string.Empty; - - /// - /// User avatar URL (46/64/96/132/0 pixels) - /// - public string Headimgurl { get; set; } = string.Empty; - - public string PhoneNumber { get; set; } = string.Empty; - - /// - /// The country where the user is located, such as China CN - /// - public string Country { get; set; } = "CN"; - - /// - /// User privilege information (such as WeChat membership, etc.) - /// - public string[] Privilege { get; set; } = Array.Empty(); - - //public string AppId { get; set; } = string.Empty; - - public DateTime? UpdatedAt { get; set; } - - public DateTime CreatedAt { get; set; } - - public WeChatUser ToWeChatUser() - { - return new WeChatUser - { - Id = Id, - OpenId = OpenId, - UnionId = UnionId, - Sex = Sex, - Province = Province, - City = City, - NickName = NickName, - Headimgurl = Headimgurl, - PhoneNumber = PhoneNumber, - Country = Country, - Privilege = Privilege, - CreatedAt = CreatedAt, - UpdatedAt = UpdatedAt - }; - } -} diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs index 4c633dd9..82e9f0d4 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs @@ -169,6 +169,4 @@ public class MongoDbContext public IMongoCollection CrontabItems => Database.GetCollection($"{_collectionPrefix}_CronTabItems"); - public IMongoCollection WeChatUsers - => Database.GetCollection($"{_collectionPrefix}_WeChatUsers"); } diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs deleted file mode 100644 index 91cca0bf..00000000 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.WeChatUser.cs +++ /dev/null @@ -1,58 +0,0 @@ -using BotSharp.Abstraction.Users.Models; - -namespace BotSharp.Plugin.MongoStorage.Repository; - -public partial class MongoRepository -{ - public WeChatUser? GetWeChatUser(string openId) - { - var weChatUser = _dc.WeChatUsers.AsQueryable().FirstOrDefault(x => x.OpenId == openId); - return weChatUser != null ? weChatUser.ToWeChatUser() : null; - } - - public WeChatUser CreateWeChatUser(WeChatUser weChatUser) - { - var weChatUserInfo = new WeChatUserDocument - { - Id = weChatUser.Id ?? Guid.NewGuid().ToString(), - OpenId = weChatUser.OpenId, - UnionId = weChatUser.UnionId, - Sex = weChatUser.Sex, - Province = weChatUser.Province, - City = weChatUser.City, - NickName = weChatUser.NickName, - Headimgurl = weChatUser.Headimgurl, - PhoneNumber = weChatUser.PhoneNumber, - Country = weChatUser.Country, - Privilege = weChatUser.Privilege, - CreatedAt = DateTime.UtcNow, - }; - - _dc.WeChatUsers.InsertOne(weChatUserInfo); - - return weChatUserInfo.ToWeChatUser(); - } - - public WeChatUser? UpdateWeChatUser(WeChatUser weChatUser) - { - if (weChatUser == null) return null; - - var filter = Builders.Filter.Eq(x => x.Id, weChatUser.Id); - var update = Builders.Update - .Set(x => x.OpenId, weChatUser.OpenId) - .Set(x => x.UnionId, weChatUser.UnionId) - .Set(x => x.Sex, weChatUser.Sex) - .Set(x => x.Province, weChatUser.Province) - .Set(x => x.City, weChatUser.City) - .Set(x => x.NickName, weChatUser.NickName) - .Set(x => x.Headimgurl, weChatUser.Headimgurl) - .Set(x => x.PhoneNumber, weChatUser.PhoneNumber) - .Set(x => x.Country, weChatUser.Country) - .Set(x => x.Privilege, weChatUser.Privilege) - .Set(x => x.UpdatedAt, DateTime.UtcNow); - - _dc.WeChatUsers.UpdateOne(filter, update); - - return weChatUser; - } -} diff --git a/src/WebStarter/appsettings.json b/src/WebStarter/appsettings.json index 3efc0b4d..c3d4bdd5 100644 --- a/src/WebStarter/appsettings.json +++ b/src/WebStarter/appsettings.json @@ -273,16 +273,6 @@ "WeixinAppSecret": "#{WeixinAppSecret}#" }, - "WeChatQtoss": { - "AppId": "", - "AppSecret": "" - }, - - "WeChatQtossAI": { - "AppId": "", - "AppSecret": "" - }, - "KnowledgeBase": { "VectorDb": { "Provider": "Qdrant" From f5b2999408295a0d089c3b0b28d874da08adf321 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Sat, 14 Dec 2024 17:19:40 +0800 Subject: [PATCH 10/14] fix: Add regionCode to GetUserByUserName API --- .../Repositories/IBotSharpRepository.cs | 2 +- .../Repository/FileRepository/FileRepository.User.cs | 4 ++-- .../BotSharp.Core/Users/Services/UserService.cs | 10 +++++----- .../Repository/MongoRepository.User.cs | 10 +++++----- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs index 3fca7372..9fe1619e 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs @@ -32,7 +32,7 @@ public interface IBotSharpRepository : IHaveServiceProvider User? GetUserById(string id) => throw new NotImplementedException(); List GetUserByIds(List ids) => throw new NotImplementedException(); List GetUsersByAffiliateId(string affiliateId) => throw new NotImplementedException(); - User? GetUserByUserName(string userName) => throw new NotImplementedException(); + User? GetUserByUserName(string userName, string regionCode = "CN") => throw new NotImplementedException(); Dashboard? GetDashboard(string id = null) => throw new NotImplementedException(); void CreateUser(User user) => throw new NotImplementedException(); void UpdateExistUser(string userId, User user) => throw new NotImplementedException(); diff --git a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs index 9d5b42be..989c9ef9 100644 --- a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs +++ b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs @@ -48,9 +48,9 @@ public partial class FileRepository return Users.Where(x => x.AffiliateId == affiliateId).ToList(); } - public User? GetUserByUserName(string userName = null) + public User? GetUserByUserName(string userName = null, string regionCode = "CN") { - return Users.FirstOrDefault(x => x.UserName == userName.ToLower()); + return Users.FirstOrDefault(x => x.UserName == userName.ToLower() && x.RegionCode == regionCode.ToLower()); } public Dashboard? GetDashboard(string id = null) diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs index a87c55fa..991ef0df 100644 --- a/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs +++ b/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs @@ -50,7 +50,7 @@ public class UserService : IUserService if (!string.IsNullOrWhiteSpace(user.UserName)) { - record = db.GetUserByUserName(user.UserName); + record = db.GetUserByUserName(user.UserName, regionCode: user.RegionCode); } if (record != null && record.Verified) @@ -214,7 +214,7 @@ public class UserService : IUserService var (id, password, regionCode) = base64.SplitAsTuple(":"); var db = _services.GetRequiredService(); - var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id); + var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id, regionCode: regionCode); if (record == null) { record = db.GetUserByPhone(id, regionCode: regionCode); @@ -384,7 +384,7 @@ public class UserService : IUserService } else if (_user.UserName != null) { - user = db.GetUserByUserName(_user.UserName); + user = db.GetUserByUserName(_user.UserName, _user.RegionCode); } else if (_user.Email != null) { @@ -471,7 +471,7 @@ public class UserService : IUserService { var id = model.UserName; var db = _services.GetRequiredService(); - var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id); + var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id, regionCode: (string.IsNullOrWhiteSpace(model.RegionCode) ? "CN" : model.RegionCode)); if (record == null) { record = db.GetUserByPhone(id, regionCode: (string.IsNullOrWhiteSpace(model.RegionCode) ? "CN" : model.RegionCode)); @@ -515,7 +515,7 @@ public class UserService : IUserService var db = _services.GetRequiredService(); - var user = db.GetUserByUserName(userName); + var user = db.GetUserByUserName(userName, regionCode: "CN"); if (user != null && user.Verified) { return true; diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs index 3c76e21d..c463541f 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs @@ -61,9 +61,9 @@ public partial class MongoRepository return users?.Any() == true ? users.Select(x => x.ToUser()).ToList() : new List(); } - public User? GetUserByUserName(string userName) + public User? GetUserByUserName(string userName, string regionCode = "CN") { - var user = _dc.Users.AsQueryable().FirstOrDefault(x => x.UserName == userName.ToLower()); + var user = _dc.Users.AsQueryable().FirstOrDefault(x => x.UserName == userName.ToLower() && x.RegionCode == regionCode.ToLower()); return user != null ? user.ToUser() : null; } @@ -331,10 +331,10 @@ public partial class MongoRepository .FirstOrDefault(x => x.Id == userId || (x.ExternalId != null && x.ExternalId == userId)); if (user == null) return; var curDash = user.Dashboard ?? new Dashboard(); - curDash.ConversationList.Add(new DashboardConversation - { + curDash.ConversationList.Add(new DashboardConversation + { Id = Guid.NewGuid().ToString(), - ConversationId = conversationId + ConversationId = conversationId }); var filter = Builders.Filter.Eq(x => x.Id, userId); From dfa2f477a0e234aacca2ade9ee3dd9758580cbf9 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Mon, 16 Dec 2024 09:58:57 +0800 Subject: [PATCH 11/14] revert: #58 --- .../Repositories/IBotSharpRepository.cs | 2 +- .../Repository/FileRepository/FileRepository.User.cs | 4 ++-- .../BotSharp.Core/Users/Services/UserService.cs | 10 +++++----- .../Repository/MongoRepository.User.cs | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs index acb6a77c..87d4fd99 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs @@ -32,7 +32,7 @@ public interface IBotSharpRepository : IHaveServiceProvider User? GetUserById(string id) => throw new NotImplementedException(); List GetUserByIds(List ids) => throw new NotImplementedException(); List GetUsersByAffiliateId(string affiliateId) => throw new NotImplementedException(); - User? GetUserByUserName(string userName, string regionCode = "CN") => throw new NotImplementedException(); + User? GetUserByUserName(string userName) => throw new NotImplementedException(); Dashboard? GetDashboard(string id = null) => throw new NotImplementedException(); void CreateUser(User user) => throw new NotImplementedException(); void UpdateExistUser(string userId, User user) => throw new NotImplementedException(); diff --git a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs index 989c9ef9..9d5b42be 100644 --- a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs +++ b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs @@ -48,9 +48,9 @@ public partial class FileRepository return Users.Where(x => x.AffiliateId == affiliateId).ToList(); } - public User? GetUserByUserName(string userName = null, string regionCode = "CN") + public User? GetUserByUserName(string userName = null) { - return Users.FirstOrDefault(x => x.UserName == userName.ToLower() && x.RegionCode == regionCode.ToLower()); + return Users.FirstOrDefault(x => x.UserName == userName.ToLower()); } public Dashboard? GetDashboard(string id = null) diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs index 991ef0df..a87c55fa 100644 --- a/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs +++ b/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs @@ -50,7 +50,7 @@ public class UserService : IUserService if (!string.IsNullOrWhiteSpace(user.UserName)) { - record = db.GetUserByUserName(user.UserName, regionCode: user.RegionCode); + record = db.GetUserByUserName(user.UserName); } if (record != null && record.Verified) @@ -214,7 +214,7 @@ public class UserService : IUserService var (id, password, regionCode) = base64.SplitAsTuple(":"); var db = _services.GetRequiredService(); - var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id, regionCode: regionCode); + var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id); if (record == null) { record = db.GetUserByPhone(id, regionCode: regionCode); @@ -384,7 +384,7 @@ public class UserService : IUserService } else if (_user.UserName != null) { - user = db.GetUserByUserName(_user.UserName, _user.RegionCode); + user = db.GetUserByUserName(_user.UserName); } else if (_user.Email != null) { @@ -471,7 +471,7 @@ public class UserService : IUserService { var id = model.UserName; var db = _services.GetRequiredService(); - var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id, regionCode: (string.IsNullOrWhiteSpace(model.RegionCode) ? "CN" : model.RegionCode)); + var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id); if (record == null) { record = db.GetUserByPhone(id, regionCode: (string.IsNullOrWhiteSpace(model.RegionCode) ? "CN" : model.RegionCode)); @@ -515,7 +515,7 @@ public class UserService : IUserService var db = _services.GetRequiredService(); - var user = db.GetUserByUserName(userName, regionCode: "CN"); + var user = db.GetUserByUserName(userName); if (user != null && user.Verified) { return true; diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs index c463541f..2c4676ca 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs @@ -61,9 +61,9 @@ public partial class MongoRepository return users?.Any() == true ? users.Select(x => x.ToUser()).ToList() : new List(); } - public User? GetUserByUserName(string userName, string regionCode = "CN") + public User? GetUserByUserName(string userName) { - var user = _dc.Users.AsQueryable().FirstOrDefault(x => x.UserName == userName.ToLower() && x.RegionCode == regionCode.ToLower()); + var user = _dc.Users.AsQueryable().FirstOrDefault(x => x.UserName == userName.ToLower()); return user != null ? user.ToUser() : null; } From 5369565701e159fb2a66bc65ce51cb2ba2b96e36 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Mon, 16 Dec 2024 13:04:00 +0800 Subject: [PATCH 12/14] fix: update UpdateExistUser API --- .../Repository/MongoRepository.User.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs index 2c4676ca..0c2eb95c 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs @@ -102,6 +102,7 @@ public partial class MongoRepository { var filter = Builders.Filter.Eq(x => x.Id, userId); var update = Builders.Update + .Set(x => x.UserName, user.UserName) .Set(x => x.Email, user.Email) .Set(x => x.Phone, user.Phone) .Set(x => x.Salt, user.Salt) From ae8e2d3100726b02f25fa262ed933c81803a9d35 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Mon, 16 Dec 2024 21:59:12 +0800 Subject: [PATCH 13/14] feat: add UpdateUserName API --- .../Repositories/IBotSharpRepository.cs | 1 + .../Repository/MongoRepository.User.cs | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs index 87d4fd99..35cb60df 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs @@ -33,6 +33,7 @@ public interface IBotSharpRepository : IHaveServiceProvider List GetUserByIds(List ids) => throw new NotImplementedException(); List GetUsersByAffiliateId(string affiliateId) => throw new NotImplementedException(); User? GetUserByUserName(string userName) => throw new NotImplementedException(); + void UpdateUserName(string userId, string userName) => throw new NotImplementedException(); Dashboard? GetDashboard(string id = null) => throw new NotImplementedException(); void CreateUser(User user) => throw new NotImplementedException(); void UpdateExistUser(string userId, User user) => throw new NotImplementedException(); diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs index 0c2eb95c..5dc088c5 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs @@ -113,6 +113,14 @@ public partial class MongoRepository _dc.Users.UpdateOne(filter, update); } + public void UpdateUserName(string userId, string userName) + { + var filter = Builders.Filter.Eq(x => x.Id, userId); + var update = Builders.Update + .Set(x => x.UserName, userName); + _dc.Users.UpdateOne(filter, update); + } + public void UpdateUserVerified(string userId) { var filter = Builders.Filter.Eq(x => x.Id, userId); From 5e70f10b83fef32b055ee5d2b4b22a994b24f7d3 Mon Sep 17 00:00:00 2001 From: AnonymousDotNet <18776095145@163.com> Date: Mon, 16 Dec 2024 22:01:06 +0800 Subject: [PATCH 14/14] revert: remove updated username --- .../Repository/MongoRepository.User.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs index 5dc088c5..f6bdbbdf 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs @@ -102,7 +102,6 @@ public partial class MongoRepository { var filter = Builders.Filter.Eq(x => x.Id, userId); var update = Builders.Update - .Set(x => x.UserName, user.UserName) .Set(x => x.Email, user.Email) .Set(x => x.Phone, user.Phone) .Set(x => x.Salt, user.Salt)