diff --git a/Controllers/Api/AlarmsController.cs b/Controllers/Api/AlarmsController.cs index 5ce76053b3..ef43eb06b2 100644 --- a/Controllers/Api/AlarmsController.cs +++ b/Controllers/Api/AlarmsController.cs @@ -106,7 +106,7 @@ private static async Task RenewAuthToken(PollingDataDTO pollingData, strin { using (var uow = ObjectFactory.GetInstance()) { - var terminalDO = await ObjectFactory.GetInstance().GetByToken(terminalToken); + var terminalDO = await ObjectFactory.GetInstance().GetByKey(terminalToken); if (terminalDO == null) { throw new Exception("No terminal was found with token: "+terminalToken); diff --git a/Controllers/Api/PlansController.cs b/Controllers/Api/PlansController.cs index c8e9c3064c..c6278f8fae 100644 --- a/Controllers/Api/PlansController.cs +++ b/Controllers/Api/PlansController.cs @@ -471,7 +471,6 @@ public async Task Unpublish(Guid planId) /// Unauthorized request [Fr8ApiAuthorize("Admin", "StandardUser", "Terminal")] [Fr8TerminalAuthentication] - [Fr8PlanDirectoryAuthentication] [HttpPost] [ResponseType(typeof(PlanNoChildrenDTO))] public async Task Load(PlanDTO plan) diff --git a/Controllers/Api/WarehousesController.cs b/Controllers/Api/WarehousesController.cs index 94477aabd9..b529203a30 100644 --- a/Controllers/Api/WarehousesController.cs +++ b/Controllers/Api/WarehousesController.cs @@ -24,7 +24,7 @@ public class WarehousesController : ApiController /// Query filter /// Collection of queried objects /// Unauthorized request - [Fr8TerminalAuthentication(true)] + [Fr8TerminalAuthentication] [HttpPost] [ResponseType(typeof(object[]))] public IHttpActionResult Query(QueryDTO query) @@ -48,7 +48,7 @@ public IHttpActionResult Query(QueryDTO query) /// /// Fr8 authentication headers must be provided /// Query filter - [Fr8TerminalAuthentication(true)] + [Fr8TerminalAuthentication] [HttpPost] [SwaggerResponse(HttpStatusCode.OK, "Objects were succesfully deleted")] [SwaggerResponse(HttpStatusCode.Unauthorized, "Unauthorized request", typeof(ErrorDTO))] @@ -73,7 +73,7 @@ public IHttpActionResult Delete(QueryDTO query) /// /// Fr8 authentication headers must be provided /// Crates to store in Fr8 warehouse - [Fr8TerminalAuthentication(true)] + [Fr8TerminalAuthentication] [HttpPost] [SwaggerResponse(HttpStatusCode.OK, "Objects were succesfully saved")] [SwaggerResponse(HttpStatusCode.Unauthorized, "Unauthorized request", typeof(ErrorDTO))] diff --git a/Docs/ForDevelopers/OperatingConcepts/Authorization/TerminalAuthentication.md b/Docs/ForDevelopers/OperatingConcepts/Authorization/TerminalAuthentication.md index dfdf5203e2..0f9816887e 100644 --- a/Docs/ForDevelopers/OperatingConcepts/Authorization/TerminalAuthentication.md +++ b/Docs/ForDevelopers/OperatingConcepts/Authorization/TerminalAuthentication.md @@ -8,34 +8,30 @@ Terminals often needs to communicate with the Hub. Some examples include getting ## Authentication your Terminal -Each request from the Hub to your Terminal includes these 2 properties: +Each request from the Hub to your Terminal includes these 2 headers: * **TerminalKey**: 4b54d12f7f834648be28aa247f523e21 * **CurrentHubUrl**: http://dev.fr8.co/ ### Terminal Key -The Hub generates this when it learns about a new Terminal. It functions in most respects as your Terminal's ID value but can be changed if it has been compromised. All of your Http requests need to include it in the header: - -Authorization: FR8 terminal_key=2db48191-cda3-4922-9cc2-a636e828063f +The Hub generates this when it learns about a new Terminal. It functions in most respects as your Terminal's ID value but can be changed if it has been compromised. All of your Http requests need to include it in the header: ### HubUrl -This is the endpoint of the Hub that is making the request. - +This is the endpoint of the Hub that is making the request. Fr8 is a distributed environment. Your terminal might be in use by many Hubs. This property lets you know which Hub to respond to. - ### Generating your Authentication Header When your terminal needs to make a request to the Hub, it needs to provide an authorization header with the terminal key Example: - Authorization: FR8-TOKEN key=2db48191-cda3-4922-9cc2-a636e828063f + Authorization: FR8 terminal_key=2db48191-cda3-4922-9cc2-a636e828063f -###Note. It was previously also necessary to put the ID of the current user session into the authorization header, but that has been removed. +###Note. It was previously also necessary to put the ID of the current user session into the authorization header, but that has been removed. [Go to Contents](/Docs/Home.md) diff --git a/Fr8TerminalBase.NET/BaseClasses/BaseConfiguration.cs b/Fr8TerminalBase.NET/BaseClasses/BaseConfiguration.cs index e776579d71..56c3224a49 100644 --- a/Fr8TerminalBase.NET/BaseClasses/BaseConfiguration.cs +++ b/Fr8TerminalBase.NET/BaseClasses/BaseConfiguration.cs @@ -99,21 +99,17 @@ public IHttpController Create(HttpRequestMessage request, HttpControllerDescript //it can only communicate with master hub for general purpose queries //or it can get a list of all hubs from discovery service - if (request.Headers.Contains("Fr8HubCallBackUrl") && request.Headers.Contains("Fr8HubCallbackSecret")) + if (request.Headers.Contains("CurrentHubUrl") && request.Headers.Contains("TerminalKey")) { - var apiUrl = request.Headers.GetValues("Fr8HubCallBackUrl").First().TrimEnd('\\', '/') + + var apiUrl = request.Headers.GetValues("CurrentHubUrl").First().TrimEnd('\\', '/') + $"/api/{CloudConfigurationManager.GetSetting("HubApiVersion")}"; - var secret = request.Headers.GetValues("Fr8HubCallbackSecret").First(); - var fr8UserId = request.Headers.Contains("Fr8UserId") - ? request.Headers.GetValues("Fr8UserId").First() - : null; + var secret = request.Headers.GetValues("TerminalKey").First(); _hubDiscovery.SetHubSecret(apiUrl, secret); hubCommunicatorFactoryExpression = c => new DefaultHubCommunicator( c.GetInstance() - .Create(new HubAuthenticationHeaderSignature(secret, fr8UserId)), apiUrl, secret, - fr8UserId); + .Create(new HubAuthenticationHeaderSignature(secret)), apiUrl, secret); } else { diff --git a/Fr8TerminalBase.NET/Infrastructure/HubAuthenticationHeaderSignature.cs b/Fr8TerminalBase.NET/Infrastructure/HubAuthenticationHeaderSignature.cs index 1ef688ad5c..7cae9140db 100644 --- a/Fr8TerminalBase.NET/Infrastructure/HubAuthenticationHeaderSignature.cs +++ b/Fr8TerminalBase.NET/Infrastructure/HubAuthenticationHeaderSignature.cs @@ -8,14 +8,14 @@ namespace Fr8.TerminalBase.Infrastructure public class HubAuthenticationHeaderSignature : IRequestSignature { private readonly string _fr8Token; - public HubAuthenticationHeaderSignature(string token, string userId) + public HubAuthenticationHeaderSignature(string token) { - _fr8Token = $"key={token}" + (string.IsNullOrEmpty(userId) ? "" : $", user={userId}"); + _fr8Token = $"FR8 terminal_key={token}"; } public void SignRequest(HttpRequestMessage request) { - request.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(), $"FR8-TOKEN {_fr8Token}"); + request.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(), _fr8Token); } } } \ No newline at end of file diff --git a/Fr8TerminalBase.NET/Services/DefaultHubCommunicator.cs b/Fr8TerminalBase.NET/Services/DefaultHubCommunicator.cs index 5465822a21..4a37a4a483 100644 --- a/Fr8TerminalBase.NET/Services/DefaultHubCommunicator.cs +++ b/Fr8TerminalBase.NET/Services/DefaultHubCommunicator.cs @@ -27,14 +27,12 @@ public class DefaultHubCommunicator : IHubCommunicator private readonly string _apiUrl; private string _userId; protected string TerminalToken { get; set; } - public string UserId => _userId; - public DefaultHubCommunicator(IRestfulServiceClient restfulServiceClient, string apiUrl, string token, string userId) + public DefaultHubCommunicator(IRestfulServiceClient restfulServiceClient, string apiUrl, string token) { TerminalToken = token; _restfulServiceClient = restfulServiceClient; _apiUrl = apiUrl?.TrimEnd('/', '\\'); - _userId = userId; } public async Task LoadPlan(PlanDTO planContents) diff --git a/Fr8TerminalBase.NET/Services/HubDiscoveryService.cs b/Fr8TerminalBase.NET/Services/HubDiscoveryService.cs index 59462b99cc..407321ac89 100644 --- a/Fr8TerminalBase.NET/Services/HubDiscoveryService.cs +++ b/Fr8TerminalBase.NET/Services/HubDiscoveryService.cs @@ -79,8 +79,8 @@ public async Task GetHubCommunicator(string hubUrl) } var secret = await setSecretTask.Task; - var restfulServiceClient = _restfulServiceClientFactory.Create(new HubAuthenticationHeaderSignature(secret, null)); - return new DefaultHubCommunicator(restfulServiceClient, string.Concat(hubUrl, _apiSuffix), secret, null); + var restfulServiceClient = _restfulServiceClientFactory.Create(new HubAuthenticationHeaderSignature(secret)); + return new DefaultHubCommunicator(restfulServiceClient, string.Concat(hubUrl, _apiSuffix), secret); } /**********************************************************************************/ diff --git a/Hub/Infrastructure/Fr8Identity.cs b/Hub/Infrastructure/Fr8Identity.cs index 4c4d066f84..bd50c2ccb7 100644 --- a/Hub/Infrastructure/Fr8Identity.cs +++ b/Hub/Infrastructure/Fr8Identity.cs @@ -4,10 +4,9 @@ namespace Hub.Infrastructure { public sealed class Fr8Identity : ClaimsIdentity { - public Fr8Identity(string name, string userId) : base("hmac") + public Fr8Identity(string terminalKey) : base("FR8") { - AddClaim(new Claim(ClaimTypes.Name, name)); - AddClaim(new Claim(ClaimTypes.NameIdentifier, userId)); + AddClaim(new Claim("TerminalKey", terminalKey)); } } } diff --git a/Hub/Infrastructure/Fr8Principal.cs b/Hub/Infrastructure/Fr8Principal.cs index 447cbeadf4..6e5c393a4f 100644 --- a/Hub/Infrastructure/Fr8Principal.cs +++ b/Hub/Infrastructure/Fr8Principal.cs @@ -4,11 +4,11 @@ namespace Hub.Infrastructure { public class Fr8Principal : GenericPrincipal { - private string TerminalId { get; set; } + private string TerminalKey { get; set; } - public Fr8Principal(string terminalId, IIdentity identity, string[] roles = null) : base(identity, roles) + public Fr8Principal(string terminalKey, IIdentity identity, string[] roles = null) : base(identity, roles) { - TerminalId = terminalId; + TerminalKey = terminalKey; } } } \ No newline at end of file diff --git a/Hub/Interfaces/ITerminal.cs b/Hub/Interfaces/ITerminal.cs index a02a64d375..9cc9c8bbf6 100644 --- a/Hub/Interfaces/ITerminal.cs +++ b/Hub/Interfaces/ITerminal.cs @@ -14,8 +14,8 @@ public interface ITerminal TerminalDO GetByKey(Guid terminalId); TerminalDO GetByNameAndVersion(string name, string version); TerminalDO RegisterOrUpdate(TerminalDO terminalDo, bool isDiscovery); - Dictionary GetRequestHeaders(TerminalDO terminal, string userId); - Task GetByToken(string token); + Dictionary GetRequestHeaders(TerminalDO terminal); + Task GetByKey(string key); Task> GetSolutionDocumentations(string terminalName); } } \ No newline at end of file diff --git a/Hub/Managers/APIManagers/Transmitters/Terminal/TerminalTransmitter.cs b/Hub/Managers/APIManagers/Transmitters/Terminal/TerminalTransmitter.cs index a8a2d7c5ec..b2ed5e0d71 100644 --- a/Hub/Managers/APIManagers/Transmitters/Terminal/TerminalTransmitter.cs +++ b/Hub/Managers/APIManagers/Transmitters/Terminal/TerminalTransmitter.cs @@ -83,7 +83,7 @@ public async Task CallActivityAsync( } requestUri = new Uri(new Uri(terminal.Endpoint), requestUri); - return await PostAsync(requestUri, dataDTO, correlationId, _terminalService.GetRequestHeaders(terminal, dataDTO.ActivityDTO.AuthToken.UserId)); + return await PostAsync(requestUri, dataDTO, correlationId, _terminalService.GetRequestHeaders(terminal)); } } } \ No newline at end of file diff --git a/Hub/Services/Terminal.cs b/Hub/Services/Terminal.cs index b1520b84a7..fc023ab1ca 100644 --- a/Hub/Services/Terminal.cs +++ b/Hub/Services/Terminal.cs @@ -178,7 +178,7 @@ public TerminalDO RegisterOrUpdate(TerminalDO terminalDo, bool isUserInitiated) } } - public Dictionary GetRequestHeaders(TerminalDO terminal, string userId) + public Dictionary GetRequestHeaders(TerminalDO terminal) { Initialize(); @@ -192,9 +192,8 @@ public Dictionary GetRequestHeaders(TerminalDO terminal, string return new Dictionary { - {"Fr8HubCallbackSecret", terminal.Secret}, - {"Fr8HubCallBackUrl", _serverUrl}, - {"Fr8UserId", userId } + {"TerminalKey", terminal.Secret}, + {"CurrentHubUrl", _serverUrl} }; } @@ -259,13 +258,13 @@ public async Task> GetSolutionDocumentations(stri return solutionPages; } - public async Task GetByToken(string token) + public async Task GetByKey(string key) { Initialize(); lock (_terminals) { - return _terminals.Values.FirstOrDefault(t => t.Secret == token); + return _terminals.Values.FirstOrDefault(t => t.Secret == key); } } diff --git a/Hub/StructureMap/StructureMapBootStrapper.cs b/Hub/StructureMap/StructureMapBootStrapper.cs index 8fb373fd9c..8f6446031c 100644 --- a/Hub/StructureMap/StructureMapBootStrapper.cs +++ b/Hub/StructureMap/StructureMapBootStrapper.cs @@ -250,14 +250,14 @@ public TerminalServiceForTests(IConfigRepository configRepository, ISecurityServ _terminal = new Terminal(configRepository, securityServices); } - public Dictionary GetRequestHeaders(TerminalDO terminal, string userId) + public Dictionary GetRequestHeaders(TerminalDO terminal) { return new Dictionary(); } - public Task GetByToken(string token) + public Task GetByKey(string key) { - return _terminal.GetByToken(token); + return _terminal.GetByKey(key); } public IEnumerable GetAll() diff --git a/HubWeb.csproj b/HubWeb.csproj index 58eed8434a..bd60ec3c00 100644 --- a/HubWeb.csproj +++ b/HubWeb.csproj @@ -457,7 +457,6 @@ - diff --git a/Infrastructure_HubWeb/Fr8PlanDirectoryAuthenticationAttribute.cs b/Infrastructure_HubWeb/Fr8PlanDirectoryAuthenticationAttribute.cs deleted file mode 100644 index e6971cb3b4..0000000000 --- a/Infrastructure_HubWeb/Fr8PlanDirectoryAuthenticationAttribute.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading; -using System.Threading.Tasks; -using System.Web; -using System.Web.Http; -using System.Web.Http.Filters; -using Fr8.Infrastructure.Utilities.Configuration; -using Hub.Infrastructure; -using Hub.Interfaces; -using StructureMap; - -namespace HubWeb.Infrastructure_HubWeb -{ - /// - /// This attribute checks for Fr8-Token authentication header in requests - /// authenticates terminals to hub - /// - public class Fr8PlanDirectoryAuthenticationAttribute : Attribute, IAuthenticationFilter - { - protected void Success(HttpAuthenticationContext context, string terminalToken, string userId) - { - var identity = new Fr8Identity("terminal-" + terminalToken, userId); - var principle = new Fr8Principal(terminalToken, identity, new[] { "Terminal" }); - Thread.CurrentPrincipal = principle; - context.Principal = principle; - if (HttpContext.Current != null) - { - HttpContext.Current.User = principle; - } - - } - - private Dictionary ExtractTokenParts(HttpRequestMessage request) - { - if (request.Headers.Authorization == null || !request.Headers.Authorization.Scheme.Equals("FR8-PD", StringComparison.OrdinalIgnoreCase) - || string.IsNullOrEmpty(request.Headers.Authorization.Parameter)) - { - return null; - } - - string tokenString = request.Headers.Authorization.Parameter; - string[] authenticationParameters = tokenString.Split(','); - var headerParams = new Dictionary(); - foreach (var authenticationParameter in authenticationParameters) - { - var splittedParam = authenticationParameter.Split('='); - if (splittedParam.Length != 2) - { - return null; - } - headerParams.Add(splittedParam[0].Trim(), splittedParam[1].Trim()); - } - return headerParams; - } - - public bool AllowMultiple => false; - - /// - /// Authenticates terminals by checking fr8 terminal authentication header - /// - /// - /// - /// - public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) - { - var request = context.Request; - var headerParams = ExtractTokenParts(request); - if (headerParams == null) - { - return; - } - - string terminalToken = headerParams.FirstOrDefault(x => x.Key == "key").Value; - var userId = headerParams.FirstOrDefault(x => x.Key == "user").Value; - //unknown terminal - if (terminalToken == null) - { - return; - } - - //we should check if this user allowed this terminal somewhere around here - if (string.IsNullOrEmpty(userId)) - { - return; - } - - if (CloudConfigurationManager.GetSetting("PlanDirectorySecret") != terminalToken) - { - return; - } - - Success(context, terminalToken, userId); - } - - public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) - { - context.Result = new ResultWithChallenge(context.Result); - return Task.FromResult(0); - } - - protected class ResultWithChallenge : IHttpActionResult - { - private readonly IHttpActionResult next; - - public ResultWithChallenge(IHttpActionResult next) - { - this.next = next; - } - - public async Task ExecuteAsync(CancellationToken cancellationToken) - { - var response = await next.ExecuteAsync(cancellationToken); - - if (response.StatusCode == HttpStatusCode.Unauthorized) - { - response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("FR8-PD")); - } - - return response; - } - } - } -} \ No newline at end of file diff --git a/Infrastructure_HubWeb/Fr8TerminalAuthenticationAttribute.cs b/Infrastructure_HubWeb/Fr8TerminalAuthenticationAttribute.cs index 296145e2fc..36414ff8b5 100644 --- a/Infrastructure_HubWeb/Fr8TerminalAuthenticationAttribute.cs +++ b/Infrastructure_HubWeb/Fr8TerminalAuthenticationAttribute.cs @@ -22,34 +22,30 @@ namespace HubWeb.Infrastructure_HubWeb public class Fr8TerminalAuthenticationAttribute : Attribute, IAuthenticationFilter { private readonly ITerminal _terminal; - private readonly bool _allowRequestsWithoutUser; - public Fr8TerminalAuthenticationAttribute(bool allowRequestsWithoutUser = false) + public Fr8TerminalAuthenticationAttribute() { _terminal = ObjectFactory.GetInstance(); - _allowRequestsWithoutUser = allowRequestsWithoutUser; } - protected void Success(HttpAuthenticationContext context, string terminalToken, string userId) + protected void Success(HttpAuthenticationContext context, string terminalKey) { - var identity = new Fr8Identity("terminal-" + terminalToken, userId); - var principle = new Fr8Principal(terminalToken, identity, new[] { "Terminal" }); + var identity = new Fr8Identity(terminalKey); + var principle = new Fr8Principal(terminalKey, identity, new[] { "Terminal" }); Thread.CurrentPrincipal = principle; context.Principal = principle; if (HttpContext.Current != null) { HttpContext.Current.User = principle; } - } private Dictionary ExtractTokenParts(HttpRequestMessage request) { - if (request.Headers.Authorization == null || !request.Headers.Authorization.Scheme.Equals("FR8-TOKEN", StringComparison.OrdinalIgnoreCase) + if (request.Headers.Authorization == null || !request.Headers.Authorization.Scheme.Equals("FR8", StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(request.Headers.Authorization.Parameter)) { return null; } - string tokenString = request.Headers.Authorization.Parameter; string[] authenticationParameters = tokenString.Split(','); var headerParams = new Dictionary(); @@ -78,41 +74,18 @@ public async Task AuthenticateAsync(HttpAuthenticationContext context, Cancellat var request = context.Request; var headerParams = ExtractTokenParts(request); - if (headerParams == null) - { - return; - } - - string terminalToken = headerParams.FirstOrDefault(x => x.Key == "key").Value; - var userId = headerParams.FirstOrDefault(x => x.Key == "user").Value; + string terminalKey = headerParams?.FirstOrDefault(x => x.Key == "terminal_key").Value; //unknown terminal - if (terminalToken == null) + if (terminalKey == null) { return; } - - //we should check if this user allowed this terminal somewhere around here - if (string.IsNullOrEmpty(userId)) - { - if (_allowRequestsWithoutUser) - { - //lets assume our user is the terminal - userId = terminalToken; - } - else - { - return; - } - } - - - var terminal = await _terminal.GetByToken(terminalToken); + var terminal = await _terminal.GetByKey(terminalKey); if (terminal == null) { return; } - - Success(context, terminalToken, userId); + Success(context, terminalKey); } public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) diff --git a/Tests/Fr8.Testing/Integration/BaseHubIntegrationTest.cs b/Tests/Fr8.Testing/Integration/BaseHubIntegrationTest.cs index 647fd2507a..eb2d60139e 100644 --- a/Tests/Fr8.Testing/Integration/BaseHubIntegrationTest.cs +++ b/Tests/Fr8.Testing/Integration/BaseHubIntegrationTest.cs @@ -67,30 +67,29 @@ protected BaseHubIntegrationTest() EmailAssert.InitEmailAssert(TestEmail, hostname, port, useSsl, username, password); } - protected Dictionary GetFr8HubAuthorizationHeader(string terminalName,string terminalVersion, string userId) + protected Dictionary GetFr8HubAuthorizationHeader(string terminalName,string terminalVersion) { using (var uow = ObjectFactory.GetInstance()) { var terminal = uow.TerminalRepository.GetQuery().Single(x => x.Name == terminalName && x.Version == terminalVersion); - var fr8Token = $"key={terminal.Secret}" + (string.IsNullOrEmpty(userId) ? "" : $", user={userId}"); + var fr8Token = $"key={terminal.Secret}"; return new Dictionary { - {System.Net.HttpRequestHeader.Authorization.ToString(), $"FR8-TOKEN {fr8Token}"} + {System.Net.HttpRequestHeader.Authorization.ToString(), $"FR8 {fr8Token}"} }; } } - protected Dictionary GetFr8TerminalAuthorizationHeader(string terminalName, string terminalVersion, string userId) + protected Dictionary GetFr8TerminalAuthorizationHeader(string terminalName, string terminalVersion) { using (var uow = ObjectFactory.GetInstance()) { var terminal = uow.TerminalRepository.GetQuery().Single(x => x.Name == terminalName && x.Version == terminalVersion); return new Dictionary { - {"Fr8HubCallbackSecret", terminal.Secret}, - {"Fr8HubCallBackUrl", ConfigurationManager.AppSettings["DefaultHubUrl"]}, - {"Fr8UserId", userId } + {"TerminalKey", terminal.Secret}, + {"CurrentHubUrl", ConfigurationManager.AppSettings["DefaultHubUrl"]} }; } } diff --git a/Tests/HubTests/Infrastructure/Fr8HubWebHMACAuthenticateAttributeTests.cs b/Tests/HubTests/Infrastructure/Fr8HubWebHMACAuthenticateAttributeTests.cs index 88642b2fcb..0a09aa43a2 100644 --- a/Tests/HubTests/Infrastructure/Fr8HubWebHMACAuthenticateAttributeTests.cs +++ b/Tests/HubTests/Infrastructure/Fr8HubWebHMACAuthenticateAttributeTests.cs @@ -34,7 +34,7 @@ public override void SetUp() _authenticationContext = new HttpAuthenticationContext(context, null); HttpRequestHeaders headers = request.Headers; - AuthenticationHeaderValue authorization = new AuthenticationHeaderValue("FR8-TOKEN", "key=test, user=test"); + AuthenticationHeaderValue authorization = new AuthenticationHeaderValue("FR8", "terminal_key=test"); headers.Authorization = authorization; } @@ -51,7 +51,7 @@ private Fr8TerminalAuthenticationAttribute CreateFilter() public async Task ShouldSetCurrentUser_WithCorrectAuthentication() { var terminalService = new Mock(); - terminalService.Setup(x => x.GetByToken(It.IsAny())).ReturnsAsync(new TerminalDO()); + terminalService.Setup(x => x.GetByKey(It.IsAny())).ReturnsAsync(new TerminalDO()); ObjectFactory.Configure(o => o.For().Use(terminalService.Object)); await CreateFilter().AuthenticateAsync(_authenticationContext, CancellationToken.None); @@ -63,7 +63,7 @@ public async Task ShouldSetCurrentUser_WithCorrectAuthentication() public async Task ShouldntSetCurrentUser_WithInCorrectAuthentication() { HttpRequestHeaders headers = _authenticationContext.Request.Headers; - AuthenticationHeaderValue authorization = new AuthenticationHeaderValue("FR8-TOKEN", "sdasdasd"); + AuthenticationHeaderValue authorization = new AuthenticationHeaderValue("FR8", "sdasdasd"); headers.Authorization = authorization; await CreateFilter().AuthenticateAsync(_authenticationContext, CancellationToken.None); @@ -74,7 +74,7 @@ public async Task ShouldntSetCurrentUser_WithInCorrectAuthentication() public async Task ShouldntSetCurrentUser_WithInvalidTerminalToken() { var terminalService = new Mock(); - terminalService.Setup(x => x.GetByToken(It.IsAny())).ReturnsAsync(null); + terminalService.Setup(x => x.GetByKey(It.IsAny())).ReturnsAsync(null); ObjectFactory.Configure(o => o.For().Use(terminalService.Object)); await CreateFilter().AuthenticateAsync(_authenticationContext, CancellationToken.None); Assert.AreEqual(null, _authenticationContext.Principal); diff --git a/Tests/terminalIntegrationTests/Integration/MonitorTerminalSubmissionPlanTest.cs b/Tests/terminalIntegrationTests/Integration/MonitorTerminalSubmissionPlanTest.cs index e75e25dc2e..770ba30265 100644 --- a/Tests/terminalIntegrationTests/Integration/MonitorTerminalSubmissionPlanTest.cs +++ b/Tests/terminalIntegrationTests/Integration/MonitorTerminalSubmissionPlanTest.cs @@ -90,7 +90,7 @@ public async Task MonitorTerminalSubmissionPlan() //Trigger creating Plan Debug.WriteLine("Trigger creating Plan"); - var terminalAuthenticationHeader = GetFr8TerminalAuthorizationHeader("terminalGoogle", "1", userId); + var terminalAuthenticationHeader = GetFr8TerminalAuthorizationHeader("terminalGoogle", "1"); await RestfulServiceClient.PostAsync(new Uri(googleEventUrl), new { fr8_user_id = userId }, null, terminalAuthenticationHeader); //Reconfiguring plan activities @@ -113,9 +113,9 @@ public async Task MonitorTerminalSubmissionPlan() await RestfulServiceClient.DeleteAsync(new Uri(deleteActivityUrl), null, terminalAuthenticationHeader); } - await ConfigureJira(plan.Activities.FirstOrDefault(a => a.Ordering == 5).Id, userId); - await ConfigureMessage(plan.Activities.FirstOrDefault(a => a.Ordering == 6).Id, userId, guidTestId.ToString()); - await ConfigureSlack(plan.Activities.FirstOrDefault(a => a.Ordering == 7).Id, userId); + await ConfigureJira(plan.Activities.FirstOrDefault(a => a.Ordering == 5).Id); + await ConfigureMessage(plan.Activities.FirstOrDefault(a => a.Ordering == 6).Id, guidTestId.ToString()); + await ConfigureSlack(plan.Activities.FirstOrDefault(a => a.Ordering == 7).Id); //Run plan again after reconfigure Debug.WriteLine("Run plan again after reconfigure"); @@ -282,13 +282,13 @@ private async Task GetPayload(Guid activityId) return Mapper.Map(DTO); } - private async Task ConfigureJira(Guid activityId, string userId) + private async Task ConfigureJira(Guid activityId) { var payloadJira = await GetPayload(activityId); SetDDL(payloadJira, "AvailableProjects", "fr8test"); DeleteSprint(payloadJira); var DTO = Mapper.Map(payloadJira); - await RestfulServiceClient.PostAsync(new Uri(GetHubApiBaseUrl() + "activities/configure"), DTO, null, GetFr8HubAuthorizationHeader("terminalGoogle", "1", userId)); + await RestfulServiceClient.PostAsync(new Uri(GetHubApiBaseUrl() + "activities/configure"), DTO, null, GetFr8HubAuthorizationHeader("terminalGoogle", "1")); } private void DeleteSprint(ActivityPayload payload) @@ -300,7 +300,7 @@ private void DeleteSprint(ActivityPayload payload) crates.Controls.Remove(crates.Controls.Last()); } - private async Task ConfigureSlack(Guid activityId, string userId) + private async Task ConfigureSlack(Guid activityId) { var payloadSlack = await GetPayload(activityId); var slackCrates = payloadSlack.CrateStorage.CrateContentsOfType().First(); @@ -308,17 +308,17 @@ private async Task ConfigureSlack(Guid activityId, string userId) SetDDL(payloadSlack, slackCrates.Controls[0].Name, "#general"); var DTO = Mapper.Map(payloadSlack); - await RestfulServiceClient.PostAsync(new Uri(GetHubApiBaseUrl()+ "activities/save"), DTO, null, GetFr8HubAuthorizationHeader("terminalGoogle", "1", userId)); + await RestfulServiceClient.PostAsync(new Uri(GetHubApiBaseUrl()+ "activities/save"), DTO, null, GetFr8HubAuthorizationHeader("terminalGoogle", "1")); } - private async Task ConfigureMessage(Guid activityId, string userId,string guid) + private async Task ConfigureMessage(Guid activityId,string guid) { var payloadMessage = await GetPayload(activityId); var messageCrates = payloadMessage.CrateStorage.CrateContentsOfType().First(); var bodyTextBox = (BuildMessageAppender)messageCrates.FindByName("Body"); bodyTextBox.Value = "testing terminal submission " + guid; var DTO = Mapper.Map(payloadMessage); - await RestfulServiceClient.PostAsync(new Uri(GetHubApiBaseUrl()+ "activities/configure"), DTO, null, GetFr8HubAuthorizationHeader("terminalGoogle", "1", userId)); + await RestfulServiceClient.PostAsync(new Uri(GetHubApiBaseUrl()+ "activities/configure"), DTO, null, GetFr8HubAuthorizationHeader("terminalGoogle", "1")); } private void SetDDL(ActivityPayload payload, string name, string key) diff --git a/terminalGoogle/Services/GoogleMTSFPlan.cs b/terminalGoogle/Services/GoogleMTSFPlan.cs index b58b1d8cc0..619b5aac95 100644 --- a/terminalGoogle/Services/GoogleMTSFPlan.cs +++ b/terminalGoogle/Services/GoogleMTSFPlan.cs @@ -98,10 +98,10 @@ public async Task CreateAndActivateNewMTSFPlan() var plans = await _hubCommunicator.GetPlansByName("MonitorSubmissionTerminalForm", PlanVisibility.Internal); var tokens = await _hubCommunicator.GetTokens(); - googleTokens = tokens.Where(t => t.Name == "terminalGoogle").FirstOrDefault(); - atlassianTokens = tokens.Where(t => t.Name == "terminalAtlassian").FirstOrDefault(); - slackTokens = tokens.Where(t => t.Name == "terminalSlack").FirstOrDefault(); - if (plans.Count() == 0) + googleTokens = tokens.FirstOrDefault(t => t.Name == "terminalGoogle"); + atlassianTokens = tokens.FirstOrDefault(t => t.Name == "terminalAtlassian"); + slackTokens = tokens.FirstOrDefault(t => t.Name == "terminalSlack"); + if (!plans.Any()) { await ConfigureAndRunPlan(); }