Skip to content

Commit 3fe9df0

Browse files
committed
Add authorization mechanism for Telegram bot messages
Introduce a new authorization mechanism to enhance bot security. - Add `TelegramBot.Attributes` namespace in `BotApp.cs`. - Implement `AuthorizeAttribute` to mark methods/controllers. - Retrieve `IBotAuthorizationHandler` for authorization logic. - Handle unauthorized access without executing the method. - Update parameter count check to handle null `args`.
1 parent 7218207 commit 3fe9df0

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Sources/TelegramBot/BotApp.cs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
using Microsoft.Extensions.DependencyInjection;
1515
using Microsoft.Extensions.Hosting;
1616
using Newtonsoft.Json.Linq;
17+
using TelegramBot.Attributes;
1718

1819
namespace TelegramBot
1920
{
@@ -207,15 +208,29 @@ private async Task HandleRequestAsync(ITelegramUpdateHandler handler, Update upd
207208
_logger.LogWarning("Method not found for message: {Text}.", update.Message?.Text);
208209
return;
209210
}
211+
if (method.GetCustomAttribute<AuthorizeAttribute>() != null
212+
|| method.DeclaringType?.GetCustomAttribute<AuthorizeAttribute>() != null)
213+
{
214+
if (_serviceProvider.GetService<IBotAuthorizationHandler>() is IBotAuthorizationHandler authorizationHandler)
215+
{
216+
if (!authorizationHandler.Authorize(user))
217+
{
218+
await authorizationHandler
219+
.HandleUnauthorized(user)
220+
.ExecuteResultAsync(new ActionContext(_client, user.Id));
221+
return;
222+
}
223+
}
224+
}
210225
if (method.ReturnType != typeof(Task<IActionResult>) && method.ReturnType != typeof(IActionResult))
211226
{
212227
throw new InvalidOperationException("Invalid return type: " + method.ReturnType.Name);
213228
}
214-
if (method.GetParameters().Length != args?.Length)
229+
if (args != null && method.GetParameters().Length != args?.Length)
215230
{
216231
throw new InvalidOperationException("Invalid arguments count: " + args?.Length);
217232
}
218-
BotControllerBase controller = (BotControllerBase)ActivatorUtilities.CreateInstance(_serviceProvider, method.DeclaringType);
233+
BotControllerBase controller = (BotControllerBase)ActivatorUtilities.CreateInstance(_serviceProvider, method.DeclaringType!);
219234
controller.Update = update;
220235
controller.User = user;
221236
if (_serviceProvider.GetService<IKeyValueProvider>() is IKeyValueProvider keyValueProvider)

0 commit comments

Comments
 (0)