Radarr/src/Radarr.Http/Authentication/AuthenticationService.cs

279 lines
8.0 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using System.Net;
2019-08-28 21:43:55 +00:00
using System.Security.Claims;
using System.Security.Principal;
using Nancy;
2013-09-23 22:31:50 +00:00
using Nancy.Authentication.Basic;
2015-01-26 02:03:21 +00:00
using Nancy.Authentication.Forms;
using NLog;
using NzbDrone.Common.Extensions;
2015-01-26 02:03:21 +00:00
using NzbDrone.Core.Authentication;
using NzbDrone.Core.Configuration;
2018-11-23 07:03:32 +00:00
using Radarr.Http.Extensions;
2013-05-22 00:58:57 +00:00
2018-11-23 07:03:32 +00:00
namespace Radarr.Http.Authentication
2013-05-22 00:58:57 +00:00
{
2015-01-26 02:03:21 +00:00
public interface IAuthenticationService : IUserValidator, IUserMapper
{
void SetContext(NancyContext context);
void LogUnauthorized(NancyContext context);
User Login(NancyContext context, string username, string password);
void Logout(NancyContext context);
2013-09-23 22:31:50 +00:00
bool IsAuthenticated(NancyContext context);
}
public class AuthenticationService : IAuthenticationService
2013-05-22 00:58:57 +00:00
{
2019-08-28 21:43:55 +00:00
private const string AnonymousUser = "Anonymous";
2019-12-22 22:08:53 +00:00
private static readonly Logger _authLogger = LogManager.GetLogger("Auth");
private readonly IUserService _userService;
private static string API_KEY;
private static AuthenticationType AUTH_METHOD;
[ThreadStatic]
2019-12-22 21:24:11 +00:00
private static NancyContext _context;
2019-09-01 09:28:07 +00:00
public AuthenticationService(IConfigFileProvider configFileProvider, IUserService userService)
2013-05-22 00:58:57 +00:00
{
2015-01-26 02:03:21 +00:00
_userService = userService;
API_KEY = configFileProvider.ApiKey;
AUTH_METHOD = configFileProvider.AuthenticationMethod;
2013-05-22 00:58:57 +00:00
}
public void SetContext(NancyContext context)
{
// Validate and GetUserIdentifier don't have access to the NancyContext so get it from the pipeline earlier
_context = context;
}
public User Login(NancyContext context, string username, string password)
{
if (AUTH_METHOD == AuthenticationType.None)
{
return null;
}
var user = _userService.FindUser(username, password);
if (user != null)
{
LogSuccess(context, username);
return user;
}
LogFailure(context, username);
return null;
}
public void Logout(NancyContext context)
{
if (AUTH_METHOD == AuthenticationType.None)
{
return;
}
if (context.CurrentUser != null)
{
2019-08-28 21:43:55 +00:00
LogLogout(context, context.CurrentUser.Identity.Name);
}
}
2019-08-28 21:43:55 +00:00
public ClaimsPrincipal Validate(string username, string password)
2013-05-22 00:58:57 +00:00
{
if (AUTH_METHOD == AuthenticationType.None)
2013-05-22 05:55:53 +00:00
{
2019-08-28 21:43:55 +00:00
return new ClaimsPrincipal(new GenericIdentity(AnonymousUser));
2013-05-22 05:55:53 +00:00
}
2015-01-26 02:03:21 +00:00
var user = _userService.FindUser(username, password);
if (user != null)
2013-05-22 00:58:57 +00:00
{
if (AUTH_METHOD != AuthenticationType.Basic)
{
// Don't log success for basic auth
LogSuccess(_context, username);
}
2019-08-28 21:43:55 +00:00
return new ClaimsPrincipal(new GenericIdentity(user.Username));
2013-05-22 00:58:57 +00:00
}
LogFailure(_context, username);
2013-05-22 00:58:57 +00:00
return null;
}
2013-07-14 07:00:50 +00:00
2019-08-28 21:43:55 +00:00
public ClaimsPrincipal GetUserFromIdentifier(Guid identifier, NancyContext context)
2013-07-14 07:00:50 +00:00
{
if (AUTH_METHOD == AuthenticationType.None)
2013-07-14 07:00:50 +00:00
{
2019-08-28 21:43:55 +00:00
return new ClaimsPrincipal(new GenericIdentity(AnonymousUser));
2013-07-14 07:00:50 +00:00
}
2015-01-26 02:03:21 +00:00
var user = _userService.FindUser(identifier);
if (user != null)
{
2019-08-28 21:43:55 +00:00
return new ClaimsPrincipal(new GenericIdentity(user.Username));
2015-01-26 02:03:21 +00:00
}
LogInvalidated(_context);
2015-01-26 02:03:21 +00:00
return null;
2013-07-14 07:00:50 +00:00
}
2013-09-23 22:31:50 +00:00
public bool IsAuthenticated(NancyContext context)
{
var apiKey = GetApiKey(context);
2013-09-23 22:31:50 +00:00
if (context.Request.IsApiRequest())
{
return ValidApiKey(apiKey);
}
if (AUTH_METHOD == AuthenticationType.None)
{
2015-01-26 02:03:21 +00:00
return true;
}
2015-01-26 02:03:21 +00:00
if (context.Request.IsFeedRequest())
{
if (ValidUser(context) || ValidApiKey(apiKey))
{
return true;
}
return false;
}
2015-01-26 02:03:21 +00:00
if (context.Request.IsLoginRequest())
{
return true;
}
if (context.Request.IsContentRequest())
{
return true;
}
if (ValidUser(context))
{
return true;
}
return false;
}
private bool ValidUser(NancyContext context)
{
2019-12-22 22:08:53 +00:00
if (context.CurrentUser != null)
{
return true;
}
return false;
}
private bool ValidApiKey(string apiKey)
{
2019-12-22 22:08:53 +00:00
if (API_KEY.Equals(apiKey))
{
return true;
}
return false;
}
private string GetApiKey(NancyContext context)
{
var apiKeyHeader = context.Request.Headers["X-Api-Key"].FirstOrDefault();
var apiKeyQueryString = context.Request.Query["ApiKey"];
if (!apiKeyHeader.IsNullOrWhiteSpace())
{
return apiKeyHeader;
}
if (apiKeyQueryString.HasValue)
{
return apiKeyQueryString.Value;
}
return context.Request.Headers.Authorization;
2013-09-23 22:31:50 +00:00
}
public void LogUnauthorized(NancyContext context)
{
_authLogger.Info("Auth-Unauthorized ip {0} url '{1}'", GetRemoteIP(context), context.Request.Url.ToString());
}
private void LogInvalidated(NancyContext context)
{
_authLogger.Info("Auth-Invalidated ip {0}", GetRemoteIP(context));
}
private void LogFailure(NancyContext context, string username)
{
_authLogger.Warn("Auth-Failure ip {0} username '{1}'", GetRemoteIP(context), username);
}
private void LogSuccess(NancyContext context, string username)
{
_authLogger.Info("Auth-Success ip {0} username '{1}'", GetRemoteIP(context), username);
}
private void LogLogout(NancyContext context, string username)
{
_authLogger.Info("Auth-Logout ip {0} username '{1}'", GetRemoteIP(context), username);
}
private string GetRemoteIP(NancyContext context)
{
if (context == null || context.Request == null)
{
return "Unknown";
}
var remoteAddress = context.Request.UserHostAddress;
IPAddress remoteIP;
// Only check if forwarded by a local network reverse proxy
if (IPAddress.TryParse(remoteAddress, out remoteIP) && remoteIP.IsLocalAddress())
{
var realIPHeader = context.Request.Headers["X-Real-IP"];
if (realIPHeader.Any())
{
return realIPHeader.First().ToString();
}
var forwardedForHeader = context.Request.Headers["X-Forwarded-For"];
if (forwardedForHeader.Any())
{
// Get the first address that was forwarded by a local IP to prevent remote clients faking another proxy
foreach (var forwardedForAddress in forwardedForHeader.SelectMany(v => v.Split(',')).Select(v => v.Trim()).Reverse())
{
if (!IPAddress.TryParse(forwardedForAddress, out remoteIP))
{
return remoteAddress;
}
if (!remoteIP.IsLocalAddress())
{
return forwardedForAddress;
}
remoteAddress = forwardedForAddress;
}
}
}
return remoteAddress;
}
2013-05-22 00:58:57 +00:00
}
}