chore: cleanup

This commit is contained in:
2025-07-25 16:37:42 +03:00
parent 7ceb8f656e
commit b15a77557e
28 changed files with 224 additions and 198 deletions

View File

@@ -8,16 +8,17 @@ namespace JOBot.Backend.Controllers;
public class HeadHunterHookController(HeadHunterService hhService)
: ControllerBase
{
[HttpGet]
public async Task<IActionResult> Get(int userId, string? error, string code)
{
var res = await hhService.AuthUser(userId, code, error);
return res switch
{
HeadHunterService.Status.Success => Ok("Авторизация завершена успешно. Вернитесь в Telegram для продолжения."),
HeadHunterService.Status.Success => Ok(
"Авторизация завершена успешно. Вернитесь в Telegram для продолжения."),
HeadHunterService.Status.UserNotFoundError => NotFound("Пользователь не найден."),
_ => BadRequest("Авторизация завершена с ошибкой. Вернитесь в Telegram для продолжения.") //TODO: Add resource
_ => BadRequest(
"Авторизация завершена с ошибкой. Вернитесь в Telegram для продолжения.") //TODO: Add resource
};
}
}

View File

@@ -1,14 +1,14 @@
namespace JOBot.Backend.DAL.Context;
using Models;
using JOBot.Backend.DAL.Models;
using Microsoft.EntityFrameworkCore;
namespace JOBot.Backend.DAL.Context;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()

View File

@@ -9,12 +9,12 @@ public class User
{
public Guid Id { get; set; }
[Key]
public required long UserId { get; set; }
[MaxLength(255)]
public string? Username { get; set; }
[Key] public required long UserId { get; set; }
[MaxLength(255)] public string? Username { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
[MaxLength(255)] public string? AccessToken { get; set; } = null;
[MaxLength(255)] public string? RefreshToken { get; set; } = null;

View File

@@ -3,12 +3,12 @@ using System.Text.Json.Serialization;
namespace JOBot.Backend.DTOs.HeadHunterHook;
public record HeadHunterTokenResponseDto(
[property:JsonPropertyName("access_token")]
[property: JsonPropertyName("access_token")]
string AccessToken,
[property:JsonPropertyName("expires_in")]
[property: JsonPropertyName("expires_in")]
int ExpiresIn,
[property:JsonPropertyName("refresh_token")]
[property: JsonPropertyName("refresh_token")]
string RefreshToken,
[property:JsonPropertyName("token_type")]
[property: JsonPropertyName("token_type")]
string TokenType
);
);

View File

@@ -1,34 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.30.2" />
<PackageReference Include="Grpc.AspNetCore" Version="2.71.0" />
<PackageReference Include="Grpc.AspNetCore.Server.Reflection" Version="2.71.0" />
<PackageReference Include="Grpc.Tools" Version="2.71.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="RabbitMQ.Client" Version="7.1.2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.30.2"/>
<PackageReference Include="Grpc.AspNetCore" Version="2.71.0"/>
<PackageReference Include="Grpc.AspNetCore.Server.Reflection" Version="2.71.0"/>
<PackageReference Include="Grpc.Tools" Version="2.71.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4"/>
<PackageReference Include="RabbitMQ.Client" Version="7.1.2"/>
</ItemGroup>
<ItemGroup>
<Protobuf Include="..\Proto\*" GrpcServices="Server"></Protobuf>
</ItemGroup>
<ItemGroup>
<Protobuf Include="..\Proto\*" GrpcServices="Server"></Protobuf>
</ItemGroup>
<ItemGroup>
<Folder Include="Data\Migrations\" />
</ItemGroup>
<ItemGroup>
<Folder Include="Data\Migrations\"/>
</ItemGroup>
</Project>

View File

@@ -10,28 +10,36 @@ using RabbitMQ.Client;
namespace JOBot.Backend.Services;
public class HeadHunterService(
IChannel channel,
ILogger<HeadHunterService> logger,
IOptions<HeadHunterConfig> config,
IChannel channel,
ILogger<HeadHunterService> logger,
IOptions<HeadHunterConfig> config,
AppDbContext dbContext)
{
public enum Status
{
UserAuthRejectedError,
HeadHunterAuthRejectedError,
UserNotFoundError,
HeadHunterResponseDeserializationFailedError,
Success
}
private readonly HeadHunterConfig _config = config.Value;
/// <summary>
/// Generate HeadHunter oauth authorization link
/// Generate HeadHunter oauth authorization link
/// </summary>
/// <param name="userId">Telegram UserId</param>
/// <returns>Link for auth</returns>
public string GenerateAuthLink(long userId)
{
return string.Format(_config.Links.AuthLink, [_config.ClientId, GetRedirectUrl(userId)]);
}
public async Task<Status> AuthUser(int userId, string authorizationCode, string? error)
public async Task<Status> AuthUser(int userId, string authorizationCode, string? error) //TODO: Разбить этот метод
{
logger.LogInformation($"Authorization for user {userId} in process...");
if (!string.IsNullOrEmpty(error))
{
logger.LogWarning($"User {userId} auth completed with error {error}");
@@ -69,7 +77,7 @@ public class HeadHunterService(
logger.LogWarning($"{res.Content.ReadAsStringAsync().Result}");
return Status.HeadHunterAuthRejectedError;
}
var responseDto = JsonSerializer.Deserialize<HeadHunterTokenResponseDto>(await res.Content.ReadAsStringAsync());
if (responseDto == null)
@@ -78,7 +86,7 @@ public class HeadHunterService(
$"{nameof(Status.HeadHunterResponseDeserializationFailedError)}");
return Status.HeadHunterResponseDeserializationFailedError;
}
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == userId);
if (user == null)
@@ -86,20 +94,20 @@ public class HeadHunterService(
logger.LogWarning($"User {userId} search completed with error {nameof(Status.UserNotFoundError)}");
return Status.UserNotFoundError;
}
user.AccessToken = responseDto.AccessToken;
user.RefreshToken = responseDto.RefreshToken;
await dbContext.SaveChangesAsync();
logger.LogInformation($"User {userId} auth completed!");
await channel.BasicPublishAsync(
string.Empty,
RabbitQueues.AuthQueue,
string.Empty,
RabbitQueues.AuthQueue,
Encoding.UTF8.GetBytes(userId.ToString()));
logger.LogInformation($"RabbitMQ event was created");
logger.LogInformation("RabbitMQ event was created");
return Status.Success;
}
@@ -114,13 +122,4 @@ public class HeadHunterService(
Query = $"?userId={userId}"
}.ToString();
}
public enum Status
{
UserAuthRejectedError,
HeadHunterAuthRejectedError,
UserNotFoundError,
HeadHunterResponseDeserializationFailedError,
Success
}
}

