AuthService.cs 8.3 KB

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