aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs
blob: b79e46469c97b802d88eefed1e84dcb6699e9cc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Collections.Generic;
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
    {
        private readonly JellyfinDbProvider _dbProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationManager"/> class.
        /// </summary>
        /// <param name="dbProvider">The database provider.</param>
        public AuthenticationManager(JellyfinDbProvider dbProvider)
        {
            _dbProvider = dbProvider;
        }

        /// <inheritdoc />
        public async Task CreateApiKey(string name)
        {
            await using var dbContext = _dbProvider.CreateContext();

            dbContext.ApiKeys.Add(new ApiKey(name));

            await dbContext.SaveChangesAsync().ConfigureAwait(false);
        }

        /// <inheritdoc />
        public async Task<IReadOnlyList<AuthenticationInfo>> GetApiKeys()
        {
            await using var dbContext = _dbProvider.CreateContext();

            return await dbContext.ApiKeys
                .AsAsyncEnumerable()
                .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);
        }

        /// <inheritdoc />
        public async Task DeleteApiKey(string accessToken)
        {
            await using var dbContext = _dbProvider.CreateContext();

            var key = await dbContext.ApiKeys
                .AsQueryable()
                .Where(apiKey => apiKey.AccessToken == accessToken)
                .FirstOrDefaultAsync()
                .ConfigureAwait(false);

            if (key == null)
            {
                return;
            }

            dbContext.Remove(key);

            await dbContext.SaveChangesAsync().ConfigureAwait(false);
        }
    }
}