using System;
using System.Threading;
using System.Threading.Tasks;
using BlueWest.Cryptography;
using BlueWest.Data.Application;
using Microsoft.Extensions.Hosting;
using Redis.OM;
using Redis.OM.Searching;
namespace BlueWest.WebApi.Session
{
///
/// Session Provider Context
///
public sealed class SessionDataService : IHostedService, ISessionCache
{
private readonly RedisConnectionProvider _provider;
private RedisCollection _sessionTokens;
///
/// Index Creation Device
///
/// Redis connection
public SessionDataService(
RedisConnectionProvider provider)
{
_provider = provider;
_sessionTokens = (RedisCollection)provider.RedisCollection();
}
///
/// Empty constructor
///
public SessionDataService() { }
///
/// Get a session token by the respective Id.
///
///
///
public async Task GetSessionTokenByIdAsync(string tokenId)
{
return await _sessionTokens.Where(x => x.Id == tokenId)
.FirstOrDefaultAsync();
}
///
/// Create a new session token
///
///
public async Task AddSessionToken(SessionToken token)
{
await _sessionTokens.InsertAsync(token);
}
///
public async Task SaveAsync()
{
await _sessionTokens.SaveAsync();
}
///
/// Save session data
///
public void Save()
{
_sessionTokens.Save();
}
///
/// Gets a Bearer By Access Token Id
///
///
public async Task GetBearerByAccessTokenId(string sessionTokenId)
{
var accessToken = await _sessionTokens.Where(t => t.Id == sessionTokenId)
.FirstOrDefaultAsync();
if (accessToken == null) return string.Empty;
if (accessToken.IsValid)
{
var createdDate = DateTime.UnixEpoch.AddMilliseconds(accessToken.CreatedDate);
if (createdDate.AddMilliseconds(accessToken.ValidFor) < DateTime.Now)
{
accessToken.IsValid = false;
}
}
await _sessionTokens.SaveAsync();
return accessToken.IsValid ? accessToken.AccessToken : string.Empty;
}
///
public async Task StartAsync(CancellationToken cancellationToken)
{
await _provider.Connection.CreateIndexAsync(typeof(SessionToken));
}
///
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}