AuthService.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Connect;
  3. using MediaBrowser.Controller.Devices;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Net;
  7. using MediaBrowser.Controller.Security;
  8. using MediaBrowser.Controller.Session;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. namespace MediaBrowser.Server.Implementations.HttpServer.Security
  13. {
  14. public class AuthService : IAuthService
  15. {
  16. private readonly IServerConfigurationManager _config;
  17. public AuthService(IUserManager userManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config, IConnectManager connectManager, ISessionManager sessionManager, IDeviceManager deviceManager)
  18. {
  19. AuthorizationContext = authorizationContext;
  20. _config = config;
  21. DeviceManager = deviceManager;
  22. SessionManager = sessionManager;
  23. ConnectManager = connectManager;
  24. UserManager = userManager;
  25. }
  26. public IUserManager UserManager { get; private set; }
  27. public IAuthorizationContext AuthorizationContext { get; private set; }
  28. public IConnectManager ConnectManager { get; private set; }
  29. public ISessionManager SessionManager { get; private set; }
  30. public IDeviceManager DeviceManager { get; private set; }
  31. /// <summary>
  32. /// Redirect the client to a specific URL if authentication failed.
  33. /// If this property is null, simply `401 Unauthorized` is returned.
  34. /// </summary>
  35. public string HtmlRedirect { get; set; }
  36. public void Authenticate(IServiceRequest request,
  37. IAuthenticationAttributes authAttribtues)
  38. {
  39. ValidateUser(request, authAttribtues);
  40. }
  41. private void ValidateUser(IServiceRequest request,
  42. IAuthenticationAttributes authAttribtues)
  43. {
  44. // This code is executed before the service
  45. var auth = AuthorizationContext.GetAuthorizationInfo(request);
  46. if (!IsExemptFromAuthenticationToken(auth, authAttribtues))
  47. {
  48. var valid = IsValidConnectKey(auth.Token);
  49. if (!valid)
  50. {
  51. ValidateSecurityToken(request, auth.Token);
  52. }
  53. }
  54. var user = string.IsNullOrWhiteSpace(auth.UserId)
  55. ? null
  56. : UserManager.GetUserById(auth.UserId);
  57. if (user == null & !string.IsNullOrWhiteSpace(auth.UserId))
  58. {
  59. throw new SecurityException("User with Id " + auth.UserId + " not found");
  60. }
  61. if (user != null)
  62. {
  63. ValidateUserAccess(user, request, authAttribtues, auth);
  64. }
  65. if (!IsExemptFromRoles(auth, authAttribtues))
  66. {
  67. var roles = authAttribtues.GetRoles().ToList();
  68. ValidateRoles(roles, user);
  69. }
  70. if (!string.IsNullOrWhiteSpace(auth.DeviceId) &&
  71. !string.IsNullOrWhiteSpace(auth.Client) &&
  72. !string.IsNullOrWhiteSpace(auth.Device))
  73. {
  74. SessionManager.LogSessionActivity(auth.Client,
  75. auth.Version,
  76. auth.DeviceId,
  77. auth.Device,
  78. request.RemoteIp,
  79. user);
  80. }
  81. }
  82. private void ValidateUserAccess(User user, IServiceRequest request,
  83. IAuthenticationAttributes authAttribtues,
  84. AuthorizationInfo auth)
  85. {
  86. if (user.Policy.IsDisabled)
  87. {
  88. throw new SecurityException("User account has been disabled.")
  89. {
  90. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  91. };
  92. }
  93. if (!user.Policy.IsAdministrator &&
  94. !authAttribtues.EscapeParentalControl &&
  95. !user.IsParentalScheduleAllowed())
  96. {
  97. request.AddResponseHeader("X-Application-Error-Code", "ParentalControl");
  98. throw new SecurityException("This user account is not allowed access at this time.")
  99. {
  100. SecurityExceptionType = SecurityExceptionType.ParentalControl
  101. };
  102. }
  103. if (!string.IsNullOrWhiteSpace(auth.DeviceId))
  104. {
  105. if (!DeviceManager.CanAccessDevice(user.Id.ToString("N"), auth.DeviceId))
  106. {
  107. throw new SecurityException("User is not allowed access from this device.")
  108. {
  109. SecurityExceptionType = SecurityExceptionType.ParentalControl
  110. };
  111. }
  112. }
  113. }
  114. private bool IsExemptFromAuthenticationToken(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues)
  115. {
  116. if (!_config.Configuration.IsStartupWizardCompleted &&
  117. authAttribtues.AllowBeforeStartupWizard)
  118. {
  119. return true;
  120. }
  121. return _config.Configuration.InsecureApps7.Contains(auth.Client ?? string.Empty,
  122. StringComparer.OrdinalIgnoreCase);
  123. }
  124. private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues)
  125. {
  126. if (!_config.Configuration.IsStartupWizardCompleted &&
  127. authAttribtues.AllowBeforeStartupWizard)
  128. {
  129. return true;
  130. }
  131. return false;
  132. }
  133. private void ValidateRoles(List<string> roles, User user)
  134. {
  135. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  136. {
  137. if (user == null || !user.Policy.IsAdministrator)
  138. {
  139. throw new SecurityException("User does not have admin access.")
  140. {
  141. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  142. };
  143. }
  144. }
  145. if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
  146. {
  147. if (user == null || !user.Policy.EnableContentDeletion)
  148. {
  149. throw new SecurityException("User does not have delete access.")
  150. {
  151. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  152. };
  153. }
  154. }
  155. }
  156. private bool IsValidConnectKey(string token)
  157. {
  158. if (string.IsNullOrEmpty(token))
  159. {
  160. return false;
  161. }
  162. return ConnectManager.IsAuthorizationTokenValid(token);
  163. }
  164. private void ValidateSecurityToken(IServiceRequest request, string token)
  165. {
  166. if (string.IsNullOrWhiteSpace(token))
  167. {
  168. throw new SecurityException("Access token is invalid or expired.");
  169. }
  170. var info = (AuthenticationInfo)request.Items["OriginalAuthenticationInfo"];
  171. if (info == null)
  172. {
  173. throw new SecurityException("Access token is invalid or expired.");
  174. }
  175. if (!info.IsActive)
  176. {
  177. throw new SecurityException("Access token has expired.");
  178. }
  179. //if (!string.IsNullOrWhiteSpace(info.UserId))
  180. //{
  181. // var user = _userManager.GetUserById(info.UserId);
  182. // if (user == null || user.Configuration.IsDisabled)
  183. // {
  184. // throw new SecurityException("User account has been disabled.");
  185. // }
  186. //}
  187. }
  188. }
  189. }