2013-09-20 22:19:48 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
2013-09-20 07:31:02 +00:00
|
|
|
|
using Nancy;
|
|
|
|
|
using Nancy.Bootstrapper;
|
2013-09-20 22:19:48 +00:00
|
|
|
|
using NzbDrone.Api.Extensions;
|
|
|
|
|
using NzbDrone.Api.Extensions.Pipelines;
|
2013-09-20 07:31:02 +00:00
|
|
|
|
using NzbDrone.Common.EnvironmentInfo;
|
|
|
|
|
using NzbDrone.Core.Configuration;
|
|
|
|
|
|
|
|
|
|
namespace NzbDrone.Api.Authentication
|
|
|
|
|
{
|
2013-09-20 22:19:48 +00:00
|
|
|
|
public class EnableStatelessAuthInNancy : IRegisterNancyPipeline
|
2013-09-20 07:31:02 +00:00
|
|
|
|
{
|
2013-09-23 22:31:50 +00:00
|
|
|
|
private readonly IAuthenticationService _authenticationService;
|
2013-09-20 07:31:02 +00:00
|
|
|
|
private readonly IConfigFileProvider _configFileProvider;
|
|
|
|
|
|
2013-09-23 22:31:50 +00:00
|
|
|
|
public EnableStatelessAuthInNancy(IAuthenticationService authenticationService, IConfigFileProvider configFileProvider)
|
2013-09-20 07:31:02 +00:00
|
|
|
|
{
|
2013-09-23 22:31:50 +00:00
|
|
|
|
_authenticationService = authenticationService;
|
2013-09-20 07:31:02 +00:00
|
|
|
|
_configFileProvider = configFileProvider;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Register(IPipelines pipelines)
|
|
|
|
|
{
|
|
|
|
|
pipelines.BeforeRequest.AddItemToEndOfPipeline(ValidateApiKey);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Response ValidateApiKey(NancyContext context)
|
|
|
|
|
{
|
|
|
|
|
Response response = null;
|
2013-09-20 22:19:48 +00:00
|
|
|
|
|
2013-09-23 22:31:50 +00:00
|
|
|
|
// if (!RuntimeInfo.IsProduction && context.Request.IsLocalRequest())
|
|
|
|
|
// {
|
|
|
|
|
// return response;
|
|
|
|
|
// }
|
2013-09-20 22:19:48 +00:00
|
|
|
|
|
|
|
|
|
var apiKey = context.Request.Headers.Authorization;
|
2013-09-20 07:31:02 +00:00
|
|
|
|
|
2013-09-23 22:31:50 +00:00
|
|
|
|
if (context.Request.IsApiRequest() && !ValidApiKey(apiKey) && !_authenticationService.IsAuthenticated(context))
|
2013-09-20 07:31:02 +00:00
|
|
|
|
{
|
|
|
|
|
response = new Response { StatusCode = HttpStatusCode.Unauthorized };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return response;
|
|
|
|
|
}
|
2013-09-23 22:31:50 +00:00
|
|
|
|
|
|
|
|
|
private bool ValidApiKey(string apiKey)
|
|
|
|
|
{
|
|
|
|
|
if (String.IsNullOrWhiteSpace(apiKey)) return false;
|
|
|
|
|
if (!apiKey.Equals(_configFileProvider.ApiKey)) return false;
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
2013-09-20 07:31:02 +00:00
|
|
|
|
}
|
|
|
|
|
}
|