From e8656a99c01d88fc4a76456cabc189d5986c7483 Mon Sep 17 00:00:00 2001 From: Haiping Chen Date: Sat, 25 May 2024 20:34:29 -0500 Subject: [PATCH] Add new user verification code. --- .../Repositories/IBotSharpRepository.cs | 9 +-- .../Users/IUserService.cs | 2 + .../BotSharp.Abstraction/Users/Models/User.cs | 2 + .../Users/Models/UserActivationModel.cs | 7 +++ .../Users/Settings/AccountSetting.cs | 9 +++ .../BotSharp.Core/BotSharpCoreExtensions.cs | 5 ++ .../Repository/BotSharpDbContext.cs | 15 ----- .../FileRepository/FileRepository.User.cs | 9 +++ .../Users/Services/UserService.cs | 59 ++++++++++++++++++- .../Controllers/UserController.cs | 12 ++++ .../Collections/UserDocument.cs | 7 ++- .../Repository/MongoRepository.User.cs | 10 ++++ .../PlaywrightWebDriver.HttpRequest.cs | 1 + 13 files changed, 125 insertions(+), 22 deletions(-) create mode 100644 src/Infrastructure/BotSharp.Abstraction/Users/Models/UserActivationModel.cs create mode 100644 src/Infrastructure/BotSharp.Abstraction/Users/Settings/AccountSetting.cs diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs index a451071e..6adcc8ad 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs @@ -17,10 +17,11 @@ public interface IBotSharpRepository #endregion #region User - User? GetUserByEmail(string email); - User? GetUserById(string id); - User? GetUserByUserName(string userName); - void CreateUser(User user); + User? GetUserByEmail(string email) => throw new NotImplementedException(); + User? GetUserById(string id) => throw new NotImplementedException(); + User? GetUserByUserName(string userName) => throw new NotImplementedException(); + void CreateUser(User user) => throw new NotImplementedException(); + void UpdateUserVerified(string userId) => throw new NotImplementedException(); #endregion #region Agent diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/IUserService.cs b/src/Infrastructure/BotSharp.Abstraction/Users/IUserService.cs index debf68f4..8f314ffa 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Users/IUserService.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Users/IUserService.cs @@ -1,4 +1,5 @@ using BotSharp.Abstraction.Users.Models; +using BotSharp.OpenAPI.ViewModels.Users; namespace BotSharp.Abstraction.Users; @@ -6,6 +7,7 @@ public interface IUserService { Task GetUser(string id); Task CreateUser(User user); + Task ActiveUser(UserActivationModel model); Task GetToken(string authorization); Task GetMyProfile(); } \ No newline at end of file diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/Models/User.cs b/src/Infrastructure/BotSharp.Abstraction/Users/Models/User.cs index 7ca441fe..4e6ca265 100644 --- a/src/Infrastructure/BotSharp.Abstraction/Users/Models/User.cs +++ b/src/Infrastructure/BotSharp.Abstraction/Users/Models/User.cs @@ -14,6 +14,8 @@ public class User public string Source { get; set; } = "internal"; public string? ExternalId { get; set; } public string Role { get; set; } = UserRole.Client; + public string? VerificationCode { get; set; } + public bool Verified { get; set; } public DateTime UpdatedTime { get; set; } = DateTime.UtcNow; public DateTime CreatedTime { get; set; } = DateTime.UtcNow; } diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/Models/UserActivationModel.cs b/src/Infrastructure/BotSharp.Abstraction/Users/Models/UserActivationModel.cs new file mode 100644 index 00000000..904bd936 --- /dev/null +++ b/src/Infrastructure/BotSharp.Abstraction/Users/Models/UserActivationModel.cs @@ -0,0 +1,7 @@ +namespace BotSharp.OpenAPI.ViewModels.Users; + +public class UserActivationModel +{ + public string UserName { get; set; } + public string VerificationCode { get; set; } +} diff --git a/src/Infrastructure/BotSharp.Abstraction/Users/Settings/AccountSetting.cs b/src/Infrastructure/BotSharp.Abstraction/Users/Settings/AccountSetting.cs new file mode 100644 index 00000000..06176ce6 --- /dev/null +++ b/src/Infrastructure/BotSharp.Abstraction/Users/Settings/AccountSetting.cs @@ -0,0 +1,9 @@ +namespace BotSharp.Abstraction.Users.Settings; + +public class AccountSetting +{ + /// + /// Whether to enable verification code to verify the authenticity of new users + /// + public bool NewUserVerification { get; set; } +} diff --git a/src/Infrastructure/BotSharp.Core/BotSharpCoreExtensions.cs b/src/Infrastructure/BotSharp.Core/BotSharpCoreExtensions.cs index 51f3eb1d..2dd2dc7f 100644 --- a/src/Infrastructure/BotSharp.Core/BotSharpCoreExtensions.cs +++ b/src/Infrastructure/BotSharp.Core/BotSharpCoreExtensions.cs @@ -5,6 +5,7 @@ using BotSharp.Core.Plugins; using BotSharp.Abstraction.Settings; using BotSharp.Abstraction.Options; using BotSharp.Abstraction.Messaging.JsonConverters; +using BotSharp.Abstraction.Users.Settings; namespace BotSharp.Core; @@ -84,6 +85,10 @@ public static class BotSharpCoreExtensions return settingService.Bind("PluginLoader"); }); + var accountSettings = new AccountSetting(); + config.Bind("Account", accountSettings); + services.AddScoped(x => accountSettings); + var loader = new PluginLoader(services, config, pluginSettings); loader.Load(assembly => { diff --git a/src/Infrastructure/BotSharp.Core/Repository/BotSharpDbContext.cs b/src/Infrastructure/BotSharp.Core/Repository/BotSharpDbContext.cs index 28aac06b..6bba6c2a 100644 --- a/src/Infrastructure/BotSharp.Core/Repository/BotSharpDbContext.cs +++ b/src/Infrastructure/BotSharp.Core/Repository/BotSharpDbContext.cs @@ -1,6 +1,5 @@ using BotSharp.Abstraction.Loggers.Models; using BotSharp.Abstraction.Plugins.Models; -using BotSharp.Abstraction.Repositories.Models; using BotSharp.Abstraction.Tasks.Models; using BotSharp.Abstraction.Users.Models; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -176,20 +175,6 @@ public class BotSharpDbContext : Database, IBotSharpRepository => throw new NotImplementedException(); #endregion - #region User - public User? GetUserByEmail(string email) - => throw new NotImplementedException(); - - public User? GetUserById(string id) - => throw new NotImplementedException(); - - public User? GetUserByUserName(string userName) - => throw new NotImplementedException(); - - public void CreateUser(User user) - => throw new NotImplementedException(); - #endregion - #region Execution Log public void AddExecutionLogs(string conversationId, List logs) { diff --git a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs index bc992a08..36f17b85 100644 --- a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs +++ b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs @@ -32,4 +32,13 @@ public partial class FileRepository var path = Path.Combine(dir, "user.json"); File.WriteAllText(path, JsonSerializer.Serialize(user, _options)); } + + public void UpdateUserVerified(string userId) + { + var user = GetUserById(userId); + user.Verified = true; + var dir = Path.Combine(_dbSettings.FileRepository, "users", user.Id); + var path = Path.Combine(dir, "user.json"); + File.WriteAllText(path, JsonSerializer.Serialize(user, _options)); + } } diff --git a/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs b/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs index 4324b6f7..ae5220b9 100644 --- a/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs +++ b/src/Infrastructure/BotSharp.Core/Users/Services/UserService.cs @@ -1,4 +1,6 @@ using BotSharp.Abstraction.Users.Models; +using BotSharp.Abstraction.Users.Settings; +using BotSharp.OpenAPI.ViewModels.Users; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using NanoidDotNet; @@ -12,12 +14,17 @@ public class UserService : IUserService private readonly IServiceProvider _services; private readonly IUserIdentity _user; private readonly ILogger _logger; + private readonly AccountSetting _setting; - public UserService(IServiceProvider services, IUserIdentity user, ILogger logger) + public UserService(IServiceProvider services, + IUserIdentity user, + ILogger logger, + AccountSetting setting) { _services = services; _user = user; _logger = logger; + _setting = setting; } public async Task CreateUser(User user) @@ -51,6 +58,12 @@ public class UserService : IUserService record.Salt = Guid.NewGuid().ToString("N"); record.Password = Utilities.HashText(user.Password, record.Salt); + if (_setting.NewUserVerification) + { + record.VerificationCode = Nanoid.Generate(alphabet: "0123456789", size: 6); + record.Verified = false; + } + db.CreateUser(record); _logger.LogWarning($"Created new user account: {record.Id} {record.UserName}"); @@ -120,6 +133,11 @@ public class UserService : IUserService return default; } + if (_setting.NewUserVerification && !record.Verified) + { + return default; + } + #if !DEBUG if (Utilities.HashText(password, record.Salt) != record.Password) { @@ -206,4 +224,43 @@ public class UserService : IUserService var user = db.GetUserById(id); return user; } + + public async Task ActiveUser(UserActivationModel model) + { + var id = model.UserName; + var db = _services.GetRequiredService(); + var record = id.Contains("@") ? db.GetUserByEmail(id) : db.GetUserByUserName(id); + if (record == null) + { + record = db.GetUserByUserName(id); + } + + if (record == null) + { + return default; + } + + if (record.VerificationCode != model.VerificationCode) + { + return default; + } + + if (record.Verified) + { + return default; + } + + db.UpdateUserVerified(record.Id); + + var accessToken = GenerateJwtToken(record); + var jwt = new JwtSecurityTokenHandler().ReadJwtToken(accessToken); + var token = new Token + { + AccessToken = accessToken, + ExpireTime = jwt.Payload.Exp.Value, + TokenType = "Bearer", + Scope = "api" + }; + return token; + } } diff --git a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs index e4201aa8..317d1fc9 100644 --- a/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs +++ b/src/Infrastructure/BotSharp.OpenAPI/Controllers/UserController.cs @@ -61,6 +61,18 @@ public class UserController : ControllerBase return UserViewModel.FromUser(createdUser); } + [AllowAnonymous] + [HttpPost("/user/activate")] + public async Task> ActivateUser(UserActivationModel model) + { + var token = await _userService.ActiveUser(model); + if (token == null) + { + return Unauthorized(); + } + return Ok(token); + } + [HttpGet("/user/me")] public async Task GetMyUserProfile() { diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/UserDocument.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/UserDocument.cs index c21a6e08..c277b9f3 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/UserDocument.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/UserDocument.cs @@ -13,7 +13,8 @@ public class UserDocument : MongoBase public string Source { get; set; } = "internal"; public string? ExternalId { get; set; } public string Role { get; set; } - + public string? VerificationCode { get; set; } + public bool Verified { get; set; } public DateTime CreatedTime { get; set; } public DateTime UpdatedTime { get; set; } @@ -30,7 +31,9 @@ public class UserDocument : MongoBase Salt = Salt, Source = Source, ExternalId = ExternalId, - Role = Role + Role = Role, + VerificationCode = VerificationCode, + Verified = Verified, }; } } \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs index 1b6b8b77..1a5211f4 100644 --- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs +++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.User.cs @@ -40,10 +40,20 @@ public partial class MongoRepository Source = user.Source, ExternalId = user.ExternalId, Role = user.Role, + VerificationCode = user.VerificationCode, + Verified = user.Verified, CreatedTime = DateTime.UtcNow, UpdatedTime = DateTime.UtcNow }; _dc.Users.InsertOne(userCollection); } + + public void UpdateUserVerified(string userId) + { + var filter = Builders.Filter.Eq(x => x.Id, userId); + var update = Builders.Update.Set(x => x.Verified, true) + .Set(x => x.UpdatedTime, DateTime.UtcNow); + _dc.Users.UpdateOne(filter, update); + } } diff --git a/src/Plugins/BotSharp.Plugin.WebDriver/Drivers/PlaywrightDriver/PlaywrightWebDriver.HttpRequest.cs b/src/Plugins/BotSharp.Plugin.WebDriver/Drivers/PlaywrightDriver/PlaywrightWebDriver.HttpRequest.cs index 4a0177a0..a769332b 100644 --- a/src/Plugins/BotSharp.Plugin.WebDriver/Drivers/PlaywrightDriver/PlaywrightWebDriver.HttpRequest.cs +++ b/src/Plugins/BotSharp.Plugin.WebDriver/Drivers/PlaywrightDriver/PlaywrightWebDriver.HttpRequest.cs @@ -27,6 +27,7 @@ public partial class PlaywrightWebDriver try { + _logger.LogInformation($"SendHttpRequest: {args.Url}"); var response = await EvaluateScript(message.ContextId, script); result.IsSuccess = true; result.Body = JsonSerializer.Serialize(response);