AuthService.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Linq;
  4. using Emby.Server.Implementations.SocketSharp;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Net;
  9. using MediaBrowser.Controller.Security;
  10. using MediaBrowser.Controller.Session;
  11. using MediaBrowser.Model.Services;
  12. using Microsoft.AspNetCore.Http;
  13. using Microsoft.Extensions.Logging;
  14. namespace Emby.Server.Implementations.HttpServer.Security
  15. {
  16. public class AuthService : IAuthService
  17. {
  18. private readonly ILogger<AuthService> _logger;
  19. private readonly IAuthorizationContext _authorizationContext;
  20. private readonly ISessionManager _sessionManager;
  21. private readonly IServerConfigurationManager _config;
  22. private readonly INetworkManager _networkManager;
  23. public AuthService(
  24. ILogger<AuthService> logger,
  25. IAuthorizationContext authorizationContext,
  26. IServerConfigurationManager config,
  27. ISessionManager sessionManager,
  28. INetworkManager networkManager)
  29. {
  30. _logger = logger;
  31. _authorizationContext = authorizationContext;
  32. _config = config;
  33. _sessionManager = sessionManager;
  34. _networkManager = networkManager;
  35. }
  36. public void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues)
  37. {
  38. ValidateUser(request, authAttribtues);
  39. }
  40. public User Authenticate(HttpRequest request, IAuthenticationAttributes authAttributes)
  41. {
  42. var req = new WebSocketSharpRequest(request, null, request.Path, _logger);
  43. var user = ValidateUser(req, authAttributes);
  44. return user;
  45. }
  46. private User ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues)
  47. {
  48. // This code is executed before the service
  49. var auth = _authorizationContext.GetAuthorizationInfo(request);
  50. if (!IsExemptFromAuthenticationToken(authAttribtues, request))
  51. {
  52. ValidateSecurityToken(request, auth.Token);
  53. }
  54. if (authAttribtues.AllowLocalOnly && !request.IsLocal)
  55. {
  56. throw new SecurityException("Operation not found.");
  57. }
  58. var user = auth.User;
  59. if (user == null && auth.UserId != Guid.Empty)
  60. {
  61. throw new SecurityException("User with Id " + auth.UserId + " not found");
  62. }
  63. if (user != null)
  64. {
  65. ValidateUserAccess(user, request, authAttribtues, auth);
  66. }
  67. var info = GetTokenInfo(request);
  68. if (!IsExemptFromRoles(auth, authAttribtues, request, info))
  69. {
  70. var roles = authAttribtues.GetRoles();
  71. ValidateRoles(roles, user);
  72. }
  73. if (!string.IsNullOrEmpty(auth.DeviceId) &&
  74. !string.IsNullOrEmpty(auth.Client) &&
  75. !string.IsNullOrEmpty(auth.Device))
  76. {
  77. _sessionManager.LogSessionActivity(auth.Client,
  78. auth.Version,
  79. auth.DeviceId,
  80. auth.Device,
  81. request.RemoteIp,
  82. user);
  83. }
  84. return user;
  85. }
  86. private void ValidateUserAccess(
  87. User user,
  88. IRequest request,
  89. IAuthenticationAttributes authAttribtues,
  90. AuthorizationInfo auth)
  91. {
  92. if (user.Policy.IsDisabled)
  93. {
  94. throw new SecurityException("User account has been disabled.")
  95. {
  96. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  97. };
  98. }
  99. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(request.RemoteIp))
  100. {
  101. throw new SecurityException("User account has been disabled.")
  102. {
  103. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  104. };
  105. }
  106. if (!user.Policy.IsAdministrator
  107. && !authAttribtues.EscapeParentalControl
  108. && !user.IsParentalScheduleAllowed())
  109. {
  110. request.Response.Headers.Add("X-Application-Error-Code", "ParentalControl");
  111. throw new SecurityException("This user account is not allowed access at this time.")
  112. {
  113. SecurityExceptionType = SecurityExceptionType.ParentalControl
  114. };
  115. }
  116. }
  117. private bool IsExemptFromAuthenticationToken(IAuthenticationAttributes authAttribtues, IRequest request)
  118. {
  119. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  120. {
  121. return true;
  122. }
  123. if (authAttribtues.AllowLocal && request.IsLocal)
  124. {
  125. return true;
  126. }
  127. if (authAttribtues.AllowLocalOnly && request.IsLocal)
  128. {
  129. return true;
  130. }
  131. return false;
  132. }
  133. private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request, AuthenticationInfo tokenInfo)
  134. {
  135. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  136. {
  137. return true;
  138. }
  139. if (authAttribtues.AllowLocal && request.IsLocal)
  140. {
  141. return true;
  142. }
  143. if (authAttribtues.AllowLocalOnly && request.IsLocal)
  144. {
  145. return true;
  146. }
  147. if (string.IsNullOrEmpty(auth.Token))
  148. {
  149. return true;
  150. }
  151. if (tokenInfo != null && tokenInfo.UserId.Equals(Guid.Empty))
  152. {
  153. return true;
  154. }
  155. return false;
  156. }
  157. private static void ValidateRoles(string[] roles, User user)
  158. {
  159. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  160. {
  161. if (user == null || !user.Policy.IsAdministrator)
  162. {
  163. throw new SecurityException("User does not have admin access.")
  164. {
  165. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  166. };
  167. }
  168. }
  169. if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
  170. {
  171. if (user == null || !user.Policy.EnableContentDeletion)
  172. {
  173. throw new SecurityException("User does not have delete access.")
  174. {
  175. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  176. };
  177. }
  178. }
  179. if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
  180. {
  181. if (user == null || !user.Policy.EnableContentDownloading)
  182. {
  183. throw new SecurityException("User does not have download access.")
  184. {
  185. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  186. };
  187. }
  188. }
  189. }
  190. private static AuthenticationInfo GetTokenInfo(IRequest request)
  191. {
  192. request.Items.TryGetValue("OriginalAuthenticationInfo", out var info);
  193. return info as AuthenticationInfo;
  194. }
  195. private void ValidateSecurityToken(IRequest request, string token)
  196. {
  197. if (string.IsNullOrEmpty(token))
  198. {
  199. throw new SecurityException("Access token is required.");
  200. }
  201. var info = GetTokenInfo(request);
  202. if (info == null)
  203. {
  204. throw new SecurityException("Access token is invalid or expired.");
  205. }
  206. //if (!string.IsNullOrEmpty(info.UserId))
  207. //{
  208. // var user = _userManager.GetUserById(info.UserId);
  209. // if (user == null || user.Configuration.IsDisabled)
  210. // {
  211. // throw new SecurityException("User account has been disabled.");
  212. // }
  213. //}
  214. }
  215. }
  216. }