AuthService.cs 8.4 KB

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