View File

@@ -1,4 +1,3 @@
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using JOBot.Backend.DAL.Context;
using JOBot.Backend.DAL.Models;
@@ -11,7 +10,7 @@ namespace JOBot.Backend.Services.gRPC;
public class UserService(AppDbContext dbContext, HeadHunterService hhService) : Proto.User.UserBase
{
/// <summary>
/// Create user
/// Create user
/// </summary>
/// <param name="request"></param>
/// <param name="_"></param>
@@ -32,7 +31,7 @@ public class UserService(AppDbContext dbContext, HeadHunterService hhService) :
}
/// <summary>
/// Get user for client
/// Get user for client
/// </summary>
/// <param name="request"></param>
/// <param name="_"></param>
@@ -46,7 +45,7 @@ public class UserService(AppDbContext dbContext, HeadHunterService hhService) :
}
/// <summary>
/// Accept EULA for user
/// Accept EULA for user
/// </summary>
/// <param name="request"></param>
/// <param name="_"></param>
@@ -64,7 +63,7 @@ public class UserService(AppDbContext dbContext, HeadHunterService hhService) :
}
public override Task<GetHeadHunterAuthHookResponse> GetHeadHunterAuthHook(
GetHeadHunterAuthHookRequest request,
GetHeadHunterAuthHookRequest request,
ServerCallContext context)
{
return Task.Run(() => new GetHeadHunterAuthHookResponse
@@ -74,7 +73,7 @@ public class UserService(AppDbContext dbContext, HeadHunterService hhService) :
}
/// <summary>
/// Throw RPCException if user not found
/// Throw RPCException if user not found
/// </summary>
/// <param name="user"></param>
/// <exception cref="RpcException"></exception>

View File

@@ -13,7 +13,7 @@ public class Startup(IConfiguration configuration)
public async Task ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddGrpc();
services.AddGrpcReflection();
services.AddControllers();
services.AddLogging();
@@ -23,9 +23,9 @@ public class Startup(IConfiguration configuration)
HostName = "jobot-rabbitmq"
}.CreateConnectionAsync();
await using var channel = await rabbitMqConnection.CreateChannelAsync();
await channel.QueueDeclareAsync(RabbitQueues.AuthQueue, false, false, autoDelete: false);
await channel.QueueDeclareAsync(RabbitQueues.AuthQueue, false, false, false);
services.AddSingleton(channel);
services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("PostgreSQL")));

View File

@@ -1,35 +1,35 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"PostgreSQL": "Host=postgres;Port=5432;Database=jobot;Username=postgres;Password=LocalDbPass"
},
"HeadHunter": {
"Links": {
"AuthLink": "https://hh.ru/oauth/authorize?response_type=code&client_id={0}&redirect_uri={1}",
"HookDomain": "jobot.lisoveliy.su",
"HookRoute": "/auth",
"HeadHunterApiDomain": "api.hh.ru",
"HeadHunterTokenRoute": "/token"
},
"ClientId": "",
"Secret": ""
},
"Kestrel": {
"Endpoints": {
"gRPC": {
"Url": "http://*:5001",
"Protocols": "Http2"
},
"REST": {
"Url": "http://*:5000",
"Protocols": "Http1"
}
}
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"PostgreSQL": "Host=postgres;Port=5432;Database=jobot;Username=postgres;Password=LocalDbPass"
},
"HeadHunter": {
"Links": {
"AuthLink": "https://hh.ru/oauth/authorize?response_type=code&client_id={0}&redirect_uri={1}",
"HookDomain": "jobot.lisoveliy.su",
"HookRoute": "/auth",
"HeadHunterApiDomain": "api.hh.ru",
"HeadHunterTokenRoute": "/token"
},
"ClientId": "",
"Secret": ""
},
"Kestrel": {
"Endpoints": {
"gRPC": {
"Url": "http://*:5001",
"Protocols": "Http2"
},
"REST": {
"Url": "http://*:5000",
"Protocols": "Http1"
}
}
}
}