AuthService.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Connect;
  3. using MediaBrowser.Controller.Devices;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Net;
  7. using MediaBrowser.Controller.Security;
  8. using MediaBrowser.Controller.Session;
  9. using System;
  10. using System.Linq;
  11. namespace Emby.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, IDeviceManager deviceManager)
  17. {
  18. AuthorizationContext = authorizationContext;
  19. _config = config;
  20. DeviceManager = deviceManager;
  21. SessionManager = sessionManager;
  22. ConnectManager = connectManager;
  23. UserManager = userManager;
  24. }
  25. public IUserManager UserManager { get; private set; }
  26. public IAuthorizationContext AuthorizationContext { get; private set; }
  27. public IConnectManager ConnectManager { get; private set; }
  28. public ISessionManager SessionManager { get; private set; }
  29. public IDeviceManager DeviceManager { get; private set; }
  30. /// <summary>
  31. /// Redirect the client to a specific URL if authentication failed.
  32. /// If this property is null, simply `401 Unauthorized` is returned.
  33. /// </summary>
  34. public string HtmlRedirect { get; set; }
  35. public void Authenticate(IServiceRequest request,
  36. IAuthenticationAttributes authAttribtues)
  37. {
  38. ValidateUser(request, authAttribtues);
  39. }
  40. private void ValidateUser(IServiceRequest request,
  41. IAuthenticationAttributes authAttribtues)
  42. {
  43. // This code is executed before the service
  44. var auth = AuthorizationContext.GetAuthorizationInfo(request);
  45. if (!IsExemptFromAuthenticationToken(auth, authAttribtues))
  46. {
  47. var valid = IsValidConnectKey(auth.Token);
  48. if (!valid)
  49. {
  50. ValidateSecurityToken(request, auth.Token);
  51. }
  52. }
  53. var user = string.IsNullOrWhiteSpace(auth.UserId)
  54. ? null
  55. : UserManager.GetUserById(auth.UserId);
  56. if (user == null & !string.IsNullOrWhiteSpace(auth.UserId))
  57. {
  58. throw new SecurityException("User with Id " + auth.UserId + " not found");
  59. }
  60. if (user != null)
  61. {
  62. ValidateUserAccess(user, request, authAttribtues, auth);
  63. }
  64. var info = GetTokenInfo(request);
  65. if (!IsExemptFromRoles(auth, authAttribtues, info))
  66. {
  67. var roles = authAttribtues.GetRoles();
  68. ValidateRoles(roles, user);
  69. }
  70. if (!string.IsNullOrWhiteSpace(auth.DeviceId) &&
  71. !string.IsNullOrWhiteSpace(auth.Client) &&
  72. !string.IsNullOrWhiteSpace(auth.Device))
  73. {
  74. SessionManager.LogSessionActivity(auth.Client,
  75. auth.Version,
  76. auth.DeviceId,
  77. auth.Device,
  78. request.RemoteIp,
  79. user);
  80. }
  81. }
  82. private void ValidateUserAccess(User user, IServiceRequest request,
  83. IAuthenticationAttributes authAttribtues,
  84. AuthorizationInfo auth)
  85. {
  86. if (user.Policy.IsDisabled)
  87. {
  88. throw new SecurityException("User account has been disabled.")
  89. {
  90. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  91. };
  92. }
  93. if (!user.Policy.IsAdministrator &&
  94. !authAttribtues.EscapeParentalControl &&
  95. !user.IsParentalScheduleAllowed())
  96. {
  97. request.AddResponseHeader("X-Application-Error-Code", "ParentalControl");
  98. throw new SecurityException("This user account is not allowed access at this time.")
  99. {
  100. SecurityExceptionType = SecurityExceptionType.ParentalControl
  101. };
  102. }
  103. if (!string.IsNullOrWhiteSpace(auth.DeviceId))
  104. {
  105. if (!DeviceManager.CanAccessDevice(user.Id.ToString("N"), auth.DeviceId))
  106. {
  107. throw new SecurityException("User is not allowed access from this device.")
  108. {
  109. SecurityExceptionType = SecurityExceptionType.ParentalControl
  110. };
  111. }
  112. }
  113. }
  114. private bool IsExemptFromAuthenticationToken(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues)
  115. {
  116. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  117. {
  118. return true;
  119. }
  120. return false;
  121. }
  122. private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, AuthenticationInfo tokenInfo)
  123. {
  124. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  125. {
  126. return true;
  127. }
  128. if (string.IsNullOrWhiteSpace(auth.Token))
  129. {
  130. return true;
  131. }
  132. if (tokenInfo != null && string.IsNullOrWhiteSpace(tokenInfo.UserId))
  133. {
  134. return true;
  135. }
  136. return false;
  137. }
  138. private void ValidateRoles(string[] roles, User user)
  139. {
  140. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  141. {
  142. if (user == null || !user.Policy.IsAdministrator)
  143. {
  144. throw new SecurityException("User does not have admin access.")
  145. {
  146. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  147. };
  148. }
  149. }
  150. if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
  151. {
  152. if (user == null || !user.Policy.EnableContentDeletion)
  153. {
  154. throw new SecurityException("User does not have delete access.")
  155. {
  156. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  157. };
  158. }
  159. }
  160. if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
  161. {
  162. if (user == null || !user.Policy.EnableContentDownloading)
  163. {
  164. throw new SecurityException("User does not have download access.")
  165. {
  166. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  167. };
  168. }
  169. }
  170. }
  171. private AuthenticationInfo GetTokenInfo(IServiceRequest request)
  172. {
  173. object info;
  174. request.Items.TryGetValue("OriginalAuthenticationInfo", out info);
  175. return info as AuthenticationInfo;
  176. }
  177. private bool IsValidConnectKey(string token)
  178. {
  179. if (string.IsNullOrEmpty(token))
  180. {
  181. return false;
  182. }
  183. return ConnectManager.IsAuthorizationTokenValid(token);
  184. }
  185. private void ValidateSecurityToken(IServiceRequest request, string token)
  186. {
  187. if (string.IsNullOrWhiteSpace(token))
  188. {
  189. throw new SecurityException("Access token is required.");
  190. }
  191. var info = GetTokenInfo(request);
  192. if (info == null)
  193. {
  194. throw new SecurityException("Access token is invalid or expired.");
  195. }
  196. if (!info.IsActive)
  197. {
  198. throw new SecurityException("Access token has expired.");
  199. }
  200. //if (!string.IsNullOrWhiteSpace(info.UserId))
  201. //{
  202. // var user = _userManager.GetUserById(info.UserId);
  203. // if (user == null || user.Configuration.IsDisabled)
  204. // {
  205. // throw new SecurityException("User account has been disabled.");
  206. // }
  207. //}
  208. }
  209. }
  210. }