AuthorizationRequestFilterAttribute.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. using MediaBrowser.Controller.Entities;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Session;
  4. using MediaBrowser.Model.Logging;
  5. using ServiceStack.Web;
  6. using System;
  7. using System.Collections.Generic;
  8. namespace MediaBrowser.Api
  9. {
  10. public class AuthorizationRequestFilterAttribute : Attribute, IHasRequestFilter
  11. {
  12. //This property will be resolved by the IoC container
  13. /// <summary>
  14. /// Gets or sets the user manager.
  15. /// </summary>
  16. /// <value>The user manager.</value>
  17. public IUserManager UserManager { get; set; }
  18. public ISessionManager SessionManager { get; set; }
  19. /// <summary>
  20. /// Gets or sets the logger.
  21. /// </summary>
  22. /// <value>The logger.</value>
  23. public ILogger Logger { get; set; }
  24. /// <summary>
  25. /// The request filter is executed before the service.
  26. /// </summary>
  27. /// <param name="request">The http request wrapper</param>
  28. /// <param name="response">The http response wrapper</param>
  29. /// <param name="requestDto">The request DTO</param>
  30. public void RequestFilter(IRequest request, IResponse response, object requestDto)
  31. {
  32. //This code is executed before the service
  33. var auth = GetAuthorizationDictionary(request);
  34. if (auth != null)
  35. {
  36. User user = null;
  37. if (auth.ContainsKey("UserId"))
  38. {
  39. var userId = auth["UserId"];
  40. if (!string.IsNullOrEmpty(userId))
  41. {
  42. user = UserManager.GetUserById(new Guid(userId));
  43. }
  44. }
  45. string deviceId;
  46. string device;
  47. string client;
  48. string version;
  49. auth.TryGetValue("DeviceId", out deviceId);
  50. auth.TryGetValue("Device", out device);
  51. auth.TryGetValue("Client", out client);
  52. auth.TryGetValue("Version", out version);
  53. if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(version))
  54. {
  55. var remoteEndPoint = request.RemoteIp;
  56. SessionManager.LogSessionActivity(client, version, deviceId, device, remoteEndPoint, user);
  57. }
  58. }
  59. }
  60. /// <summary>
  61. /// Gets the auth.
  62. /// </summary>
  63. /// <param name="httpReq">The HTTP req.</param>
  64. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  65. private static Dictionary<string, string> GetAuthorizationDictionary(IRequest httpReq)
  66. {
  67. var auth = httpReq.Headers["Authorization"];
  68. return GetAuthorization(auth);
  69. }
  70. public static User GetCurrentUser(IRequest httpReq, IUserManager userManager)
  71. {
  72. var info = GetAuthorization(httpReq);
  73. return string.IsNullOrEmpty(info.UserId) ? null :
  74. userManager.GetUserById(new Guid(info.UserId));
  75. }
  76. /// <summary>
  77. /// Gets the authorization.
  78. /// </summary>
  79. /// <param name="httpReq">The HTTP req.</param>
  80. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  81. public static AuthorizationInfo GetAuthorization(IRequest httpReq)
  82. {
  83. var auth = GetAuthorizationDictionary(httpReq);
  84. string userId = null;
  85. string deviceId = null;
  86. string device = null;
  87. string client = null;
  88. string version = null;
  89. if (auth != null)
  90. {
  91. auth.TryGetValue("UserId", out userId);
  92. auth.TryGetValue("DeviceId", out deviceId);
  93. auth.TryGetValue("Device", out device);
  94. auth.TryGetValue("Client", out client);
  95. auth.TryGetValue("Version", out version);
  96. }
  97. return new AuthorizationInfo
  98. {
  99. Client = client,
  100. Device = device,
  101. DeviceId = deviceId,
  102. UserId = userId,
  103. Version = version
  104. };
  105. }
  106. /// <summary>
  107. /// Gets the authorization.
  108. /// </summary>
  109. /// <param name="authorizationHeader">The authorization header.</param>
  110. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  111. private static Dictionary<string, string> GetAuthorization(string authorizationHeader)
  112. {
  113. if (authorizationHeader == null) return null;
  114. var parts = authorizationHeader.Split(' ');
  115. // There should be at least to parts
  116. if (parts.Length < 2) return null;
  117. // It has to be a digest request
  118. if (!string.Equals(parts[0], "MediaBrowser", StringComparison.OrdinalIgnoreCase))
  119. {
  120. return null;
  121. }
  122. // Remove uptil the first space
  123. authorizationHeader = authorizationHeader.Substring(authorizationHeader.IndexOf(' '));
  124. parts = authorizationHeader.Split(',');
  125. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  126. foreach (var item in parts)
  127. {
  128. var param = item.Trim().Split(new[] { '=' }, 2);
  129. result.Add(param[0], param[1].Trim(new[] { '"' }));
  130. }
  131. return result;
  132. }
  133. /// <summary>
  134. /// A new shallow copy of this filter is used on every request.
  135. /// </summary>
  136. /// <returns>IHasRequestFilter.</returns>
  137. public IHasRequestFilter Copy()
  138. {
  139. return this;
  140. }
  141. /// <summary>
  142. /// Order in which Request Filters are executed.
  143. /// &lt;0 Executed before global request filters
  144. /// &gt;0 Executed after global request filters
  145. /// </summary>
  146. /// <value>The priority.</value>
  147. public int Priority
  148. {
  149. get { return 0; }
  150. }
  151. }
  152. public class AuthorizationInfo
  153. {
  154. public string UserId;
  155. public string DeviceId;
  156. public string Device;
  157. public string Client;
  158. public string Version;
  159. }
  160. }