diff --git a/Configuration/XBotServiceConfiguration.cs b/Configuration/XBotServiceConfiguration.cs index 677c39b..5291fc6 100644 --- a/Configuration/XBotServiceConfiguration.cs +++ b/Configuration/XBotServiceConfiguration.cs @@ -15,7 +15,7 @@ namespace xBotService.Configuration /// /// Verification Code Time to Live in Minute ... /// - public int VerificationCodeTTL { get; set; } = 300; + public int VerificationCodeTTL { get; set; } = 5; /// /// Default Timeout ... diff --git a/Constants/XBotMessageIds.cs b/Constants/XBotMessageIds.cs index 0a3bbfe..93bac4d 100644 --- a/Constants/XBotMessageIds.cs +++ b/Constants/XBotMessageIds.cs @@ -10,5 +10,6 @@ namespace xBotService.Constants این کد را با ورود به سامانه در بخش پروفایل کاربری وارد کنید """; public const string XBotRequestVerificationCodeMessageText = "برای دریافت کد اعتبارسنجی روی دکمه زیر کلیک کنید:"; + public const string XBotUserVerificationSucceedMessageText = "کاربر گرامی، اعتبار سنجی شما با موفقیت انجام شد."; } } \ No newline at end of file diff --git a/Controllers/XBotProviderControllerBase.cs b/Controllers/XBotProviderControllerBase.cs index 042e512..827ffc6 100644 --- a/Controllers/XBotProviderControllerBase.cs +++ b/Controllers/XBotProviderControllerBase.cs @@ -12,19 +12,22 @@ using System.Collections.Generic; using xIdentityService.Interfaces; using xIdentityService.Controllers; using Microsoft.Extensions.Logging; +using xBotService.Reciever; namespace xBotService.Controllers { public abstract class XBotProviderControllerBase : XBaseIdentityApiV1Controller { private readonly IXBotProvider botProvider; + private readonly XBotBotUpdateRecieverBackgroundService botHandler; protected XBotProviderControllerBase( IXBotProvider botProvider, - ILogger logger, XAppConfiguration appConfiguration, IXIdentityProvider identityProvider, - XValidationProvider validationProvider + XValidationProvider validationProvider, + ILogger logger, + XBotBotUpdateRecieverBackgroundService botHandler ) : base( logger, appConfiguration, @@ -33,6 +36,7 @@ namespace xBotService.Controllers ) { this.botProvider = botProvider; + this.botHandler = botHandler; } // @@ -130,200 +134,97 @@ namespace xBotService.Controllers } } - // [HttpPost("{chatId}/ShowVerificationMenu")] - // public virtual async Task> ShowVerificationMenu( - // [FromRoute] long chatId, - // CancellationToken cancellationToken = default - // ) - // { - // // - // try - // { - // // - // // Validation ... - // if (!ModelState.IsValid) - // { - // XException.InvalidArgs.Throw(); - // } - // if (chatId <= 0) - // { - // XException.InvalidArgs.Throw(); - // } + [HttpPost("{botUserId}/ShowVerificationMenu")] + public virtual async Task> ShowVerificationMenu( + [FromRoute] long botUserId, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validation ... + if (botUserId <= 0) + { + XException.InvalidArgs.Throw(); + } - // // - // var result = await botProvider.SendVerificationMenu( - // chatId: chatId, - // cancellationToken: cancellationToken - // ); + // + var result = await botProvider.ShowVerificationMenu( + botUserId: botUserId, + cancellationToken: cancellationToken + ); - // // - // return Ok(result.ToDynamicObject()); - // } - // catch (Exception ex) - // { - // // - // var result = GetExceptionActionResult(ex); - // return result; - // } - // } + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } - // [HttpPost("{chatId}/SendVerificationCode")] - // public virtual async Task> SendVerificationCode( - // [FromRoute] long chatId, - // [FromQuery] string code, - // [FromQuery] int ttlSeconds, - // CancellationToken cancellationToken = default - // ) - // { - // // - // try - // { - // // - // // Validation ... - // if (!ModelState.IsValid) - // { - // XException.InvalidArgs.Throw(); - // } - // if (chatId <= 0 || code.IsNullOrEmpty() || ttlSeconds < 60) - // { - // XException.InvalidArgs.Throw(); - // } + [HttpPost("{token}/VerifyUser")] + public virtual async Task> VerifyUser( + [FromRoute] string token, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validation ... + if (token.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } - // // - // var result = await botProvider.SendVerificationCode( - // code: code, - // chatId: chatId, - // ttlSeconds: ttlSeconds, - // cancellationToken: cancellationToken - // ); + // + var userInfo = await GetUserInfo(); - // // - // return Ok(result.ToDynamicObject()); - // } - // catch (Exception ex) - // { - // // - // var result = GetExceptionActionResult(ex); - // return result; - // } - // } + // + var result = await botProvider.VerifyUser( + token: token, + userInfo: userInfo, + cancellationToken: cancellationToken + ); - // [HttpPost("{id}/AnswerCallback")] - // public virtual async Task> AnswerCallbackQuery( - // [FromRoute] string callbackQueryId, - // [FromQuery] string text = null, - // [FromQuery] bool showAlert = false, - // CancellationToken cancellationToken = default - // ) - // { - // // - // try - // { - // // - // // Validation ... - // if (!ModelState.IsValid || - // callbackQueryId.IsNullOrEmpty()) - // { - // XException.InvalidArgs.Throw(); - // } + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } - // // - // var result = await botProvider.AnswerCallbackQuery( - // text: text, - // showAlert: showAlert, - // callbackQueryId: callbackQueryId, - // cancellationToken: cancellationToken - // ); + [HttpPost("Refresh")] + public virtual async Task Refresh( + CancellationToken cancellationToken = default + ) + { + // + try + { + // + await botHandler.Refresh(cancellationToken); - // // - // return Ok(result.ToDynamicObject()); - // } - // catch (Exception ex) - // { - // // - // var result = GetExceptionActionResult(ex); - // return result; - // } - // } - - // [HttpPost("{chatId}/RemoveInlineKeyboard")] - // public virtual async Task> RemoveInlineKeyboard( - // [FromRoute] long chatId, - // [FromQuery] long messageId, - // CancellationToken cancellationToken = default - // ) - // { - // // - // try - // { - // // - // // Validation ... - // if (!ModelState.IsValid) - // { - // XException.InvalidArgs.Throw(); - // } - // if (chatId <= 0 || messageId <= 0) - // { - // XException.InvalidArgs.Throw(); - // } - - // // - // var result = await botProvider.RemoveInlineKeyboard( - // chatId: chatId, - // messageId: messageId, - // cancellationToken: cancellationToken - // ); - - // // - // return Ok(result.ToDynamicObject()); - // } - // catch (Exception ex) - // { - // // - // var result = GetExceptionActionResult(ex); - // return result; - // } - // } - - // [HttpPost("Webhook")] - // public virtual async Task> SetWebhook( - // [FromQuery] string webhookUrl, - // [FromQuery] string secretToken = null, - // CancellationToken cancellationToken = default - // ) - // { - // // - // try - // { - // // - // // Validation ... - // if (!ModelState.IsValid) - // { - // XException.InvalidArgs.Throw(); - // } - // await ValidationProvider - // .GroupValidationBuilder() - // .AddNotEmpty(webhookUrl) - // .AddUrl(webhookUrl) - // .ValidateGroupAsync(); - - // // - // var result = await botProvider.SetWebhook( - // webhookUrl: webhookUrl, - // secretToken: secretToken, - // cancellationToken: cancellationToken - // ); - - // // - // return Ok(result); - // } - // catch (Exception ex) - // { - // // - // var result = GetExceptionActionResult(ex); - // return result; - // } - // } + // + return Ok(); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } #endregion } } \ No newline at end of file diff --git a/Interfaces/IXBotProvider.cs b/Interfaces/IXBotProvider.cs index fa66f97..28f6790 100644 --- a/Interfaces/IXBotProvider.cs +++ b/Interfaces/IXBotProvider.cs @@ -5,11 +5,12 @@ using System.Threading.Tasks; using System.Collections.Generic; using xCommons.Extensions; using xBotService.Models.Dtos; +using xIdentityModels.Models; namespace xBotService.Interfaces { public interface IXBotProvider - { + { /// /// Retrieve Bot Info ... /// @@ -29,7 +30,7 @@ namespace xBotService.Interfaces XBotUpdatesRequest requestModel, CancellationToken cancellationToken = default ); - + /// /// Sending Simple String Message to Bot ... /// @@ -49,7 +50,7 @@ namespace xBotService.Interfaces /// /// Task ShowVerificationMenu( - long botUserId, + long botUserId, string label = XBotMessageIds.XBotRequestVerificationCodeLabel, CancellationToken cancellationToken = default ); @@ -57,53 +58,25 @@ namespace xBotService.Interfaces /// /// Send Verification Code to Requests ... /// - /// + /// /// /// Task SendVerificationCode( - XBotUserDto botUser, + long botUserId, CancellationToken cancellationToken = default ); /// - /// an Accept for Exit Loading on Bot ... + /// Verify User Subscription ... /// - /// - /// - /// + /// + /// /// /// - // Task AnswerCallbackQuery( - // string callbackQueryId, - // string text = null, - // bool showAlert = false, - // CancellationToken cancellationToken = default - // ); - - /// - /// Remove Inline Keyboard After Click (Optional) ... - /// - /// - /// - /// - /// - // Task RemoveInlineKeyboard( - // long chatId, - // long messageId, - // CancellationToken cancellationToken = default - // ); - - /// - /// Set Webhook for Retrieve Messages on Recieved ... - /// - /// - /// - /// - /// - // Task SetWebhook( - // string webhookUrl, - // string secretToken = null, - // CancellationToken cancellationToken = default - // ); + Task VerifyUser( + string token, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); } } \ No newline at end of file diff --git a/Models/Dtos/XBotUserDto.cs b/Models/Dtos/XBotUserDto.cs index bee0a81..6daa865 100644 --- a/Models/Dtos/XBotUserDto.cs +++ b/Models/Dtos/XBotUserDto.cs @@ -32,6 +32,12 @@ namespace xBotService.Models.Dtos /// public bool ShownVirificationMenu { get; set; } + /// + /// Verification Code ... + /// + /// + public string VerificationCode { get; set; } + /// /// Verified On ... /// diff --git a/Models/Entities/XBotUser.cs b/Models/Entities/XBotUser.cs index 78c2105..c911094 100644 --- a/Models/Entities/XBotUser.cs +++ b/Models/Entities/XBotUser.cs @@ -25,6 +25,12 @@ namespace xBotService.Models.Entities /// public bool ShownVirificationMenu { get; set; } + /// + /// Verification Code ... + /// + /// + public string VerificationCode { get; set; } + /// /// Verified On ... /// diff --git a/Providers/GraphQL/XBotUserGraphType.cs b/Providers/GraphQL/XBotUserGraphType.cs index 92ef7fc..b56700c 100644 --- a/Providers/GraphQL/XBotUserGraphType.cs +++ b/Providers/GraphQL/XBotUserGraphType.cs @@ -13,6 +13,7 @@ namespace xBotService.Providers.GraphQL Field(x => x.BotUserName); Field(x => x.BotLastname); Field(x => x.BotFirstname); + Field(x => x.VerificationCode); Field(x => x.LastVerificationSent); Field(x => x.ShownVirificationMenu); } diff --git a/Providers/XBotProvider.cs b/Providers/XBotProvider.cs index 4ea9b88..e609a22 100644 --- a/Providers/XBotProvider.cs +++ b/Providers/XBotProvider.cs @@ -17,6 +17,7 @@ using xExceptions.Constants; using System; using xBotService.Models.Dtos; using xIdentityService.Security; +using xBotService.Interfaces.Dtos; namespace xBotService.Providers { @@ -28,21 +29,24 @@ namespace xBotService.Providers private readonly IXIdentityHttpProvider httpProvider; private readonly XValidationProvider validationProvider; private readonly XBotServiceConfiguration configuration; + private readonly IXBotUserServiceProvider botUserServiceProvider; public XBotProvider( ILogger logger, IXSecurityProvider securityProvider, IXIdentityHttpProvider httpProvider, XValidationProvider validationProvider, - XBotServiceConfiguration configuration + XBotServiceConfiguration configuration, + IXBotUserServiceProvider botUserServiceProvider ) { // this.logger = logger; - this.securityProvider = securityProvider; this.httpProvider = httpProvider; this.configuration = configuration; + this.securityProvider = securityProvider; this.validationProvider = validationProvider; + this.botUserServiceProvider = botUserServiceProvider; } // @@ -253,6 +257,13 @@ namespace xBotService.Providers XException.InvalidArgs.Throw(); } + // + // Normalize ... + if (label.IsNullOrEmpty()) + { + label = XBotMessageIds.XBotRequestVerificationCodeLabel; + } + // // Markup for Keyboards ... var markup = XBotReplyMarkup @@ -289,16 +300,29 @@ namespace xBotService.Providers /// /// Send Verification Code to Requests ... /// - /// + /// /// /// public virtual async Task SendVerificationCode( - XBotUserDto botUser, + long botUserId, CancellationToken cancellationToken = default ) { // // Validate ... + if (botUserId <= 0) + { + XException.InvalidArgs.Throw(); + } + + // + // Check Bot User Exists ... + var botUser = await botUserServiceProvider.FindOneAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: x => x.BotUserId.Equals(botUserId) + ); if ( botUser.IsNullOrDefault() || botUser.BotUserId <= 0) @@ -314,20 +338,22 @@ namespace xBotService.Providers } // - var code = securityProvider - .Encrypt(botUser.BotUserId.ToString()) - .ToMd5String(); + var verifiedTime = DateTime.UtcNow; + var code = CalculateVerificationCode( + user: botUser, + verifiedTime: verifiedTime + ); // var message = XBotMessageIds.XBotVerificationCodeMessageText .ApplyTemplates(new Dictionary { - { XBotParams.XVerificationTokenParam, code }, + { XBotParams.XVerificationTokenParam, code }, { XBotParams.XTTLInMinuteParam, configuration.VerificationCodeTTL.ToString() }, }); - + // - var response = await SendMessage( + var result = await SendMessage( cancellationToken: cancellationToken, requestModel: new XBotSendMessageRequest { @@ -335,158 +361,152 @@ namespace xBotService.Providers ChatId = botUser.BotUserId, } ); + if (!result.IsNullOrDefault()) + { + // + // Update Bot User ... + botUser.VerificationCode = code; + botUser.LastVerificationSent = verifiedTime; + botUser = await botUserServiceProvider.UpdateAsync( + item: botUser, + id: botUser.Id, + saveChanges: true, + connectionId: null, + cancellationToken: cancellationToken + ); + } // - return response; + return result; } /// - /// an Accept for Exit Loading on Bot ... + /// Verify User Subscription ... /// - /// - /// - /// + /// + /// /// /// - // public virtual async Task AnswerCallbackQuery( - // string callbackQueryId, - // string text = null, - // bool showAlert = false, - // CancellationToken cancellationToken = default - // ) - // { - // // - // // Validation ... - // validationProvider.GroupValidationBuilder() - // .AddNotEmpty(callbackQueryId) - // .ValidateGroup(); + public virtual async Task VerifyUser( + string token, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + if (!token.IsMD5String() || + token.IsNullOrEmpty() || + userInfo.IsNullOrDefault()) + { + XException.InvalidArgs.Throw(); + } - // // - // var client = GetRestClient(); - // var request = GetRestRequest( - // endpoint: XBotEndpoints.AnswerCallbackQuery, - // @params: new Dictionary - // { - // { XBotParams.XTokenParam, configuration.Token } - // } - // ); + // + // Detect Verified User ... + var botUser = await botUserServiceProvider.FindOneAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + predicate: x => + x.LastVerificationSent.HasValue && + x.VerificationCode.Equals(token) + ); + if (botUser.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } - // // - // request.AddJsonBody(new - // { - // text = text, - // show_alert = showAlert, - // callback_query_id = callbackQueryId, - // }); + // + // Check Verification Code is Valid ... + var userCode = CalculateVerificationCode( + user: botUser, + verifiedTime: botUser.LastVerificationSent.Value + ); + if (!token.Equals(userCode)) + { + XException.NotAllowed.Throw(); + } - // // - // var response = await httpProvider.RunRestRequest( - // client: client, - // request: request, - // method: XHttpMethod.POST, - // cancellationToken: cancellationToken - // ); + // + // Validate Toke Life Time ... + var isExpired = botUser.LastVerificationSent.Value + .IsExpiredTTL(configuration.VerificationCodeTTL * 60); + if (isExpired) + { + // + // Cleanup User Verification Info ... + botUser.VerificationCode = null; + botUser.LastVerificationSent = null; + botUser.ShownVirificationMenu = false; - // // - // return response; - // } + // + botUser = await botUserServiceProvider.UpdateAsync( + item: botUser, + id: botUser.Id, + saveChanges: true, + connectionId: null, + cancellationToken: cancellationToken + ); - /// - /// Remove Inline Keyboard After Click (Optional) ... - /// - /// - /// - /// - /// - // public virtual async Task RemoveInlineKeyboard( - // long chatId, - // long messageId, - // CancellationToken cancellationToken = default - // ) - // { - // // - // // Validation ... - // if (chatId <= 0 || messageId <= 0) - // { - // XException.InvalidArgs.Throw(); - // } + // + XException.ExpiredDate.Throw(); + } - // // - // var client = GetRestClient(); - // var request = GetRestRequest( - // endpoint: XBotEndpoints.EditMessageReplyMarkup, - // @params: new Dictionary - // { - // { XBotParams.XTokenParam, configuration.Token } - // } - // ); + // + // Make User Valid ... + botUser.VerificationCode = null; + botUser.UserId = userInfo.UserId; + botUser.LastVerificationSent = null; + botUser.VerifiedOn = DateTime.UtcNow; + botUser.ShownVirificationMenu = false; - // // - // request.AddJsonBody(new - // { - // chat_id = chatId, - // message_id = messageId, - // reply_markup = new { inline_keyboard = new List>() } - // }); + // + botUser = await botUserServiceProvider.UpdateAsync( + item: botUser, + id: botUser.Id, + saveChanges: true, + connectionId: null, + cancellationToken: cancellationToken + ); - // // - // var response = await httpProvider.RunRestRequest( - // client: client, - // request: request, - // method: XHttpMethod.POST, - // cancellationToken: cancellationToken - // ); + // + // Send User Verification Message ... + var result = await SendMessage( + cancellationToken: cancellationToken, + requestModel: new XBotSendMessageRequest + { + ChatId = botUser.BotUserId, + Text = XBotMessageIds.XBotUserVerificationSucceedMessageText + } + ); - // // - // return response; - // } - - /// - /// Set Webhook for Retrieve Messages on Recieved ... - /// - /// - /// - /// - /// - // public virtual async Task SetWebhook( - // string webhookUrl, - // string secretToken = null, - // CancellationToken cancellationToken = default - // ) - // { - // // - // var client = GetRestClient(); - // var request = GetRestRequest( - // endpoint: XBotEndpoints.SetWebhook, - // @params: new Dictionary - // { - // { XBotParams.XTokenParam, configuration.Token } - // } - // ); - - // // - // request.AddJsonBody(new - // { - // url = webhookUrl, - // secret_token = secretToken - // }); - - // // - // var iResponse = await httpProvider.RunRestRequest( - // client: client, - // request: request, - // method: XHttpMethod.POST, - // cancellationToken: cancellationToken - // ); - // var response = iResponse?.Ok ?? false; - - // // - // return response; - // } + // + return result; + } #endregion // #region Private ... + /// + /// Calculate Verification Code ... + /// + /// + /// + /// + private string CalculateVerificationCode( + XBotUserDto user, + DateTime verifiedTime + ) + { + // + var result = securityProvider + .Encrypt($"{user.BotUserId}{verifiedTime}") + .ToMd5String(); + + // + return result; + } #endregion } } \ No newline at end of file diff --git a/Reciever/XBotBotUpdateRecieverBackgroundService.cs b/Reciever/XBotBotUpdateRecieverBackgroundService.cs index 21c8933..0581184 100644 --- a/Reciever/XBotBotUpdateRecieverBackgroundService.cs +++ b/Reciever/XBotBotUpdateRecieverBackgroundService.cs @@ -190,8 +190,9 @@ namespace xBotService.Reciever { // await HandleBotAction( + botUser: item, update: update, - botUserDto: item + cancellationToken: cancellationToken ); return; } @@ -230,11 +231,13 @@ namespace xBotService.Reciever /// Handle Bot Sent Commands ... /// /// - /// + /// + /// /// public async Task HandleBotAction( XBotUpdateResponse update, - XBotUserDto botUserDto + XBotUserDto botUser, + CancellationToken cancellationToken = default ) { // @@ -262,6 +265,10 @@ namespace xBotService.Reciever // // Remove Inline Keyboard ... // And Send Verification ... + await botProvider.SendVerificationCode( + botUserId: botUser.BotUserId, + cancellationToken: cancellationToken + ); break; } }