AuthService.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. if (authAttribtues.IgnoreLegacyAuth)
  132. {
  133. return true;
  134. }
  135. return false;
  136. }
  137. private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request, AuthenticationInfo tokenInfo)
  138. {
  139. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  140. {
  141. return true;
  142. }
  143. if (authAttribtues.AllowLocal && request.IsLocal)
  144. {
  145. return true;
  146. }
  147. if (authAttribtues.AllowLocalOnly && request.IsLocal)
  148. {
  149. return true;
  150. }
  151. if (string.IsNullOrEmpty(auth.Token))
  152. {
  153. return true;
  154. }
  155. if (tokenInfo != null && tokenInfo.UserId.Equals(Guid.Empty))
  156. {
  157. return true;
  158. }
  159. return false;
  160. }
  161. private static void ValidateRoles(string[] roles, User user)
  162. {
  163. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  164. {
  165. if (user == null || !user.Policy.IsAdministrator)
  166. {
  167. throw new SecurityException("User does not have admin access.")
  168. {
  169. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  170. };
  171. }
  172. }
  173. if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
  174. {
  175. if (user == null || !user.Policy.EnableContentDeletion)
  176. {
  177. throw new SecurityException("User does not have delete access.")
  178. {
  179. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  180. };
  181. }
  182. }
  183. if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
  184. {
  185. if (user == null || !user.Policy.EnableContentDownloading)
  186. {
  187. throw new SecurityException("User does not have download access.")
  188. {
  189. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  190. };
  191. }
  192. }
  193. }
  194. private static AuthenticationInfo GetTokenInfo(IRequest request)
  195. {
  196. request.Items.TryGetValue("OriginalAuthenticationInfo", out var info);
  197. return info as AuthenticationInfo;
  198. }
  199. private void ValidateSecurityToken(IRequest request, string token)
  200. {
  201. if (string.IsNullOrEmpty(token))
  202. {
  203. throw new SecurityException("Access token is required.");
  204. }
  205. var info = GetTokenInfo(request);
  206. if (info == null)
  207. {
  208. throw new SecurityException("Access token is invalid or expired.");
  209. }
  210. //if (!string.IsNullOrEmpty(info.UserId))
  211. //{
  212. // var user = _userManager.GetUserById(info.UserId);
  213. // if (user == null || user.Configuration.IsDisabled)
  214. // {
  215. // throw new SecurityException("User account has been disabled.");
  216. // }
  217. //}
  218. }
  219. }
  220. }