Updated Nancy to 2.0

This commit is contained in:
ta264
2019-08-28 22:43:55 +01:00
committed by Qstick
parent 6c4e3b1fd5
commit 79cf3079c3
68 changed files with 394 additions and 400 deletions
@@ -1,62 +0,0 @@
using Nancy;
using Nancy.Authentication.Basic;
using Nancy.Authentication.Forms;
using Nancy.Bootstrapper;
using Nancy.Cryptography;
using NzbDrone.Api.Extensions.Pipelines;
using NzbDrone.Core.Configuration;
namespace NzbDrone.Api.Authentication
{
public class EnableAuthInNancy : IRegisterNancyPipeline
{
private readonly IAuthenticationService _authenticationService;
private readonly IConfigService _configService;
private readonly IConfigFileProvider _configFileProvider;
public EnableAuthInNancy(IAuthenticationService authenticationService,
IConfigService configService,
IConfigFileProvider configFileProvider)
{
_authenticationService = authenticationService;
_configService = configService;
_configFileProvider = configFileProvider;
}
public void Register(IPipelines pipelines)
{
RegisterFormsAuth(pipelines);
pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration(_authenticationService, "Sonarr"));
pipelines.BeforeRequest.AddItemToEndOfPipeline(RequiresAuthentication);
}
private Response RequiresAuthentication(NancyContext context)
{
Response response = null;
if (!_authenticationService.IsAuthenticated(context))
{
response = new Response { StatusCode = HttpStatusCode.Unauthorized };
}
return response;
}
private void RegisterFormsAuth(IPipelines pipelines)
{
var cryptographyConfiguration = new CryptographyConfiguration(
new RijndaelEncryptionProvider(new PassphraseKeyGenerator(_configService.RijndaelPassphrase,
new byte[] {1, 2, 3, 4, 5, 6, 7, 8})),
new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase,
new byte[] {1, 2, 3, 4, 5, 6, 7, 8}))
);
FormsAuthentication.Enable(pipelines, new FormsAuthenticationConfiguration
{
RedirectUrl = "~/login",
UserMapper = _authenticationService,
CryptographyConfiguration = cryptographyConfiguration
});
}
}
}
@@ -3,9 +3,6 @@ using Nancy;
using Nancy.Authentication.Forms;
using Nancy.Extensions;
using Nancy.ModelBinding;
using NLog;
using NzbDrone.Common.Instrumentation;
using NzbDrone.Core.Authentication;
using NzbDrone.Core.Configuration;
namespace Radarr.Http.Authentication
@@ -19,8 +16,8 @@ namespace Radarr.Http.Authentication
{
_authService = authService;
_configFileProvider = configFileProvider;
Post["/login"] = x => Login(this.Bind<LoginResource>());
Get["/logout"] = x => Logout();
Post("/login", x => Login(this.Bind<LoginResource>()));
Get("/logout", x => Logout());
}
private Response Login(LoginResource resource)
@@ -1,12 +1,12 @@
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using Nancy;
using Nancy.Authentication.Basic;
using Nancy.Authentication.Forms;
using Nancy.Security;
using NLog;
using NzbDrone.Common.Extensions;
using NzbDrone.Common.Instrumentation;
using NzbDrone.Core.Authentication;
using NzbDrone.Core.Configuration;
using Radarr.Http.Extensions;
@@ -26,7 +26,7 @@ namespace Radarr.Http.Authentication
public class AuthenticationService : IAuthenticationService
{
private static readonly Logger _authLogger = LogManager.GetLogger("Auth");
private static readonly NzbDroneUser AnonymousUser = new NzbDroneUser { UserName = "Anonymous" };
private const string AnonymousUser = "Anonymous";
private readonly IUserService _userService;
private readonly NancyContext _nancyContext;
@@ -80,15 +80,15 @@ namespace Radarr.Http.Authentication
if (context.CurrentUser != null)
{
LogLogout(context, context.CurrentUser.UserName);
LogLogout(context, context.CurrentUser.Identity.Name);
}
}
public IUserIdentity Validate(string username, string password)
public ClaimsPrincipal Validate(string username, string password)
{
if (AUTH_METHOD == AuthenticationType.None)
{
return AnonymousUser;
return new ClaimsPrincipal(new GenericIdentity(AnonymousUser));
}
var user = _userService.FindUser(username, password);
@@ -101,7 +101,7 @@ namespace Radarr.Http.Authentication
LogSuccess(_context, username);
}
return new NzbDroneUser { UserName = user.Username };
return new ClaimsPrincipal(new GenericIdentity(user.Username));
}
LogFailure(_context, username);
@@ -109,18 +109,18 @@ namespace Radarr.Http.Authentication
return null;
}
public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
public ClaimsPrincipal GetUserFromIdentifier(Guid identifier, NancyContext context)
{
if (AUTH_METHOD == AuthenticationType.None)
{
return AnonymousUser;
return new ClaimsPrincipal(new GenericIdentity(AnonymousUser));
}
var user = _userService.FindUser(identifier);
if (user != null)
{
return new NzbDroneUser { UserName = user.Username };
return new ClaimsPrincipal(new GenericIdentity(user.Username));
}
LogInvalidated(_context);
@@ -76,7 +76,7 @@ namespace Radarr.Http.Authentication
FormsAuthentication.FormsAuthenticationCookieName = "RadarrAuth";
var cryptographyConfiguration = new CryptographyConfiguration(
new RijndaelEncryptionProvider(new PassphraseKeyGenerator(_configService.RijndaelPassphrase, Encoding.ASCII.GetBytes(_configService.RijndaelSalt))),
new AesEncryptionProvider(new PassphraseKeyGenerator(_configService.RijndaelPassphrase, Encoding.ASCII.GetBytes(_configService.RijndaelSalt))),
new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase, Encoding.ASCII.GetBytes(_configService.HmacSalt)))
);
@@ -99,7 +99,7 @@ namespace Radarr.Http.Authentication
context.Response.Headers["Location"].StartsWith($"{_configFileProvider.UrlBase}/login", StringComparison.InvariantCultureIgnoreCase)) ||
context.Response.StatusCode == HttpStatusCode.Unauthorized)
{
context.Response = new { Error = "Unauthorized" }.AsResponse(HttpStatusCode.Unauthorized);
context.Response = new { Error = "Unauthorized" }.AsResponse(context, HttpStatusCode.Unauthorized);
}
}
}
@@ -1,12 +0,0 @@
using System.Collections.Generic;
using Nancy.Security;
namespace Radarr.Http.Authentication
{
public class NzbDroneUser : IUserIdentity
{
public string UserName { get; set; }
public IEnumerable<string> Claims { get; set; }
}
}
@@ -14,7 +14,9 @@ namespace Radarr.Http.ErrorManagement
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
if (statusCode == HttpStatusCode.SeeOther || statusCode == HttpStatusCode.OK)
{
return;
}
if (statusCode == HttpStatusCode.Continue)
{
@@ -23,13 +25,17 @@ namespace Radarr.Http.ErrorManagement
}
if (statusCode == HttpStatusCode.Unauthorized)
{
return;
}
if (context.Response.ContentType == "text/html" || context.Response.ContentType == "text/plain")
{
context.Response = new ErrorModel
{
Message = statusCode.ToString()
}.AsResponse(statusCode);
{
Message = statusCode.ToString()
}.AsResponse(context, statusCode);
}
}
}
}
}
@@ -27,14 +27,14 @@ namespace Radarr.Http.ErrorManagement
if (exception is ApiException apiException)
{
_logger.Warn(apiException, "API Error");
return apiException.ToErrorResponse();
return apiException.ToErrorResponse(context);
}
if (exception is ValidationException validationException)
{
_logger.Warn("Invalid request {0}", validationException.Message);
return validationException.Errors.AsResponse(HttpStatusCode.BadRequest);
return validationException.Errors.AsResponse(context, HttpStatusCode.BadRequest);
}
if (exception is NzbDroneClientException clientException)
@@ -43,7 +43,7 @@ namespace Radarr.Http.ErrorManagement
{
Message = exception.Message,
Description = exception.ToString()
}.AsResponse((HttpStatusCode)clientException.StatusCode);
}.AsResponse(context, (HttpStatusCode)clientException.StatusCode);
}
if (exception is ModelNotFoundException notFoundException)
@@ -52,7 +52,7 @@ namespace Radarr.Http.ErrorManagement
{
Message = exception.Message,
Description = exception.ToString()
}.AsResponse(HttpStatusCode.NotFound);
}.AsResponse(context, HttpStatusCode.NotFound);
}
if (exception is ModelConflictException conflictException)
@@ -61,7 +61,7 @@ namespace Radarr.Http.ErrorManagement
{
Message = exception.Message,
Description = exception.ToString()
}.AsResponse(HttpStatusCode.Conflict);
}.AsResponse(context, HttpStatusCode.Conflict);
}
if (exception is SQLiteException sqLiteException)
@@ -72,7 +72,7 @@ namespace Radarr.Http.ErrorManagement
return new ErrorModel
{
Message = exception.Message,
}.AsResponse(HttpStatusCode.Conflict);
}.AsResponse(context, HttpStatusCode.Conflict);
}
_logger.Error(sqLiteException, "[{0} {1}]", context.Request.Method, context.Request.Path);
@@ -84,7 +84,7 @@ namespace Radarr.Http.ErrorManagement
{
Message = exception.Message,
Description = exception.ToString()
}.AsResponse(HttpStatusCode.InternalServerError);
}.AsResponse(context, HttpStatusCode.InternalServerError);
}
}
}
}
+2 -2
View File
@@ -19,9 +19,9 @@ namespace Radarr.Http.Exceptions
Content = content;
}
public JsonResponse<ErrorModel> ToErrorResponse()
public JsonResponse<ErrorModel> ToErrorResponse(NancyContext context)
{
return new ErrorModel(this).AsResponse(StatusCode);
return new ErrorModel(this).AsResponse(context, StatusCode);
}
private static string GetMessage(HttpStatusCode statusCode, object content)
@@ -1,22 +1,23 @@
using System.Collections.Generic;
using System.IO;
using Nancy;
using Nancy.Responses.Negotiation;
using NzbDrone.Common.Serializer;
namespace Radarr.Http.Extensions
{
public class NancyJsonSerializer : ISerializer
{
public bool CanSerialize(string contentType)
public bool CanSerialize(MediaRange contentType)
{
return true;
return contentType == "application/json";
}
public void Serialize<TModel>(string contentType, TModel model, Stream outputStream)
public void Serialize<TModel>(MediaRange contentType, TModel model, Stream outputStream)
{
Json.Serialize(model, outputStream);
}
public IEnumerable<string> Extensions { get; private set; }
}
}
}
@@ -32,9 +32,9 @@ namespace Radarr.Http.Extensions
return Json.Deserialize(value, type);
}
public static JsonResponse<TModel> AsResponse<TModel>(this TModel model, HttpStatusCode statusCode = HttpStatusCode.OK)
public static JsonResponse<TModel> AsResponse<TModel>(this TModel model, NancyContext context, HttpStatusCode statusCode = HttpStatusCode.OK)
{
var response = new JsonResponse<TModel>(model, NancySerializer) { StatusCode = statusCode };
var response = new JsonResponse<TModel>(model, NancySerializer, context.Environment) { StatusCode = statusCode };
response.Headers.DisableCache();
return response;
@@ -59,4 +59,4 @@ namespace Radarr.Http.Extensions
return headers;
}
}
}
}
@@ -27,7 +27,7 @@ namespace Radarr.Http.Frontend
_apiKey = configFileProvider.ApiKey;
_urlBase = configFileProvider.UrlBase;
Get["/initialize.js"] = x => Index();
Get("/initialize.js", x => Index());
}
private Response Index()
@@ -1,6 +1,5 @@
using System;
using System.IO;
using Nancy;
using NLog;
using NzbDrone.Common.Disk;
using NzbDrone.Common.EnvironmentInfo;
@@ -18,8 +18,8 @@ namespace Radarr.Http.Frontend
_requestMappers = requestMappers;
_logger = logger;
Get["/{resource*}"] = x => Index();
Get["/"] = x => Index();
Get("/{resource*}", x => Index());
Get("/", x => Index());
}
private Response Index()
+30 -25
View File
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using Nancy;
using Nancy.Responses.Negotiation;
using Newtonsoft.Json;
using NzbDrone.Core.Datastore;
using Radarr.Http.Extensions;
@@ -72,13 +73,13 @@ namespace Radarr.Http.REST
set
{
_deleteResource = value;
Delete[ID_ROUTE] = options =>
Delete(ID_ROUTE, options =>
{
ValidateId(options.Id);
DeleteResource((int)options.Id);
return new object().AsResponse();
};
return new object();
});
}
}
@@ -88,7 +89,7 @@ namespace Radarr.Http.REST
set
{
_getResourceById = value;
Get[ID_ROUTE] = options =>
Get(ID_ROUTE, options =>
{
ValidateId(options.Id);
try
@@ -100,13 +101,13 @@ namespace Radarr.Http.REST
return new NotFoundResponse();
}
return resource.AsResponse();
return resource;
}
catch (ModelNotFoundException)
{
return new NotFoundResponse();
}
};
});
}
}
@@ -117,11 +118,11 @@ namespace Radarr.Http.REST
{
_getResourceAll = value;
Get[ROOT_ROUTE] = options =>
Get(ROOT_ROUTE, options =>
{
var resource = GetResourceAll();
return resource.AsResponse();
};
return resource;
});
}
}
@@ -132,11 +133,11 @@ namespace Radarr.Http.REST
{
_getResourcePaged = value;
Get[ROOT_ROUTE] = options =>
Get(ROOT_ROUTE, options =>
{
var resource = GetResourcePaged(ReadPagingResourceFromRequest());
return resource.AsResponse();
};
return resource;
});
}
}
@@ -147,11 +148,11 @@ namespace Radarr.Http.REST
{
_getResourceSingle = value;
Get[ROOT_ROUTE] = options =>
Get(ROOT_ROUTE, options =>
{
var resource = GetResourceSingle();
return resource.AsResponse();
};
return resource;
});
}
}
@@ -161,12 +162,11 @@ namespace Radarr.Http.REST
set
{
_createResource = value;
Post[ROOT_ROUTE] = options =>
Post(ROOT_ROUTE, options =>
{
var id = CreateResource(ReadResourceFromRequest());
return GetResourceById(id).AsResponse(HttpStatusCode.Created);
};
return ResponseWithCode(GetResourceById(id), HttpStatusCode.Created);
});
}
}
@@ -176,23 +176,28 @@ namespace Radarr.Http.REST
set
{
_updateResource = value;
Put[ROOT_ROUTE] = options =>
Put(ROOT_ROUTE, options =>
{
var resource = ReadResourceFromRequest();
UpdateResource(resource);
return GetResourceById(resource.Id).AsResponse(HttpStatusCode.Accepted);
};
return ResponseWithCode(GetResourceById(resource.Id), HttpStatusCode.Accepted);
});
Put[ID_ROUTE] = options =>
Put(ID_ROUTE, options =>
{
var resource = ReadResourceFromRequest();
resource.Id = options.Id;
UpdateResource(resource);
return GetResourceById(resource.Id).AsResponse(HttpStatusCode.Accepted);
};
return ResponseWithCode(GetResourceById(resource.Id), HttpStatusCode.Accepted);
});
}
}
protected Negotiator ResponseWithCode(object model, HttpStatusCode statusCode)
{
return Negotiate.WithModel(model).WithStatusCode(statusCode);
}
protected TResource ReadResourceFromRequest(bool skipValidate = false)
{
TResource resource;
+4 -4
View File
@@ -5,9 +5,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="8.4.0" />
<PackageReference Include="Nancy" Version="1.4.4" />
<PackageReference Include="Nancy.Authentication.Basic" Version="1.4.1" />
<PackageReference Include="Nancy.Authentication.Forms" Version="1.4.1" />
<PackageReference Include="Nancy" Version="2.0.0" />
<PackageReference Include="Nancy.Authentication.Basic" Version="2.0.0" />
<PackageReference Include="Nancy.Authentication.Forms" Version="2.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="NLog" Version="4.6.7" />
</ItemGroup>
@@ -20,4 +20,4 @@
<HintPath>..\Libraries\Sqlite\System.Data.SQLite.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
</Project>
+16 -3
View File
@@ -1,12 +1,13 @@
using System;
using System.Linq;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Diagnostics;
using Nancy.Responses.Negotiation;
using NLog;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Instrumentation;
using NzbDrone.Core.Instrumentation;
using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.Messaging.Events;
using Radarr.Http.Extensions.Pipelines;
using TinyIoC;
@@ -51,7 +52,19 @@ namespace Radarr.Http
return _tinyIoCContainer;
}
protected override DiagnosticsConfiguration DiagnosticsConfiguration => new DiagnosticsConfiguration { Password = @"password" };
protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration
{
get
{
// We don't support Xml Serialization atm
return NancyInternalConfiguration.WithOverrides(x => x.ResponseProcessors.Remove(typeof(XmlProcessor)));
}
}
public override void Configure(Nancy.Configuration.INancyEnvironment environment)
{
environment.Diagnostics(password: @"password");
}
protected override byte[] FavIcon => null;
}
+18
View File
@@ -0,0 +1,18 @@
using Nancy;
using Nancy.Responses.Negotiation;
namespace Radarr.Http
{
public abstract class RadarrModule : NancyModule
{
protected RadarrModule(string resource)
: base(resource)
{
}
protected Negotiator ResponseWithCode(object model, HttpStatusCode statusCode)
{
return Negotiate.WithModel(model).WithStatusCode(statusCode);
}
}
}
@@ -6,6 +6,7 @@ using System.Reflection;
using Nancy;
using Nancy.Diagnostics;
using Nancy.Bootstrapper;
using Nancy.Configuration;
namespace Radarr.Http
{
@@ -52,6 +53,47 @@ namespace Radarr.Http
return this.ApplicationContainer.Resolve<INancyEngine>();
}
//
// Summary:
// Gets the Nancy.Configuration.INancyEnvironmentConfigurator used by th.
//
// Returns:
// An Nancy.Configuration.INancyEnvironmentConfigurator instance.
protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()
{
return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>();
}
//
// Summary:
// Get the Nancy.Configuration.INancyEnvironment instance.
//
// Returns:
// An configured Nancy.Configuration.INancyEnvironment instance.
//
// Remarks:
// The boostrapper must be initialised (Nancy.Bootstrapper.INancyBootstrapper.Initialise)
// prior to calling this.
public override INancyEnvironment GetEnvironment()
{
return this.ApplicationContainer.Resolve<INancyEnvironment>();
}
//
// Summary:
// Registers an Nancy.Configuration.INancyEnvironment instance in the container.
//
// Parameters:
// container:
// The container to register into.
//
// environment:
// The Nancy.Configuration.INancyEnvironment instance to register.
protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment)
{
ApplicationContainer.Register<INancyEnvironment>(environment);
}
/// <summary>
/// Create a default, unconfigured, container
/// </summary>