AuthService.cs 6.9 KB

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