1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-12-16 11:37:58 +02:00
Sonarr/NzbDrone.Api/Authentication/EnableStatelessAuthInNancy.cs

55 lines
1.7 KiB
C#
Raw Normal View History

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