From c6a362bf2ba2f465f1998501c0dd8a73e0a0d11c Mon Sep 17 00:00:00 2001 From: Jamie Rees Date: Wed, 4 Jul 2018 14:28:01 +0100 Subject: [PATCH] Added the ability to impersonate a user when using the API Key. This allows people to use the API and request as a certain user. #2363 --- src/Ombi/ApiKeyMiddlewear.cs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/Ombi/ApiKeyMiddlewear.cs b/src/Ombi/ApiKeyMiddlewear.cs index f38317b3e..f3c956df4 100644 --- a/src/Ombi/ApiKeyMiddlewear.cs +++ b/src/Ombi/ApiKeyMiddlewear.cs @@ -94,9 +94,31 @@ namespace Ombi } else { - var identity = new GenericIdentity("API"); - var principal = new GenericPrincipal(identity, new[] { "Admin", "ApiUser" }); - context.User = principal; + // Check if we have a UserName header if so we can impersonate that user + if (context.Request.Headers.Keys.Contains("UserName", StringComparer.InvariantCultureIgnoreCase)) + { + var username = context.Request.Headers["UserName"].FirstOrDefault(); + var um = context.RequestServices.GetService(); + var user = await um.Users.FirstOrDefaultAsync(x => + x.UserName.Equals(username, StringComparison.InvariantCultureIgnoreCase)); + if (user == null) + { + context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; + await context.Response.WriteAsync("Invalid User"); + await next.Invoke(context); + } + var roles = await um.GetRolesAsync(user); + var identity = new GenericIdentity(user.UserName); + var principal = new GenericPrincipal(identity, roles.ToArray()); + context.User = principal; + } + else + { + var identity = new GenericIdentity("API"); + var principal = new GenericPrincipal(identity, new[] { "Admin", "ApiUser" }); + context.User = principal; + } + await next.Invoke(context); } }