using Grpc.Core; using JOBot.Backend.DAL.Context; using JOBot.Backend.DAL.Models; using JOBot.Proto; using Microsoft.EntityFrameworkCore; using User = JOBot.Backend.DAL.Models.User; namespace JOBot.Backend.Services.gRPC; public class UserService(AppDbContext dbContext, HeadHunterService hhService) : Proto.User.UserBase { /// /// Create user /// /// /// /// Status of operation (fail if user exists) public override async Task Register(RegisterRequest request, ServerCallContext _) { if (await dbContext.Users.AnyAsync(x => x.UserId == request.UserId)) return new RegisterResponse { Success = false }; dbContext.Users.Add(new User { UserId = request.UserId, Username = !string.IsNullOrEmpty(request.Username) ? request.Username : null }); await dbContext.SaveChangesAsync(); return new RegisterResponse { Success = true }; } /// /// Get user for client /// /// /// /// User, or throws RPC exception if not found public override async Task GetUser(GetUserRequest request, ServerCallContext _) { var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == request.UserId); ThrowIfUserNotFound(user); return user!.MapToResponse(); } /// /// Accept EULA for user /// /// /// /// Status of operation public override async Task AcceptEula(AcceptEulaRequest request, ServerCallContext _) { var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == request.UserId); if (user == null) return new AcceptEulaResponse { Success = false }; user.Eula = request.EulaAccepted; await dbContext.SaveChangesAsync(); return new AcceptEulaResponse { Success = true }; } public override Task GetHeadHunterAuthHook( GetHeadHunterAuthHookRequest request, ServerCallContext context) { return Task.Run(() => new GetHeadHunterAuthHookResponse { RegistrationUrl = hhService.GenerateAuthLink(request.UserId) }); } /// /// Throw RPCException if user not found /// /// /// private static void ThrowIfUserNotFound(User? user) { if (user == null) throw new RpcException(new Status(StatusCode.NotFound, "User not found")); } }