AuthService.cs 6.3 KB

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