Kavita+ Reset License & Discord Integration (#2516)

This commit is contained in:
Joe Milazzo 2024-01-04 14:53:15 -06:00 committed by GitHub
parent 138794ffed
commit c37596889a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 230 additions and 86 deletions

View file

@ -8,7 +8,6 @@ using API.Entities.Enums;
using API.Extensions;
using API.Services;
using API.Services.Plus;
using Kavita.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
@ -17,22 +16,13 @@ namespace API.Controllers;
#nullable enable
public class LicenseController : BaseApiController
public class LicenseController(
IUnitOfWork unitOfWork,
ILogger<LicenseController> logger,
ILicenseService licenseService,
ILocalizationService localizationService)
: BaseApiController
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<LicenseController> _logger;
private readonly ILicenseService _licenseService;
private readonly ILocalizationService _localizationService;
public LicenseController(IUnitOfWork unitOfWork, ILogger<LicenseController> logger,
ILicenseService licenseService, ILocalizationService localizationService)
{
_unitOfWork = unitOfWork;
_logger = logger;
_licenseService = licenseService;
_localizationService = localizationService;
}
/// <summary>
/// Checks if the user's license is valid or not
/// </summary>
@ -41,7 +31,7 @@ public class LicenseController : BaseApiController
[ResponseCache(CacheProfileName = ResponseCacheProfiles.LicenseCache)]
public async Task<ActionResult<bool>> HasValidLicense(bool forceCheck = false)
{
return Ok(await _licenseService.HasActiveLicense(forceCheck));
return Ok(await licenseService.HasActiveLicense(forceCheck));
}
/// <summary>
@ -54,7 +44,7 @@ public class LicenseController : BaseApiController
public async Task<ActionResult<bool>> HasLicense()
{
return Ok(!string.IsNullOrEmpty(
(await _unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey)).Value));
(await unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey)).Value));
}
[Authorize("RequireAdminRole")]
@ -62,14 +52,24 @@ public class LicenseController : BaseApiController
[ResponseCache(CacheProfileName = ResponseCacheProfiles.LicenseCache)]
public async Task<ActionResult> RemoveLicense()
{
_logger.LogInformation("Removing license on file for Server");
var setting = await _unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey);
logger.LogInformation("Removing license on file for Server");
var setting = await unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey);
setting.Value = null;
_unitOfWork.SettingsRepository.Update(setting);
await _unitOfWork.CommitAsync();
unitOfWork.SettingsRepository.Update(setting);
await unitOfWork.CommitAsync();
return Ok();
}
[Authorize("RequireAdminRole")]
[HttpPost("reset")]
public async Task<ActionResult> ResetLicense(UpdateLicenseDto dto)
{
logger.LogInformation("Resetting license on file for Server");
if (await licenseService.ResetLicense(dto.License, dto.Email)) return Ok();
return BadRequest(localizationService.Translate(User.GetUserId(), "unable-to-reset-k+"));
}
/// <summary>
/// Updates server license
/// </summary>
@ -81,11 +81,11 @@ public class LicenseController : BaseApiController
{
try
{
await _licenseService.AddLicense(dto.License.Trim(), dto.Email.Trim());
await licenseService.AddLicense(dto.License.Trim(), dto.Email.Trim(), dto.DiscordId);
}
catch (Exception ex)
{
return BadRequest(await _localizationService.Translate(User.GetUserId(), ex.Message));
return BadRequest(await localizationService.Translate(User.GetUserId(), ex.Message));
}
return Ok();
}

View file

@ -5,4 +5,5 @@ public class EncryptLicenseDto
public required string License { get; set; }
public required string InstallId { get; set; }
public required string EmailId { get; set; }
public string? DiscordId { get; set; }
}

View file

@ -0,0 +1,8 @@
namespace API.DTOs.License;
public class ResetLicenseDto
{
public required string License { get; set; }
public required string InstallId { get; set; }
public required string EmailId { get; set; }
}

View file

@ -10,4 +10,8 @@ public class UpdateLicenseDto
/// Email registered with Stripe
/// </summary>
public required string Email { get; set; }
/// <summary>
/// Optional DiscordId
/// </summary>
public string? DiscordId { get; set; }
}

View file

@ -175,6 +175,7 @@
"not-authenticated": "User is not authenticated",
"unable-to-register-k+": "Unable to register license due to error. Reach out to Kavita+ Support",
"unable-to-reset-k+": "Unable to reset Kavita+ license due to error. Reach out to Kavita+ Support",
"anilist-cred-expired": "AniList Credentials have expired or not set",
"scrobble-bad-payload": "Bad payload from Scrobble Provider",
"theme-doesnt-exist": "Theme file missing or invalid",

View file

@ -26,8 +26,9 @@ public interface ILicenseService
{
Task ValidateLicenseStatus();
Task RemoveLicense();
Task AddLicense(string license, string email);
Task AddLicense(string license, string email, string? discordId);
Task<bool> HasActiveLicense(bool forceCheck = false);
Task<bool> ResetLicense(string license, string email);
}
public class LicenseService : ILicenseService
@ -87,7 +88,7 @@ public class LicenseService : ILicenseService
/// <param name="license"></param>
/// <param name="email"></param>
/// <returns></returns>
private async Task<string> RegisterLicense(string license, string email)
private async Task<string> RegisterLicense(string license, string email, string? discordId)
{
if (string.IsNullOrWhiteSpace(license) || string.IsNullOrWhiteSpace(email)) return string.Empty;
try
@ -104,7 +105,8 @@ public class LicenseService : ILicenseService
{
License = license.Trim(),
InstallId = HashUtil.ServerToken(),
EmailId = email.Trim()
EmailId = email.Trim(),
DiscordId = discordId?.Trim()
})
.ReceiveJson<RegisterLicenseResponseDto>();
@ -164,10 +166,10 @@ public class LicenseService : ILicenseService
await provider.RemoveAsync(CacheKey);
}
public async Task AddLicense(string license, string email)
public async Task AddLicense(string license, string email, string? discordId)
{
var serverSetting = await _unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey);
var lic = await RegisterLicense(license, email);
var lic = await RegisterLicense(license, email, discordId);
if (string.IsNullOrWhiteSpace(lic))
throw new KavitaException("unable-to-register-k+");
serverSetting.Value = lic;
@ -199,4 +201,43 @@ public class LicenseService : ILicenseService
return false;
}
public async Task<bool> ResetLicense(string license, string email)
{
try
{
var encryptedLicense = await _unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey);
var response = await (Configuration.KavitaPlusApiUrl + "/api/license/reset")
.WithHeader("Accept", "application/json")
.WithHeader("User-Agent", "Kavita")
.WithHeader("x-license-key", encryptedLicense.Value)
.WithHeader("x-installId", HashUtil.ServerToken())
.WithHeader("x-kavita-version", BuildInfo.Version)
.WithHeader("Content-Type", "application/json")
.WithTimeout(TimeSpan.FromSeconds(Configuration.DefaultTimeOutSecs))
.PostJsonAsync(new ResetLicenseDto()
{
License = license.Trim(),
InstallId = HashUtil.ServerToken(),
EmailId = email
})
.ReceiveString();
if (string.IsNullOrEmpty(response))
{
var provider = _cachingProviderFactory.GetCachingProvider(EasyCacheProfiles.License);
await provider.RemoveAsync(CacheKey);
return true;
}
_logger.LogError("An error happened during the request to Kavita+ API: {ErrorMessage}", response);
throw new KavitaException(response);
}
catch (FlurlHttpException e)
{
_logger.LogError(e, "An error happened during the request to Kavita+ API");
}
return false;
}
}