Merged authentication so they don't step on eachother

Fixed: iCal authentication with API Key
This commit is contained in:
Mark McDowall 2014-05-10 15:24:29 -07:00
commit 412291a7c4
4 changed files with 75 additions and 74 deletions

View file

@ -1,6 +1,10 @@
using Nancy;
using System;
using System.Linq;
using Nancy;
using Nancy.Authentication.Basic;
using Nancy.Security;
using NzbDrone.Api.Extensions;
using NzbDrone.Common;
using NzbDrone.Core.Configuration;
namespace NzbDrone.Api.Authentication
@ -15,10 +19,12 @@ namespace NzbDrone.Api.Authentication
{
private readonly IConfigFileProvider _configFileProvider;
private static readonly NzbDroneUser AnonymousUser = new NzbDroneUser { UserName = "Anonymous" };
private static String API_KEY;
public AuthenticationService(IConfigFileProvider configFileProvider)
{
_configFileProvider = configFileProvider;
API_KEY = configFileProvider.ApiKey;
}
public IUserIdentity Validate(string username, string password)
@ -47,9 +53,71 @@ namespace NzbDrone.Api.Authentication
public bool IsAuthenticated(NancyContext context)
{
if (context.CurrentUser == null && _configFileProvider.AuthenticationEnabled) return false;
var apiKey = GetApiKey(context);
return true;
if (context.Request.IsApiRequest())
{
return ValidApiKey(apiKey);
}
if (context.Request.IsFeedRequest())
{
if (!Enabled)
{
return true;
}
if (ValidUser(context) || ValidApiKey(apiKey))
{
return true;
}
return false;
}
if (!Enabled)
{
return true;
}
if (ValidUser(context))
{
return true;
}
return false;
}
private bool ValidUser(NancyContext context)
{
if (context.CurrentUser != null) return true;
return false;
}
private bool ValidApiKey(string apiKey)
{
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;
}
}
}