using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
namespace zero.Preview;
public class PreviewService : IPreviewService
{
protected IZeroTokenProvider TokenProvider { get; private set; }
protected IZeroOptions Options { get; private set; }
public PreviewService(IZeroTokenProvider tokenProvider, IZeroOptions options)
{
TokenProvider = tokenProvider;
Options = options;
}
///
public async Task CreateAccessToken(string key, ClaimsPrincipal backofficeUser)
{
string fullKey = GetKey(key, backofficeUser);
return await TokenProvider.Create(fullKey, TimeSpan.FromMinutes(Options.For().TokenExpirationInMinutes), 32);
}
///
public async Task IsAccessGranted(HttpRequest request, ClaimsPrincipal backofficeUser)
{
string token = request.Query[Options.For().QueryParameter];
if (!token.HasValue())
{
return false;
}
return await IsAccessGranted(token, backofficeUser);
}
///
public async Task IsAccessGranted(string token, ClaimsPrincipal backofficeUser)
{
return await TokenProvider.Exists(token);
}
///
/// Generate the key for a new preview access
///
protected string GetKey(string keyPrefix, ClaimsPrincipal backofficeUser)
{
//string userId = UserManager.GetUserId(backofficeUser);
//if (userId.IsNullOrEmpty())
//{
// throw new InvalidOperationException("Preview access is only granted for authenticated users");
//}
if (keyPrefix.IsNullOrEmpty())
{
throw new ArgumentNullException(nameof(keyPrefix), "Please define a key for generating preview access");
}
return "zero:preview:" + /*userId + ":" + */ keyPrefix;
}
}
public interface IPreviewService
{
///
/// Create a token for a new preview access.
///
Task CreateAccessToken(string key, ClaimsPrincipal backofficeUser);
//
/// Determine whether the access to the preview is granted based on an HTTP request
///
Task IsAccessGranted(HttpRequest request, ClaimsPrincipal backofficeUser);
///
/// Determine whether the access to the preview is granted based on the passed token
///
Task IsAccessGranted(string token, ClaimsPrincipal backofficeUser);
}