AuthService.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Connect;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Net;
  5. using MediaBrowser.Controller.Session;
  6. using ServiceStack;
  7. using ServiceStack.Auth;
  8. using ServiceStack.Web;
  9. using System;
  10. using System.Collections.Specialized;
  11. using System.Linq;
  12. namespace MediaBrowser.Server.Implementations.HttpServer.Security
  13. {
  14. public class AuthService : IAuthService
  15. {
  16. private readonly IServerConfigurationManager _config;
  17. public AuthService(IUserManager userManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config, IConnectManager connectManager)
  18. {
  19. AuthorizationContext = authorizationContext;
  20. _config = config;
  21. ConnectManager = connectManager;
  22. SessionManager = sessionManager;
  23. UserManager = userManager;
  24. }
  25. public IUserManager UserManager { get; private set; }
  26. public ISessionManager SessionManager { get; private set; }
  27. public IAuthorizationContext AuthorizationContext { get; private set; }
  28. public IConnectManager ConnectManager { get; private set; }
  29. /// <summary>
  30. /// Restrict authentication to a specific <see cref="IAuthProvider"/>.
  31. /// For example, if this attribute should only permit access
  32. /// if the user is authenticated with <see cref="BasicAuthProvider"/>,
  33. /// you should set this property to <see cref="BasicAuthProvider.Name"/>.
  34. /// </summary>
  35. public string Provider { get; set; }
  36. /// <summary>
  37. /// Redirect the client to a specific URL if authentication failed.
  38. /// If this property is null, simply `401 Unauthorized` is returned.
  39. /// </summary>
  40. public string HtmlRedirect { get; set; }
  41. public void Authenticate(IRequest request,
  42. IResponse response,
  43. object requestDto,
  44. IAuthenticated authAttribtues)
  45. {
  46. if (HostContext.HasValidAuthSecret(request))
  47. return;
  48. //ExecuteBasic(req, res, requestDto); //first check if session is authenticated
  49. //if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)
  50. ValidateUser(request, response, authAttribtues);
  51. }
  52. private void ValidateUser(IRequest req, IResponse response, IAuthenticated authAttribtues)
  53. {
  54. // This code is executed before the service
  55. var auth = AuthorizationContext.GetAuthorizationInfo(req);
  56. if (!authAttribtues.AllowLocal || !req.IsLocal)
  57. {
  58. if (!string.IsNullOrWhiteSpace(auth.Token) ||
  59. !_config.Configuration.InsecureApps6.Contains(auth.Client ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  60. {
  61. var valid = IsValidConnectKey(auth.Token);
  62. if (!valid)
  63. {
  64. SessionManager.ValidateSecurityToken(auth.Token);
  65. }
  66. }
  67. }
  68. var user = string.IsNullOrWhiteSpace(auth.UserId)
  69. ? null
  70. : UserManager.GetUserById(auth.UserId);
  71. if (user == null & !string.IsNullOrWhiteSpace(auth.UserId))
  72. {
  73. throw new ArgumentException("User with Id " + auth.UserId + " not found");
  74. }
  75. if (user != null)
  76. {
  77. if (user.Configuration.IsDisabled)
  78. {
  79. throw new AuthenticationException("User account has been disabled.");
  80. }
  81. if (!user.Configuration.IsAdministrator &&
  82. !authAttribtues.EscapeParentalControl &&
  83. !user.IsParentalScheduleAllowed())
  84. {
  85. response.AddHeader("X-Application-Error-Code", "ParentalControl");
  86. throw new AuthenticationException("This user account is not allowed access at this time.");
  87. }
  88. }
  89. var roles = authAttribtues.GetRoles().ToList();
  90. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  91. {
  92. if (user == null || !user.Configuration.IsAdministrator)
  93. {
  94. throw new ArgumentException("Administrative access is required for this request.");
  95. }
  96. }
  97. if (!string.IsNullOrWhiteSpace(auth.DeviceId) &&
  98. !string.IsNullOrWhiteSpace(auth.Client) &&
  99. !string.IsNullOrWhiteSpace(auth.Device))
  100. {
  101. SessionManager.LogSessionActivity(auth.Client,
  102. auth.Version,
  103. auth.DeviceId,
  104. auth.Device,
  105. req.RemoteIp,
  106. user);
  107. }
  108. }
  109. private bool IsValidConnectKey(string token)
  110. {
  111. if (string.IsNullOrEmpty(token))
  112. {
  113. return false;
  114. }
  115. return ConnectManager.IsAuthorizationTokenValid(token);
  116. }
  117. protected bool DoHtmlRedirectIfConfigured(IRequest req, IResponse res, bool includeRedirectParam = false)
  118. {
  119. var htmlRedirect = this.HtmlRedirect ?? AuthenticateService.HtmlRedirect;
  120. if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(MimeTypes.Html))
  121. {
  122. DoHtmlRedirect(htmlRedirect, req, res, includeRedirectParam);
  123. return true;
  124. }
  125. return false;
  126. }
  127. public static void DoHtmlRedirect(string redirectUrl, IRequest req, IResponse res, bool includeRedirectParam)
  128. {
  129. var url = req.ResolveAbsoluteUrl(redirectUrl);
  130. if (includeRedirectParam)
  131. {
  132. var absoluteRequestPath = req.ResolveAbsoluteUrl("~" + req.PathInfo + ToQueryString(req.QueryString));
  133. url = url.AddQueryParam(HostContext.ResolveLocalizedString(LocalizedStrings.Redirect), absoluteRequestPath);
  134. }
  135. res.RedirectToUrl(url);
  136. }
  137. private static string ToQueryString(INameValueCollection queryStringCollection)
  138. {
  139. return ToQueryString((NameValueCollection)queryStringCollection.Original);
  140. }
  141. private static string ToQueryString(NameValueCollection queryStringCollection)
  142. {
  143. if (queryStringCollection == null || queryStringCollection.Count == 0)
  144. return String.Empty;
  145. return "?" + queryStringCollection.ToFormUrlEncoded();
  146. }
  147. }
  148. }