Implement base controller for shared functionality; update existing controllers to inherit from BaseController and adjust user ID handling. Add JWT authentication support and modify item retrieval methods in GameDataController.

This commit is contained in:
Jose Henrique 2025-02-15 21:57:59 -03:00
parent 6d81ff1564
commit b84599b370
10 changed files with 72 additions and 31 deletions

4
.gitignore vendored
View File

@ -6,4 +6,6 @@ appsettings.Development.json
*.db *.db
*.db-shm *.db-shm
*.db-wal *.db-wal
*.csproj.user *.csproj.user
game-data

View File

@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace PetCompanion.Controllers
{
[Authorize]
[ApiController]
[Route("api/v1/[controller]")]
public class BaseController : Controller
{
protected string userId => User.Claims.FirstOrDefault(c => c.Type == "user_id").Value;
}
}

View File

@ -3,13 +3,10 @@ using PetCompanion.Repositories;
namespace PetCompanion.Controllers namespace PetCompanion.Controllers
{ {
[ApiController] public class GameDataController : BaseController
[Route("api/v1/[controller]")]
public class GameDataController : Controller
{ {
private readonly GameItemsRepository gameItemsRepository; private readonly GameItemsRepository gameItemsRepository;
private readonly ILogger<InventoryController> logger; private readonly ILogger<InventoryController> logger;
private readonly Guid userId = Guid.Parse("f5f4b3b3-3b7b-4b7b-8b7b-7b7b7b7b7b7b");
public GameDataController( public GameDataController(
ILogger<InventoryController> logger, ILogger<InventoryController> logger,
@ -19,7 +16,20 @@ namespace PetCompanion.Controllers
this.gameItemsRepository = gameItemsRepository; this.gameItemsRepository = gameItemsRepository;
} }
[HttpGet("item/icon/{itemId}")] [HttpGet("item/{itemId}")]
public IActionResult GetItemInfo(int itemId)
{
try
{
return Ok(gameItemsRepository.GetById(itemId));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet("item/{itemId}/icon")]
public IActionResult GetItemIcon(int itemId) public IActionResult GetItemIcon(int itemId)
{ {
try try

View File

@ -1,16 +1,14 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using PetCompanion.Models;
using PetCompanion.Services; using PetCompanion.Services;
namespace PetCompanion.Controllers namespace PetCompanion.Controllers
{ {
[ApiController] [ApiController]
[Route("api/v1/[controller]")] [Route("api/v1/[controller]")]
public class InventoryController : ControllerBase public class InventoryController : BaseController
{ {
private readonly PetInventoryService inventoryService; private readonly PetInventoryService inventoryService;
private readonly ILogger<InventoryController> logger; private readonly ILogger<InventoryController> logger;
private readonly Guid userId = Guid.Parse("f5f4b3b3-3b7b-4b7b-8b7b-7b7b7b7b7b7b");
public InventoryController( public InventoryController(
ILogger<InventoryController> logger, ILogger<InventoryController> logger,

View File

@ -4,14 +4,11 @@ using PetCompanion.Services;
namespace PetCompanion.Controllers namespace PetCompanion.Controllers
{ {
[ApiController] public class PetController : BaseController
[Route("api/v1/[controller]")]
public class PetController : ControllerBase
{ {
private readonly PetService petService; private readonly PetService petService;
private readonly PetClassService petClassService; private readonly PetClassService petClassService;
private readonly ILogger<PetController> logger; private readonly ILogger<PetController> logger;
private Guid userId = Guid.Parse("f5f4b3b3-3b7b-4b7b-8b7b-7b7b7b7b7b7b");
public PetController( public PetController(
ILogger<PetController> logger, ILogger<PetController> logger,

View File

@ -3,14 +3,11 @@ using PetCompanion.Services;
namespace PetCompanion.Controllers namespace PetCompanion.Controllers
{ {
[ApiController] public class SkillController : BaseController
[Route("api/v1/[controller]")]
public class SkillController : ControllerBase
{ {
private readonly SkillService _skillService; private readonly SkillService _skillService;
private readonly PetSkillService _petSkillService; private readonly PetSkillService _petSkillService;
private readonly ILogger<SkillController> _logger; private readonly ILogger<SkillController> _logger;
private Guid userId = Guid.Parse("f5f4b3b3-3b7b-4b7b-8b7b-7b7b7b7b7b7b");
public SkillController( public SkillController(
ILogger<SkillController> logger, ILogger<SkillController> logger,
@ -34,7 +31,7 @@ namespace PetCompanion.Controllers
{ {
try try
{ {
var skills = _petSkillService.GetPetSkills(petId, userId.ToString()); var skills = _petSkillService.GetPetSkills(petId, userId);
return Ok(skills); return Ok(skills);
} }
catch (Exception ex) catch (Exception ex)
@ -48,7 +45,7 @@ namespace PetCompanion.Controllers
{ {
try try
{ {
var result = _petSkillService.UpgradeSkill(petId, userId.ToString(), skillId); var result = _petSkillService.UpgradeSkill(petId, userId, skillId);
return Ok(result); return Ok(result);
} }
catch (Exception ex) catch (Exception ex)

View File

@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using PetCompanion.Data; using PetCompanion.Data;
using PetCompanion.Repositories; using PetCompanion.Repositories;
using PetCompanion.Services; using PetCompanion.Services;
@ -12,6 +14,10 @@ namespace PetCompanion
{ {
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Read Firebase configuration from environment variables
var firebaseAppId = Environment.GetEnvironmentVariable("FIREBASE_APP_ID") ??
throw new InvalidOperationException("FIREBASE_APP_ID environment variable is not set");
// Add services to the container. // Add services to the container.
builder.Services.AddControllers() builder.Services.AddControllers()
.AddJsonOptions(options => .AddJsonOptions(options =>
@ -57,6 +63,21 @@ namespace PetCompanion
}); });
}); });
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = $"https://securetoken.google.com/{firebaseAppId}";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = $"https://securetoken.google.com/{firebaseAppId}",
ValidateAudience = true,
ValidAudience = firebaseAppId,
ValidateLifetime = true
};
});
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
@ -67,6 +88,8 @@ namespace PetCompanion
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
// After app builder is created // After app builder is created

View File

@ -64,11 +64,11 @@ namespace PetCompanion.Services
var gathered = new List<ActionGathered>(); var gathered = new List<ActionGathered>();
var baseRate = timeElapsed + pet.Level * 10; // Base rate per hour var baseRate = (timeElapsed + pet.Level) / 10; // Base rate per hour
gathered.Add(new ActionGathered gathered.Add(new ActionGathered
{ {
Resource = "Junk", Resource = "Junk",
Amount = (int)(baseRate * 2) Amount = (int)(baseRate * 0.2)
}); });
var random = new Random(); var random = new Random();
@ -79,28 +79,28 @@ namespace PetCompanion.Services
gathered.Add(new ActionGathered gathered.Add(new ActionGathered
{ {
Resource = "Wisdom", Resource = "Wisdom",
Amount = (int)(baseRate * (pet.Stats.Intelligence * 2)) Amount = (int)(baseRate * (pet.Stats.Intelligence * 0.5))
}); });
break; break;
case PetActionGather.GATHERING_GOLD: case PetActionGather.GATHERING_GOLD:
gathered.Add(new ActionGathered gathered.Add(new ActionGathered
{ {
Resource = "Gold", Resource = "Gold",
Amount = (int)(baseRate * (pet.Stats.Charisma * 2)) Amount = (int)(baseRate * (pet.Stats.Charisma * 0.5))
}); });
break; break;
case PetActionGather.GATHERING_FOOD: case PetActionGather.GATHERING_FOOD:
gathered.Add(new ActionGathered gathered.Add(new ActionGathered
{ {
Resource = "Food", Resource = "Food",
Amount = (int)(baseRate * (pet.Stats.Strength * 1.5)) Amount = (int)(baseRate * (pet.Stats.Strength * 0.5))
}); });
break; break;
case PetActionGather.EXPLORE: case PetActionGather.EXPLORE:
gathered.Add(new ActionGathered gathered.Add(new ActionGathered
{ {
Resource = "Wisdom", Resource = "Wisdom",
Amount = (int)(baseRate * (pet.Stats.Strength * 3)) Amount = (int)(baseRate * (pet.Stats.Strength * 0.25))
}); });
if (random.Next(0, 100) < 5) if (random.Next(0, 100) < 5)
@ -122,7 +122,7 @@ namespace PetCompanion.Services
gathered.Add(new ActionGathered gathered.Add(new ActionGathered
{ {
Resource = "Gold", Resource = "Gold",
Amount = (int)(baseRate * (pet.Stats.Strength * 3)) Amount = (int)(baseRate * (pet.Stats.Strength * 0.25))
}); });
if (random.Next(0, 100) < 10) if (random.Next(0, 100) < 10)
@ -130,7 +130,7 @@ namespace PetCompanion.Services
pet.Health -= random.Next(5, 10); pet.Health -= random.Next(5, 10);
} }
if (random.Next(0, 100) < 500) if (random.Next(0, 100) < 10)
{ {
gathered.Add(new ActionGathered gathered.Add(new ActionGathered
{ {

View File

@ -29,18 +29,18 @@ namespace PetCompanion.Services
this.petActionService = petActionService; this.petActionService = petActionService;
} }
public IEnumerable<Pet> GetAllPets(Guid userId) public IEnumerable<Pet> GetAllPets(string userId)
{ {
return petRepository.GetPetsByUserId(userId.ToString()); return petRepository.GetPetsByUserId(userId);
} }
public Pet CreatePet(Guid userId, PetCreationRequest petRequest) public Pet CreatePet(string userId, PetCreationRequest petRequest)
{ {
var petId = Guid.NewGuid().ToString(); var petId = Guid.NewGuid().ToString();
var pet = new Pet var pet = new Pet
{ {
Id = petId, Id = petId,
UserId = userId.ToString(), UserId = userId,
Name = petRequest.Name, Name = petRequest.Name,
Class = petRequest.Class, Class = petRequest.Class,
Health = 100, Health = 100,

View File

@ -12,6 +12,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CsvHelper" Version="33.0.1" /> <PackageReference Include="CsvHelper" Version="33.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.13" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.1" /> <PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.1"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>