using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Data.Entities.Security;
using MediaBrowser.Controller.Security;
using Microsoft.EntityFrameworkCore;
namespace Jellyfin.Server.Implementations.Security
{
///
public class AuthenticationManager : IAuthenticationManager
{
private readonly JellyfinDbProvider _dbProvider;
///
/// Initializes a new instance of the class.
///
/// The database provider.
public AuthenticationManager(JellyfinDbProvider dbProvider)
{
_dbProvider = dbProvider;
}
///
public async Task CreateApiKey(string name)
{
await using var dbContext = _dbProvider.CreateContext();
dbContext.ApiKeys.Add(new ApiKey(name));
await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
///
public async Task> GetApiKeys()
{
await using var dbContext = _dbProvider.CreateContext();
return await dbContext.ApiKeys
.AsAsyncEnumerable()
.Select(key => new AuthenticationInfo
{
AppName = key.Name,
AccessToken = key.AccessToken.ToString("N", CultureInfo.InvariantCulture),
DateCreated = key.DateCreated,
DeviceId = string.Empty,
DeviceName = string.Empty,
AppVersion = string.Empty
}).ToListAsync().ConfigureAwait(false);
}
///
public async Task DeleteApiKey(Guid id)
{
await using var dbContext = _dbProvider.CreateContext();
var key = await dbContext.ApiKeys
.AsQueryable()
.Where(apiKey => apiKey.AccessToken == id)
.FirstOrDefaultAsync();
if (key == null)
{
return;
}
dbContext.Remove(key);
await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
}
}