jellyfin-server/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs

78 lines
2.6 KiB
C#
Raw Normal View History

2021-06-18 22:26:58 +00:00
using System.Collections.Generic;
2021-04-01 21:08:22 +00:00
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Data.Entities.Security;
using MediaBrowser.Controller.Security;
using Microsoft.EntityFrameworkCore;
namespace Jellyfin.Server.Implementations.Security
{
/// <inheritdoc />
public class AuthenticationManager : IAuthenticationManager
{
2023-01-16 17:14:44 +00:00
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
2021-04-01 21:08:22 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticationManager"/> class.
/// </summary>
/// <param name="dbProvider">The database provider.</param>
2023-01-16 17:14:44 +00:00
public AuthenticationManager(IDbContextFactory<JellyfinDbContext> dbProvider)
2021-04-01 21:08:22 +00:00
{
_dbProvider = dbProvider;
}
/// <inheritdoc />
public async Task CreateApiKey(string name)
{
var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{
dbContext.ApiKeys.Add(new ApiKey(name));
2021-04-01 21:08:22 +00:00
await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
2021-04-01 21:08:22 +00:00
}
/// <inheritdoc />
public async Task<IReadOnlyList<AuthenticationInfo>> GetApiKeys()
{
var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{
return await dbContext.ApiKeys
.Select(key => new AuthenticationInfo
{
AppName = key.Name,
AccessToken = key.AccessToken,
DateCreated = key.DateCreated,
DeviceId = string.Empty,
DeviceName = string.Empty,
AppVersion = string.Empty
}).ToListAsync().ConfigureAwait(false);
}
2021-04-01 21:08:22 +00:00
}
/// <inheritdoc />
2021-06-18 22:26:58 +00:00
public async Task DeleteApiKey(string accessToken)
2021-04-01 21:08:22 +00:00
{
var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
2021-04-01 21:08:22 +00:00
{
var key = await dbContext.ApiKeys
.Where(apiKey => apiKey.AccessToken == accessToken)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
2021-04-01 21:08:22 +00:00
2022-12-05 14:00:20 +00:00
if (key is null)
{
return;
}
dbContext.Remove(key);
2021-04-01 21:08:22 +00:00
await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
2021-04-01 21:08:22 +00:00
}
}
}