aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
blob: 129faeaab073c6fff60cefa02d0d40b0b2e5648c (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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#pragma warning disable CS1591

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Services;
using Microsoft.Net.Http.Headers;

namespace Emby.Server.Implementations.HttpServer.Security
{
    public class AuthorizationContext : IAuthorizationContext
    {
        private readonly IAuthenticationRepository _authRepo;
        private readonly IUserManager _userManager;

        public AuthorizationContext(IAuthenticationRepository authRepo, IUserManager userManager)
        {
            _authRepo = authRepo;
            _userManager = userManager;
        }

        public AuthorizationInfo GetAuthorizationInfo(object requestContext)
        {
            return GetAuthorizationInfo((IRequest)requestContext);
        }

        public AuthorizationInfo GetAuthorizationInfo(IRequest requestContext)
        {
            if (requestContext.Items.TryGetValue("AuthorizationInfo", out var cached))
            {
                return (AuthorizationInfo)cached;
            }

            return GetAuthorization(requestContext);
        }

        /// <summary>
        /// Gets the authorization.
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private AuthorizationInfo GetAuthorization(IRequest httpReq)
        {
            var auth = GetAuthorizationDictionary(httpReq);

            string deviceId = null;
            string device = null;
            string client = null;
            string version = null;
            string token = null;

            if (auth != null)
            {
                auth.TryGetValue("DeviceId", out deviceId);
                auth.TryGetValue("Device", out device);
                auth.TryGetValue("Client", out client);
                auth.TryGetValue("Version", out version);
                auth.TryGetValue("Token", out token);
            }

            if (string.IsNullOrEmpty(token))
            {
                token = httpReq.Headers["X-Emby-Token"];
            }

            if (string.IsNullOrEmpty(token))
            {
                token = httpReq.Headers["X-MediaBrowser-Token"];
            }
            if (string.IsNullOrEmpty(token))
            {
                token = httpReq.QueryString["api_key"];
            }

            var info = new AuthorizationInfo
            {
                Client = client,
                Device = device,
                DeviceId = deviceId,
                Version = version,
                Token = token
            };

            if (!string.IsNullOrWhiteSpace(token))
            {
                var result = _authRepo.Get(new AuthenticationInfoQuery
                {
                    AccessToken = token
                });

                var tokenInfo = result.Items.Count > 0 ? result.Items[0] : null;

                if (tokenInfo != null)
                {
                    var updateToken = false;

                    // TODO: Remove these checks for IsNullOrWhiteSpace
                    if (string.IsNullOrWhiteSpace(info.Client))
                    {
                        info.Client = tokenInfo.AppName;
                    }

                    if (string.IsNullOrWhiteSpace(info.DeviceId))
                    {
                        info.DeviceId = tokenInfo.DeviceId;
                    }

                    // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
                    var allowTokenInfoUpdate = info.Client == null || info.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;

                    if (string.IsNullOrWhiteSpace(info.Device))
                    {
                        info.Device = tokenInfo.DeviceName;
                    }

                    else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
                    {
                        if (allowTokenInfoUpdate)
                        {
                            updateToken = true;
                            tokenInfo.DeviceName = info.Device;
                        }
                    }

                    if (string.IsNullOrWhiteSpace(info.Version))
                    {
                        info.Version = tokenInfo.AppVersion;
                    }
                    else if (!string.Equals(info.Version, tokenInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
                    {
                        if (allowTokenInfoUpdate)
                        {
                            updateToken = true;
                            tokenInfo.AppVersion = info.Version;
                        }
                    }

                    if ((DateTime.UtcNow - tokenInfo.DateLastActivity).TotalMinutes > 3)
                    {
                        tokenInfo.DateLastActivity = DateTime.UtcNow;
                        updateToken = true;
                    }

                    if (!tokenInfo.UserId.Equals(Guid.Empty))
                    {
                        info.User = _userManager.GetUserById(tokenInfo.UserId);

                        if (info.User != null && !string.Equals(info.User.Name, tokenInfo.UserName, StringComparison.OrdinalIgnoreCase))
                        {
                            tokenInfo.UserName = info.User.Name;
                            updateToken = true;
                        }
                    }

                    if (updateToken)
                    {
                        _authRepo.Update(tokenInfo);
                    }
                }
                httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
            }

            httpReq.Items["AuthorizationInfo"] = info;

            return info;
        }

        /// <summary>
        /// Gets the auth.
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private Dictionary<string, string> GetAuthorizationDictionary(IRequest httpReq)
        {
            var auth = httpReq.Headers["X-Emby-Authorization"];

            if (string.IsNullOrEmpty(auth))
            {
                auth = httpReq.Headers[HeaderNames.Authorization];
            }

            return GetAuthorization(auth);
        }

        /// <summary>
        /// Gets the authorization.
        /// </summary>
        /// <param name="authorizationHeader">The authorization header.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private Dictionary<string, string> GetAuthorization(string authorizationHeader)
        {
            if (authorizationHeader == null)
            {
                return null;
            }

            var parts = authorizationHeader.Split(new[] { ' ' }, 2);

            // There should be at least to parts
            if (parts.Length != 2)
            {
                return null;
            }

            var acceptedNames = new[] { "MediaBrowser", "Emby" };

            // It has to be a digest request
            if (!acceptedNames.Contains(parts[0], StringComparer.OrdinalIgnoreCase))
            {
                return null;
            }

            // Remove uptil the first space
            authorizationHeader = parts[1];
            parts = authorizationHeader.Split(',');

            var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (var item in parts)
            {
                var param = item.Trim().Split(new[] { '=' }, 2);

                if (param.Length == 2)
                {
                    var value = NormalizeValue(param[1].Trim(new[] { '"' }));
                    result.Add(param[0], value);
                }
            }

            return result;
        }

        private static string NormalizeValue(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return value;
            }

            return WebUtility.HtmlEncode(value);
        }
    }
}