feat: created auth hook on TClient
This commit is contained in:
parent
f115760713
commit
970526d84e
@ -14,6 +14,7 @@ public class HeadHunterService(
|
|||||||
IChannel channel,
|
IChannel channel,
|
||||||
ILogger<HeadHunterService> logger,
|
ILogger<HeadHunterService> logger,
|
||||||
IOptions<HeadHunterConfig> config,
|
IOptions<HeadHunterConfig> config,
|
||||||
|
IWebHostEnvironment env,
|
||||||
AppDbContext dbContext)
|
AppDbContext dbContext)
|
||||||
{
|
{
|
||||||
public enum Status
|
public enum Status
|
||||||
@ -47,45 +48,54 @@ public class HeadHunterService(
|
|||||||
return Status.UserAuthRejectedError;
|
return Status.UserAuthRejectedError;
|
||||||
}
|
}
|
||||||
|
|
||||||
using var client = new HttpClient();
|
HeadHunterTokenResponseDto? responseDto;
|
||||||
var form = new Dictionary<string, string>
|
if (!env.IsDevelopment()) //Production server
|
||||||
{
|
{
|
||||||
{ "client_id", _config.ClientId },
|
using var client = new HttpClient();
|
||||||
{ "client_secret", _config.Secret },
|
var form = new Dictionary<string, string>
|
||||||
{ "code", authorizationCode },
|
|
||||||
{ "grant_type", "authorization_code" },
|
|
||||||
{ "redirect_uri", GetRedirectUrl(userId) }
|
|
||||||
};
|
|
||||||
client.BaseAddress = new UriBuilder(_config.Links.HeadHunterApiDomain)
|
|
||||||
{
|
|
||||||
Port = -1,
|
|
||||||
Scheme = "https"
|
|
||||||
}.Uri;
|
|
||||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("Jobot BackEnd Service");
|
|
||||||
|
|
||||||
using var res = await client.SendAsync(
|
|
||||||
new HttpRequestMessage(
|
|
||||||
HttpMethod.Post,
|
|
||||||
_config.Links.HeadHunterTokenRoute)
|
|
||||||
{
|
{
|
||||||
Content = new FormUrlEncodedContent(form)
|
{ "client_id", _config.ClientId },
|
||||||
});
|
{ "client_secret", _config.Secret },
|
||||||
|
{ "code", authorizationCode },
|
||||||
|
{ "grant_type", "authorization_code" },
|
||||||
|
{ "redirect_uri", GetRedirectUrl(userId) }
|
||||||
|
};
|
||||||
|
client.BaseAddress = new UriBuilder(_config.Links.HeadHunterApiDomain)
|
||||||
|
{
|
||||||
|
Port = -1,
|
||||||
|
Scheme = "https"
|
||||||
|
}.Uri;
|
||||||
|
client.DefaultRequestHeaders.UserAgent.ParseAdd("Jobot BackEnd Service");
|
||||||
|
|
||||||
if (!res.IsSuccessStatusCode)
|
using var res = await client.SendAsync(
|
||||||
{
|
new HttpRequestMessage(
|
||||||
logger.LogWarning($"Response of HttpRequest {_config.Links.HeadHunterApiDomain}" +
|
HttpMethod.Post,
|
||||||
$"{_config.Links.HeadHunterTokenRoute} has unsuccessful status code {res.StatusCode}");
|
_config.Links.HeadHunterTokenRoute)
|
||||||
logger.LogWarning($"{res.Content.ReadAsStringAsync().Result}");
|
{
|
||||||
return Status.HeadHunterAuthRejectedError;
|
Content = new FormUrlEncodedContent(form)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
logger.LogWarning($"Response of HttpRequest {_config.Links.HeadHunterApiDomain}" +
|
||||||
|
$"{_config.Links.HeadHunterTokenRoute} has unsuccessful status code {res.StatusCode}");
|
||||||
|
logger.LogWarning($"{res.Content.ReadAsStringAsync().Result}");
|
||||||
|
return Status.HeadHunterAuthRejectedError;
|
||||||
|
}
|
||||||
|
|
||||||
|
responseDto =
|
||||||
|
JsonSerializer.Deserialize<HeadHunterTokenResponseDto>(await res.Content.ReadAsStringAsync());
|
||||||
|
|
||||||
|
if (responseDto == null)
|
||||||
|
{
|
||||||
|
logger.LogWarning($"User {userId} auth completed with error " +
|
||||||
|
$"{nameof(Status.HeadHunterResponseDeserializationFailedError)}");
|
||||||
|
return Status.HeadHunterResponseDeserializationFailedError;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
else
|
||||||
var responseDto = JsonSerializer.Deserialize<HeadHunterTokenResponseDto>(await res.Content.ReadAsStringAsync());
|
|
||||||
|
|
||||||
if (responseDto == null)
|
|
||||||
{
|
{
|
||||||
logger.LogWarning($"User {userId} auth completed with error " +
|
responseDto = new HeadHunterTokenResponseDto("testtoken", 0, "testtoken", "--");
|
||||||
$"{nameof(Status.HeadHunterResponseDeserializationFailedError)}");
|
|
||||||
return Status.HeadHunterResponseDeserializationFailedError;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == userId);
|
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == userId);
|
||||||
|
@ -19,9 +19,9 @@ public class Startup(IConfiguration configuration)
|
|||||||
services.AddControllers();
|
services.AddControllers();
|
||||||
services.AddLogging();
|
services.AddLogging();
|
||||||
|
|
||||||
await using var rabbitMqConnection = await new ConnectionFactory
|
var rabbitMqConnection = await new ConnectionFactory
|
||||||
{
|
{
|
||||||
HostName = "jobot-rabbitmq"
|
HostName = "rabbitmq"
|
||||||
}.CreateConnectionAsync();
|
}.CreateConnectionAsync();
|
||||||
var channel = await rabbitMqConnection.CreateChannelAsync();
|
var channel = await rabbitMqConnection.CreateChannelAsync();
|
||||||
await channel.QueueDeclareAsync(
|
await channel.QueueDeclareAsync(
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
using JOBot.TClient.Infrastructure.Extensions;
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
using Telegram.Bot.Types;
|
using Telegram.Bot.Types;
|
||||||
|
|
||||||
@ -9,6 +10,6 @@ public class InfoCommand(ITelegramBotClient bot) : ITelegramCommand
|
|||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
||||||
|
|
||||||
await bot.SendMessage(update.Message.From.Id, TextResource.Info, cancellationToken: ct);
|
await bot.SendMessageRemK(update.Message.From.Id, TextResource.Info, cancellationToken: ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -77,7 +77,7 @@ public sealed class BotBackgroundService(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await bot.SendMessage(update.Message.From.Id, TextResource.CommandNotFound, cancellationToken: ct);
|
await bot.SendMessageRemK(update.Message.From.Id, TextResource.CommandNotFound, cancellationToken: ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
using JOBot.TClient.Infrastructure.Extensions;
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
using Telegram.Bot.Types;
|
using Telegram.Bot.Types;
|
||||||
|
|
||||||
@ -11,7 +12,7 @@ public class FallbackException : Exception
|
|||||||
{
|
{
|
||||||
public FallbackException(string message, Message botMessage, ITelegramBotClient botClient) : base(message)
|
public FallbackException(string message, Message botMessage, ITelegramBotClient botClient) : base(message)
|
||||||
{
|
{
|
||||||
botClient.SendMessage(botMessage.Chat.Id,
|
botClient.SendMessageRemK(botMessage.Chat.Id,
|
||||||
TextResource.FallbackMessage);
|
TextResource.FallbackMessage);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -0,0 +1,52 @@
|
|||||||
|
using Telegram.Bot;
|
||||||
|
using Telegram.Bot.Types;
|
||||||
|
using Telegram.Bot.Types.Enums;
|
||||||
|
using Telegram.Bot.Types.ReplyMarkups;
|
||||||
|
|
||||||
|
namespace JOBot.TClient.Infrastructure.Extensions;
|
||||||
|
|
||||||
|
public static class TelegramBotClientExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extension method for auto-remove of reply keyboard if is null
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bot"></param>
|
||||||
|
/// <param name="chatId"></param>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
/// <param name="parseMode"></param>
|
||||||
|
/// <param name="replyParameters"></param>
|
||||||
|
/// <param name="replyMarkup"></param>
|
||||||
|
/// <param name="linkPreviewOptions"></param>
|
||||||
|
/// <param name="messageThreadId"></param>
|
||||||
|
/// <param name="entities"></param>
|
||||||
|
/// <param name="disableNotification"></param>
|
||||||
|
/// <param name="protectContent"></param>
|
||||||
|
/// <param name="messageEffectId"></param>
|
||||||
|
/// <param name="businessConnectionId"></param>
|
||||||
|
/// <param name="allowPaidBroadcast"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static Task<Message> SendMessageRemK(
|
||||||
|
this ITelegramBotClient bot,
|
||||||
|
ChatId chatId,
|
||||||
|
string text,
|
||||||
|
ParseMode parseMode = default,
|
||||||
|
ReplyParameters? replyParameters = null,
|
||||||
|
ReplyMarkup? replyMarkup = null,
|
||||||
|
LinkPreviewOptions? linkPreviewOptions = null,
|
||||||
|
int? messageThreadId = null,
|
||||||
|
IEnumerable<MessageEntity>? entities = null,
|
||||||
|
bool disableNotification = false,
|
||||||
|
bool protectContent = false,
|
||||||
|
string? messageEffectId = null,
|
||||||
|
string? businessConnectionId = null,
|
||||||
|
bool allowPaidBroadcast = false,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
replyMarkup ??= new ReplyKeyboardRemove();
|
||||||
|
|
||||||
|
return bot.SendMessage(chatId, text, parseMode, replyParameters, replyMarkup, linkPreviewOptions, messageThreadId,
|
||||||
|
entities, disableNotification, protectContent, messageEffectId, businessConnectionId, allowPaidBroadcast,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
@ -1,26 +1,24 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using JOBot.Infrastructure.Config;
|
using JOBot.Infrastructure.Config;
|
||||||
using JOBot.TClient.Services;
|
using JOBot.TClient.Services;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
using RabbitMQ.Client;
|
using RabbitMQ.Client;
|
||||||
using RabbitMQ.Client.Events;
|
using RabbitMQ.Client.Events;
|
||||||
|
|
||||||
namespace JOBot.TClient.Queues;
|
namespace JOBot.TClient.Queues;
|
||||||
|
|
||||||
public class AuthQueue
|
public class AuthQueue(IChannel channel, PrepareUserService prepareUserService) : BackgroundService
|
||||||
{
|
{
|
||||||
private readonly PrepareUserService _prepareUserService;
|
|
||||||
public AuthQueue(
|
|
||||||
IChannel channel, PrepareUserService prepareUserService)
|
|
||||||
{
|
|
||||||
_prepareUserService = prepareUserService;
|
|
||||||
|
|
||||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
|
||||||
consumer.ReceivedAsync += OnDataReceivedAsync;
|
|
||||||
channel.BasicConsumeAsync(RabbitQueues.AuthQueue, autoAck: true, consumer: consumer);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task OnDataReceivedAsync(object sender, BasicDeliverEventArgs eventArgs)
|
private async Task OnDataReceivedAsync(object sender, BasicDeliverEventArgs eventArgs)
|
||||||
{
|
{
|
||||||
await _prepareUserService.SelectCv(Convert.ToInt64(Encoding.UTF8.GetString(eventArgs.Body.ToArray())));
|
await prepareUserService.AuthHookReceived(Convert.ToInt64(Encoding.UTF8.GetString(eventArgs.Body.ToArray())));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
var consumer = new AsyncEventingBasicConsumer(channel);
|
||||||
|
consumer.ReceivedAsync += OnDataReceivedAsync;
|
||||||
|
await channel.BasicConsumeAsync(RabbitQueues.AuthQueue, autoAck: true, consumer: consumer, cancellationToken: stoppingToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
using JOBot.TClient.Infrastructure.Extensions;
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
using Telegram.Bot.Types;
|
using Telegram.Bot.Types;
|
||||||
|
|
||||||
@ -9,6 +10,6 @@ public class MenuService(ITelegramBotClient bot)
|
|||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
||||||
|
|
||||||
await bot.SendMessage(update.Message.From.Id, "PrepareUser stage is done.", cancellationToken: ct);
|
await bot.SendMessageRemK(update.Message.From.Id, "PrepareUser stage is done.", cancellationToken: ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,6 @@
|
|||||||
using JOBot.Proto;
|
using JOBot.Proto;
|
||||||
using JOBot.TClient.Infrastructure.Exceptions;
|
using JOBot.TClient.Infrastructure.Exceptions;
|
||||||
|
using JOBot.TClient.Infrastructure.Extensions;
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
using Telegram.Bot.Types;
|
using Telegram.Bot.Types;
|
||||||
using User = JOBot.Proto.User;
|
using User = JOBot.Proto.User;
|
||||||
@ -31,7 +32,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
|||||||
|
|
||||||
if (!result.Success)
|
if (!result.Success)
|
||||||
{
|
{
|
||||||
await _bot.SendMessage(update.Message.Chat.Id,
|
await _bot.SendMessageRemK(update.Message.Chat.Id,
|
||||||
TextResource.FallbackMessage,
|
TextResource.FallbackMessage,
|
||||||
cancellationToken: ct);
|
cancellationToken: ct);
|
||||||
|
|
||||||
@ -59,7 +60,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
|||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
ArgumentNullException.ThrowIfNull(update.Message?.From);
|
||||||
|
|
||||||
await _bot.SendMessage(
|
await _bot.SendMessageRemK(
|
||||||
update.Message.From.Id,
|
update.Message.From.Id,
|
||||||
TextResource.EULA,
|
TextResource.EULA,
|
||||||
replyMarkup: new[] { ButtonResource.EULAAgrement }, cancellationToken: ct);
|
replyMarkup: new[] { ButtonResource.EULAAgrement }, cancellationToken: ct);
|
||||||
@ -93,7 +94,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
|||||||
UserId = update.Message.From.Id
|
UserId = update.Message.From.Id
|
||||||
});
|
});
|
||||||
|
|
||||||
await _bot.SendMessage(
|
await _bot.SendMessageRemK(
|
||||||
update.Message.From.Id,
|
update.Message.From.Id,
|
||||||
string.Format(TextResource.AskForAuth, [url.RegistrationUrl]),
|
string.Format(TextResource.AskForAuth, [url.RegistrationUrl]),
|
||||||
cancellationToken: ct);
|
cancellationToken: ct);
|
||||||
@ -101,7 +102,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
|||||||
|
|
||||||
public async Task AuthHookReceived(long userId, CancellationToken ct = default)
|
public async Task AuthHookReceived(long userId, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
await _bot.SendMessage(userId, "Авторизация завершена успешно!", cancellationToken: ct);
|
await _bot.SendMessageRemK(userId, "✅ Авторизация завершена успешно!", cancellationToken: ct);
|
||||||
await SelectCv(userId, ct);
|
await SelectCv(userId, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,7 +115,7 @@ public class PrepareUserService(ITelegramBotClient bot, User.UserClient userClie
|
|||||||
|
|
||||||
public async Task SelectCv(long userId, CancellationToken ct = default)
|
public async Task SelectCv(long userId, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
await _bot.SendMessage(userId, "Давайте выберем одно из доступных резюме:",
|
await _bot.SendMessageRemK(userId, "Давайте выберем одно из доступных резюме:",
|
||||||
cancellationToken: ct); //TODO: https://git.lisoveliy.su/Lisoveliy/JOBot/issues/9
|
cancellationToken: ct); //TODO: https://git.lisoveliy.su/Lisoveliy/JOBot/issues/9
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -23,17 +23,17 @@ public static class Startup
|
|||||||
{
|
{
|
||||||
services.AddSingleton(config);
|
services.AddSingleton(config);
|
||||||
|
|
||||||
services.AddScoped<ChannelBase, GrpcChannel>(_ => GrpcChannel.ForAddress(config.GetValue<string>("BackendHost")
|
services.AddSingleton(_ => GrpcChannel.ForAddress(config.GetValue<string>("BackendHost")
|
||||||
?? throw new MissingFieldException("Host is not defined")));
|
?? throw new MissingFieldException("Host is not defined")));
|
||||||
|
|
||||||
#region Commands
|
#region Commands
|
||||||
|
|
||||||
services.AddScoped<StartCommand>();
|
services.AddSingleton<StartCommand>();
|
||||||
services.AddScoped<MenuCommand>();
|
services.AddSingleton<MenuCommand>();
|
||||||
services.AddScoped<InfoCommand>();
|
services.AddSingleton<InfoCommand>();
|
||||||
|
|
||||||
//buttons
|
//buttons
|
||||||
services.AddScoped<EulaAgreementButtonCommand>();
|
services.AddSingleton<EulaAgreementButtonCommand>();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@ -46,21 +46,21 @@ public static class Startup
|
|||||||
#region Services
|
#region Services
|
||||||
|
|
||||||
services.AddSingleton<UserService>();
|
services.AddSingleton<UserService>();
|
||||||
services.AddScoped<PrepareUserService>();
|
services.AddSingleton<PrepareUserService>();
|
||||||
services.AddScoped<MenuService>();
|
services.AddSingleton<MenuService>();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region States
|
#region States
|
||||||
|
|
||||||
services.AddScoped<PrepareUserState>();
|
services.AddSingleton<PrepareUserState>();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region RabbitMQ Clients
|
#region RabbitMQ Clients
|
||||||
|
|
||||||
var factory = new ConnectionFactory { HostName = "localhost" };
|
var factory = new ConnectionFactory { HostName = "rabbitmq" };
|
||||||
using var connection = factory.CreateConnectionAsync().Result;
|
var connection = factory.CreateConnectionAsync().Result;
|
||||||
var channel = connection.CreateChannelAsync().Result;
|
var channel = connection.CreateChannelAsync().Result;
|
||||||
|
|
||||||
channel.QueueDeclareAsync(
|
channel.QueueDeclareAsync(
|
||||||
@ -70,7 +70,8 @@ public static class Startup
|
|||||||
false,
|
false,
|
||||||
arguments: null).Wait();
|
arguments: null).Wait();
|
||||||
|
|
||||||
services.AddSingleton<AuthQueue>();
|
services.AddSingleton(channel);
|
||||||
|
services.AddHostedService<AuthQueue>();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
@ -9,6 +9,8 @@ services:
|
|||||||
- "15672:15672"
|
- "15672:15672"
|
||||||
volumes:
|
volumes:
|
||||||
- rabbitmq_data:/var/lib/rabbitmq/
|
- rabbitmq_data:/var/lib/rabbitmq/
|
||||||
|
networks:
|
||||||
|
- jobot
|
||||||
|
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:15
|
image: postgres:15
|
||||||
@ -28,6 +30,7 @@ services:
|
|||||||
dockerfile: JOBot.Backend/Dockerfile
|
dockerfile: JOBot.Backend/Dockerfile
|
||||||
depends_on:
|
depends_on:
|
||||||
- postgres
|
- postgres
|
||||||
|
- rabbitmq
|
||||||
ports:
|
ports:
|
||||||
- "5000:5000"
|
- "5000:5000"
|
||||||
- "5001:5001"
|
- "5001:5001"
|
||||||
|
@ -6,6 +6,8 @@ services:
|
|||||||
image: rabbitmq:4
|
image: rabbitmq:4
|
||||||
volumes:
|
volumes:
|
||||||
- rabbitmq_data:/var/lib/rabbitmq/
|
- rabbitmq_data:/var/lib/rabbitmq/
|
||||||
|
networks:
|
||||||
|
- jobot
|
||||||
|
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:15
|
image: postgres:15
|
||||||
@ -23,7 +25,7 @@ services:
|
|||||||
dockerfile: JOBot.Backend/Dockerfile
|
dockerfile: JOBot.Backend/Dockerfile
|
||||||
depends_on:
|
depends_on:
|
||||||
- postgres
|
- postgres
|
||||||
- image
|
- rabbitmq
|
||||||
ports:
|
ports:
|
||||||
- "5000:5000"
|
- "5000:5000"
|
||||||
networks:
|
networks:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user