aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server.Implementations/User/DefaultAuthenticationProvider.cs
blob: 024500bf81b34e013683a304a370c10c17f0a523 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Common;
using MediaBrowser.Common.Cryptography;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Model.Cryptography;

namespace Jellyfin.Server.Implementations.User
{
    /// <summary>
    /// The default authentication provider.
    /// </summary>
    public class DefaultAuthenticationProvider : IAuthenticationProvider, IRequiresResolvedUser
    {
        private readonly ICryptoProvider _cryptographyProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultAuthenticationProvider"/> class.
        /// </summary>
        /// <param name="cryptographyProvider">The cryptography provider.</param>
        public DefaultAuthenticationProvider(ICryptoProvider cryptographyProvider)
        {
            _cryptographyProvider = cryptographyProvider;
        }

        /// <inheritdoc />
        public string Name => "Default";

        /// <inheritdoc />
        public bool IsEnabled => true;

        /// <inheritdoc />
        // This is dumb and an artifact of the backwards way auth providers were designed.
        // This version of authenticate was never meant to be called, but needs to be here for interface compat
        // Only the providers that don't provide local user support use this
        public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
        {
            throw new NotImplementedException();
        }

        /// <inheritdoc />
        // This is the version that we need to use for local users. Because reasons.
        public Task<ProviderAuthenticationResult> Authenticate(string username, string password, Data.Entities.User resolvedUser)
        {
            if (resolvedUser == null)
            {
                throw new AuthenticationException("Specified user does not exist.");
            }

            bool success = false;

            // As long as jellyfin supports passwordless users, we need this little block here to accommodate
            if (!HasPassword(resolvedUser))
            {
                return Task.FromResult(new ProviderAuthenticationResult
                {
                    Username = username
                });
            }

            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

            PasswordHash readyHash = PasswordHash.Parse(resolvedUser.Password);
            if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id)
                || _cryptographyProvider.DefaultHashMethod == readyHash.Id)
            {
                byte[] calculatedHash = _cryptographyProvider.ComputeHash(
                    readyHash.Id,
                    passwordBytes,
                    readyHash.Salt.ToArray());

                if (readyHash.Hash.SequenceEqual(calculatedHash))
                {
                    success = true;
                }
            }
            else
            {
                throw new AuthenticationException($"Requested crypto method not available in provider: {readyHash.Id}");
            }

            if (!success)
            {
                throw new AuthenticationException("Invalid username or password");
            }

            return Task.FromResult(new ProviderAuthenticationResult
            {
                Username = username
            });
        }

        /// <inheritdoc />
        public bool HasPassword(Data.Entities.User user)
            => !string.IsNullOrEmpty(user.Password);

        /// <inheritdoc />
        public Task ChangePassword(Data.Entities.User user, string newPassword)
        {
            if (string.IsNullOrEmpty(newPassword))
            {
                user.Password = null;
                return Task.CompletedTask;
            }

            PasswordHash newPasswordHash = _cryptographyProvider.CreatePasswordHash(newPassword);
            user.Password = newPasswordHash.ToString();

            return Task.CompletedTask;
        }

        /// <inheritdoc />
        public void ChangeEasyPassword(Data.Entities.User user, string newPassword, string newPasswordHash)
        {
            if (newPassword != null)
            {
                newPasswordHash = _cryptographyProvider.CreatePasswordHash(newPassword).ToString();
            }

            if (string.IsNullOrWhiteSpace(newPasswordHash))
            {
                throw new ArgumentNullException(nameof(newPasswordHash));
            }

            user.EasyPassword = newPasswordHash;
        }

        /// <inheritdoc />
        public string GetEasyPasswordHash(Data.Entities.User user)
        {
            return string.IsNullOrEmpty(user.EasyPassword)
                ? null
                : Hex.Encode(PasswordHash.Parse(user.EasyPassword).Hash);
        }

        /// <summary>
        /// Hashes the provided string.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="str">The string to hash.</param>
        /// <returns>The hashed string.</returns>
        public string GetHashedString(Data.Entities.User user, string str)
        {
            if (string.IsNullOrEmpty(user.Password))
            {
                return _cryptographyProvider.CreatePasswordHash(str).ToString();
            }

            // TODO: make use of iterations parameter?
            PasswordHash passwordHash = PasswordHash.Parse(user.Password);
            var salt = passwordHash.Salt.ToArray();
            return new PasswordHash(
                passwordHash.Id,
                _cryptographyProvider.ComputeHash(
                    passwordHash.Id,
                    Encoding.UTF8.GetBytes(str),
                    salt),
                salt,
                passwordHash.Parameters.ToDictionary(x => x.Key, y => y.Value)).ToString();
        }

        /// <summary>
        /// Hashes the provided string.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="str">The string to hash.</param>
        /// <returns>The hashed string.</returns>
        public ReadOnlySpan<byte> GetHashed(Data.Entities.User user, string str)
        {
            if (string.IsNullOrEmpty(user.Password))
            {
                return _cryptographyProvider.CreatePasswordHash(str).Hash;
            }

            // TODO: make use of iterations parameter?
            PasswordHash passwordHash = PasswordHash.Parse(user.Password);
            return _cryptographyProvider.ComputeHash(
                    passwordHash.Id,
                    Encoding.UTF8.GetBytes(str),
                    passwordHash.Salt.ToArray());
        }
    }
}