private ClaimTransformationsLogic ClaimTransformationsLogicInstance() { var routeBinding = new RouteBinding(); var mockHttpContextAccessor = HttpContextAccessorHelper.MockObject(routeBinding); var telemetryScopedLogger = TelemetryLoggerHelper.ScopedLoggerObject(mockHttpContextAccessor); return(new ClaimTransformationsLogic(telemetryScopedLogger, mockHttpContextAccessor)); }
private async Task <RouteBinding> GetRouteDataAsync(TelemetryScopedLogger scopedLogger, Track.IdKey trackIdKey, string partyNameAndBinding = null) { var track = await GetTrackAsync(tenantRepository, trackIdKey); var routeBinding = new RouteBinding { RouteUrl = $"{trackIdKey.TenantName}{$"/{trackIdKey.TrackName}{(!partyNameAndBinding.IsNullOrWhiteSpace() ? $"/{partyNameAndBinding}" : string.Empty)}"}", TenantName = trackIdKey.TenantName, TrackName = trackIdKey.TrackName, PartyNameAndBinding = partyNameAndBinding, PrimaryKey = track.PrimaryKey, SecondaryKey = track.SecondaryKey, ClaimMappings = track.ClaimMappings, Resources = track.Resources, SequenceLifetime = track.SequenceLifetime, PasswordLength = track.PasswordLength, CheckPasswordComplexity = track.CheckPasswordComplexity.Value, CheckPasswordRisk = track.CheckPasswordRisk.Value, AllowIframeOnDomains = track.AllowIframeOnDomains }; if (!partyNameAndBinding.IsNullOrWhiteSpace()) { var partyNameBindingMatch = partyNameBindingRegex.Match(partyNameAndBinding); if (!partyNameBindingMatch.Success) { throw new ArgumentException($"Invalid party name and binding match. PartyNameAndBinding '{partyNameAndBinding}'"); } if (partyNameBindingMatch.Groups["upparty"].Success) { routeBinding.UpParty = await GetUpPartyAsync(tenantRepository, trackIdKey, partyNameBindingMatch.Groups["upparty"]); } else if (partyNameBindingMatch.Groups["downparty"].Success) { routeBinding.DownParty = await GetDownPartyAsync(tenantRepository, trackIdKey, partyNameBindingMatch.Groups["downparty"]); if (routeBinding.DownParty.AllowUpParties?.Count() >= 1) { if (partyNameBindingMatch.Groups["toupparty"].Success) { routeBinding.ToUpParties = await GetAllowedToUpPartyIds(scopedLogger, trackIdKey, partyNameBindingMatch.Groups["toupparty"], routeBinding.DownParty); } else { routeBinding.ToUpParties = routeBinding.DownParty.AllowUpParties.Take(1).ToList(); } } } else { throw new ArgumentException($"Invalid party name and binding group match. PartyNameAndBinding '{partyNameAndBinding}'"); } } return(routeBinding); }
private IEnumerable <ClaimMap> GetMappings(RouteBinding RouteBinding) { var mappings = GetDefaultMappings(); if (RouteBinding.ClaimMappings != null && RouteBinding.ClaimMappings.Mappings?.Count() > 0) { mappings = mappings.ConcatOnce(RouteBinding.ClaimMappings.Mappings, (f, s) => s.JwtClaim == f.JwtClaim); } mappings = mappings.ConcatOnce(GetDefaultChangeableMappings(), (f, s) => s.JwtClaim == f.JwtClaim); return(mappings); }
private async Task <RouteBinding> GetRouteDataAsync(TelemetryScopedLogger scopedLogger, IServiceProvider requestServices, Track.IdKey trackIdKey, string partyNameAndBinding, bool acceptUnknownParty) { var track = await GetTrackAsync(tenantRepository, trackIdKey); var routeBinding = new RouteBinding { RouteUrl = $"{trackIdKey.TenantName}/{trackIdKey.TrackName}{(!partyNameAndBinding.IsNullOrWhiteSpace() ? $"/{partyNameAndBinding}" : string.Empty)}", TenantName = trackIdKey.TenantName, TrackName = trackIdKey.TrackName, Resources = track.Resources, }; return(await PostRouteDataAsync(scopedLogger, requestServices, trackIdKey, track, routeBinding, partyNameAndBinding, acceptUnknownParty)); }
private TMessage Get(bool delete) { if (RouteBinding.TenantName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TenantName), RouteBinding.GetTypeName()); } if (RouteBinding.TrackName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TrackName), RouteBinding.GetTypeName()); } if (RouteBinding.UpParty == null) { throw new ArgumentNullException(nameof(RouteBinding.UpParty), RouteBinding.GetTypeName()); } logger.ScopeTrace($"Get Cookie '{typeof(TMessage).Name}', Route '{RouteBinding.Route}', Delete '{delete}'."); var cookie = httpContextAccessor.HttpContext.Request.Cookies[CookieName()]; if (!cookie.IsNullOrWhiteSpace()) { try { var envelope = CookieEnvelope <TMessage> .FromCookieString(CreateProtector(), cookie); if (delete) { logger.ScopeTrace($"Delete Cookie, '{typeof(TMessage).Name}', Route '{RouteBinding.Route}'."); DeleteByName(CookieName()); } return(envelope.Message); } catch (CryptographicException ex) { logger.Warning(ex, $"Unable to Unprotect Cookie '{typeof(TMessage).Name}', deleting cookie."); DeleteByName(CookieName()); return(null); } catch (Exception ex) { throw new Exception($"Unable to Read Cookie '{typeof(TMessage).Name}'.", ex); } } else { return(null); } }
public static IHttpContextAccessor MockObject(RouteBinding routeBinding) { var items = new Dictionary <object, object>(); var cookies = new Dictionary <string, string>(); var mockHttpContext = new Mock <HttpContext>(); mockHttpContext.SetupProperty(c => c.Items, items); var routeData = new RouteData(); routeBinding.TenantName = routeBinding.TenantName ?? "testtenant"; routeBinding.TrackName = routeBinding.TrackName ?? "testtrack"; routeData.DataTokens.Add(Constants.Routes.RouteBindingKey, routeBinding); routeData.DataTokens.Add(Constants.Routes.SequenceStringKey, "1234asdf1234"); var mockRoutingFeature = new Mock <IRoutingFeature>(); mockRoutingFeature.Setup(rf => rf.RouteData).Returns(routeData); mockHttpContext.Setup(c => c.Features[typeof(IRoutingFeature)]).Returns(mockRoutingFeature.Object); var mockHttpRequest = new Mock <HttpRequest>(); mockHttpContext.Setup(c => c.Request).Returns(mockHttpRequest.Object); mockHttpRequest.Setup(r => r.Scheme).Returns("https"); mockHttpRequest.Setup(r => r.Host).Returns(new HostString("foxidstest.test")); mockHttpRequest.Setup(r => r.Path).Returns(new PathString("/sometenant/sometrack/(login)/login/CreateUser/_CfDJ8JOhOhitapNOk0YwRh-azW-uLvIVSVeabekwNFrDKn836MraokC1PKD-7HatR09hT5CwAjOV7L5QkNyBP11yExMbePpBDAg8ohpk7TxflZ-EOV7Ib6T4rRwYqzORMrNF9zty3y0wsgmgSYP9njaPvMpfA3W3sKZIWq5S_IKdbKNs")); var mockRequestCookieCollection = new Mock <IRequestCookieCollection>(); mockHttpRequest.Setup(r => r.Cookies).Returns(mockRequestCookieCollection.Object); mockRequestCookieCollection.Setup(rc => rc[It.IsAny <string>()]).Returns((string key) => cookies[key]); mockRequestCookieCollection.Setup(rc => rc.Keys).Returns(cookies.Keys); var mockHttpResponse = new Mock <HttpResponse>(); mockHttpContext.Setup(c => c.Response).Returns(mockHttpResponse.Object); var mockResponseCookies = new Mock <IResponseCookies>(); mockHttpResponse.Setup(r => r.Cookies).Returns(mockResponseCookies.Object); mockResponseCookies.Setup(rc => rc.Append(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CookieOptions>())).Callback((string key, string value, CookieOptions options) => cookies[key] = value); var mockHttpContextAccessor = new Mock <IHttpContextAccessor>(); mockHttpContextAccessor.Setup(ca => ca.HttpContext).Returns(mockHttpContext.Object); return(mockHttpContextAccessor.Object); }
public IHttpActionResult Put(int?id, [FromBody] RouteBinding routeBinding) { if (routeBinding == null) { return(BadRequest("No route specified")); } if (!id.HasValue) { return(BadRequest("No id specified")); } var userId = User.Identity.GetUserId(); using (var db = ApplicationDbContext.Create()) { var user = db.Users.Single(x => x.Id == userId); if (userId != user.Id) { return(BadRequest("Invalid user")); } var routeToUpdate = db.Routes.SingleOrDefault(x => x.Id == id.Value); if (routeToUpdate == null) { return(BadRequest("Route does not exist")); } var route = db.Routes.Attach(routeToUpdate); var entry = db.Entry(routeToUpdate); route.Name = routeBinding.name; route.Origin = routeBinding.origin; route.Destination = routeBinding.destination; route.IsLoopRoute = routeBinding.is_loop_route; route.Distance = routeBinding.distance; entry.State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return(Ok("Route updated")); } }
public async Task <SessionCookie> DeleteSessionAsync(RouteBinding RouteBinding) { logger.ScopeTrace($"Delete session, Route '{RouteBinding.Route}'."); var session = await sessionCookieRepository.GetAsync(); if (session != null) { await sessionCookieRepository.DeleteAsync(); logger.ScopeTrace($"Session deleted, Session id '{session.SessionId}'."); return(session); } else { logger.ScopeTrace("Session do not exists."); return(null); } }
private async Task <string> CreateExternalKeyAsync(Track mTrack) { var certificateClient = new CertificateClient(new Uri(settings.KeyVault.EndpointUri), tokenCredential); var externalName = $"{RouteBinding.TenantNameDashTrackName}-{Guid.NewGuid()}"; var certificatePolicy = new CertificatePolicy("self", RouteBinding.GetCertificateSubject()) { Exportable = false, ValidityInMonths = mTrack.KeyExternalValidityInMonths }; certificatePolicy.LifetimeActions.Add(new LifetimeAction(CertificatePolicyAction.AutoRenew) { DaysBeforeExpiry = mTrack.KeyExternalAutoRenewDaysBeforeExpiry }); await certificateClient.StartCreateCertificateAsync(externalName, certificatePolicy); return(externalName); }
private void Save(TMessage message, DateTimeOffset?persistentCookieExpires) { if (RouteBinding.TenantName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TenantName), RouteBinding.GetTypeName()); } if (RouteBinding.TrackName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TrackName), RouteBinding.GetTypeName()); } if (RouteBinding.UpParty == null) { throw new ArgumentNullException(nameof(RouteBinding.UpParty), RouteBinding.GetTypeName()); } if (message == null) { new ArgumentNullException(nameof(message)); } logger.ScopeTrace($"Save Cookie '{typeof(TMessage).Name}', Route '{RouteBinding.Route}'."); var cookieOptions = new CookieOptions { Secure = true, HttpOnly = true, SameSite = SameSiteMode.Lax, IsEssential = true, Path = GetPath(), }; if (persistentCookieExpires != null) { cookieOptions.Expires = persistentCookieExpires; } httpContextAccessor.HttpContext.Response.Cookies.Append( CookieName(), new CookieEnvelope <TMessage> { Message = message, }.ToCookieString(CreateProtector()), cookieOptions); }
private void CheckRouteBinding() { if (RouteBinding == null) { new ArgumentNullException(nameof(RouteBinding)); } if (RouteBinding.TenantName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TenantName), RouteBinding.GetTypeName()); } if (RouteBinding.TrackName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TrackName), RouteBinding.GetTypeName()); } if (RouteBinding.UpParty == null) { throw new ArgumentNullException(nameof(RouteBinding.UpParty), RouteBinding.GetTypeName()); } }
public IHttpActionResult Post([FromBody] RouteBinding routeBinding) { if (routeBinding == null) { return(BadRequest("No route specified")); } var userId = User.Identity.GetUserId(); using (var db = ApplicationDbContext.Create()) { var user = db.Users.Single(x => x.Id == userId); if (user.Id != userId) { return(BadRequest("Invalid user")); } var route = new Route() { Name = routeBinding.name, Origin = routeBinding.origin, Destination = routeBinding.destination, Distance = routeBinding.distance, IsLoopRoute = routeBinding.is_loop_route, User = user }; db.Routes.Add(route); db.SaveChanges(); return(Created("Routes", new RouteResultModel() { id = route.Id, name = route.Name, origin = route.Origin, destination = route.Destination, is_loop_route = route.IsLoopRoute, distance = route.Distance })); } }
private AccountLogic AccountLogicInstance(int passwordLength = 8, bool checkPasswordComplexity = true, bool checkPasswordRisk = true) { var routeBinding = new RouteBinding { PasswordLength = passwordLength, CheckPasswordComplexity = checkPasswordComplexity, CheckPasswordRisk = checkPasswordRisk, }; var mockHttpContextAccessor = HttpContextAccessorHelper.MockObject(routeBinding); var telemetryScopedLogger = TelemetryLoggerHelper.ScopedLoggerObject(mockHttpContextAccessor); var fakeTenantRepository = new FakeTenantRepository(); var fakeMasterRepository = new FakeMasterRepository(); var secretHashLogic = new SecretHashLogic(mockHttpContextAccessor); var accountLogic = new AccountLogic(telemetryScopedLogger, fakeTenantRepository, fakeMasterRepository, secretHashLogic, mockHttpContextAccessor); return(accountLogic); }
public string GetSupportedCulture(IEnumerable <string> cultures, RouteBinding routeBinding = null) { var resourceEnvelope = embeddedResourceLogic.GetResourceEnvelope(); routeBinding = routeBinding ?? RouteBinding; var supportedCultures = resourceEnvelope.SupportedCultures; if (routeBinding.Resources?.Count > 0) { var trackSupportedCultures = routeBinding.Resources.SelectMany(r => r.Items.GroupBy(ig => ig.Culture)).Select(rk => rk.Key); supportedCultures = supportedCultures.ConcatOnce(trackSupportedCultures); } foreach (var culture in cultures.Take(maximumCultureNamesToTry)) { if (supportedCultures.Where(c => c.Equals(culture, StringComparison.InvariantCultureIgnoreCase) || c.StartsWith($"{culture}_", StringComparison.InvariantCultureIgnoreCase)).Any()) { return(culture); } } return(resourceEnvelope.SupportedCultures.First()); }
/// <summary> /// Creates an event consumer that begins consuming events from the specified URI. /// Events are delivered to the event handler. The disposable object that is /// returned is used to define the lifetime associated with the subscription. /// </summary> /// <param name="uri">The URI.</param> /// <param name="eventHandler">The event handler.</param> /// <returns></returns> public IDisposable Subscribe(Uri uri, EventHandler <UpdateEventArgs> eventHandler) { var pathParts = uri.Segments; var exchangePath = pathParts[1].TrimEnd('/'); var routingKey = pathParts[2]; // find the exchange path binding ExchangePathBinding exchangePathBinding; if (!_exchangePathBindingTable.TryGetValue(exchangePath, out exchangePathBinding)) { exchangePathBinding = new ExchangePathBinding(); exchangePathBinding.Connection = _connectionFactory.CreateConnection(); exchangePathBinding.Channel = exchangePathBinding.Connection.CreateModel(); _exchangePathBindingTable[exchangePath] = exchangePathBinding; } // find a queue for this routingKey RouteBinding routeBinding; if (!exchangePathBinding.RoutingKeyTable.TryGetValue(routingKey, out routeBinding)) { routeBinding = new RouteBinding(); routeBinding.Queue = exchangePathBinding.Channel.QueueDeclare(); routeBinding.Consumer = new EventingBasicConsumer(); routeBinding.Consumer.Received += routeBinding.HandleEvent; exchangePathBinding.RoutingKeyTable[routingKey] = routeBinding; exchangePathBinding.Channel.QueueBind(routeBinding.Queue, exchangePath, routingKey); exchangePathBinding.Channel.BasicConsume(routeBinding.Queue, true, routeBinding.Consumer); } routeBinding.Events += eventHandler; return(new TrackedDisposable( () => routeBinding.Events -= eventHandler)); }
private void Delete() { if (RouteBinding == null) { new ArgumentNullException(nameof(RouteBinding)); } if (RouteBinding.TenantName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TenantName), RouteBinding.GetTypeName()); } if (RouteBinding.TrackName.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(RouteBinding.TrackName), RouteBinding.GetTypeName()); } if (RouteBinding.UpParty == null) { throw new ArgumentNullException(nameof(RouteBinding.UpParty), RouteBinding.GetTypeName()); } logger.ScopeTrace($"Delete Cookie '{typeof(TMessage).Name}', Route '{RouteBinding.Route}'."); DeleteByName(CookieName()); }
private async Task <RouteBinding> GetRouteDataAsync(TelemetryScopedLogger scopedLogger, IServiceProvider requestServices, Track.IdKey trackIdKey, bool hasCustomDomain, string customDomain, string partyNameAndBinding, bool acceptUnknownParty) { if (hasCustomDomain) { var tenantCacheLogic = requestServices.GetService <TenantCacheLogic>(); trackIdKey.TenantName = await tenantCacheLogic.GetTenantNameByCustomDomain(customDomain); } var track = await GetTrackAsync(trackIdKey, hasCustomDomain); scopedLogger.SetScopeProperty(Constants.Logs.TenantName, trackIdKey.TenantName); scopedLogger.SetScopeProperty(Constants.Logs.TrackName, trackIdKey.TrackName); var routeBinding = new RouteBinding { HasCustomDomain = hasCustomDomain, RouteUrl = $"{(!hasCustomDomain ? $"{trackIdKey.TenantName}/" : string.Empty)}{trackIdKey.TrackName}{(!partyNameAndBinding.IsNullOrWhiteSpace() ? $"/{partyNameAndBinding}" : string.Empty)}", TenantName = trackIdKey.TenantName, TrackName = trackIdKey.TrackName, Resources = track.Resources, }; return(await PostRouteDataAsync(scopedLogger, requestServices, trackIdKey, track, routeBinding, partyNameAndBinding, acceptUnknownParty)); }
public async Task <ActionResult <Api.TrackKey> > PutTrackKeyType([FromBody] Api.TrackKey trackKey) { try { if (!await ModelState.TryValidateObjectAsync(trackKey)) { return(BadRequest(ModelState)); } var mTrackKey = mapper.Map <TrackKey>(trackKey); var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey { TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName }); if (mTrack.Key.Type != mTrackKey.Type) { switch (mTrackKey.Type) { case TrackKeyType.Contained: mTrack.Key.Type = mTrackKey.Type; var certificate = await RouteBinding.CreateSelfSignedCertificateBySubjectAsync(); mTrack.Key.Keys = new List <TrackKeyItem> { new TrackKeyItem { Key = await certificate.ToFTJsonWebKeyAsync(true) } }; if (!mTrack.Key.ExternalName.IsNullOrWhiteSpace()) { await externalKeyLogic.DeleteExternalKeyAsync(mTrack.Key.ExternalName); mTrack.Key.ExternalName = null; } break; case TrackKeyType.KeyVaultRenewSelfSigned: mTrack.Key.Type = mTrackKey.Type; mTrack.Key.Keys = null; mTrack.Key.ExternalName = await externalKeyLogic.CreateExternalKeyAsync(mTrack); break; case TrackKeyType.KeyVaultUpload: default: throw new Exception($"Track key type not supported '{mTrackKey.Type}'."); } await tenantRepository.UpdateAsync(mTrack); } return(Ok(mapper.Map <Api.TrackKey>(mTrack.Key))); } catch (CosmosDataException ex) { if (ex.StatusCode == HttpStatusCode.NotFound) { logger.Warning(ex, $"NotFound, Update '{typeof(Api.TrackKey).Name}' type by track name '{RouteBinding.TrackName}'."); return(NotFound(typeof(Api.TrackKey).Name, RouteBinding.TrackName)); } throw; } }
public static string GetCertificateSubject(this RouteBinding routeBinding) { return((routeBinding.TenantName, routeBinding.TrackName).GetCertificateSubject()); }
public async Task <ActionResult <Api.TrackKeyItemsContained> > PutTrackKeyContained([FromBody] Api.TrackKeyItemContainedRequest trackKeyRequest) { try { if (!await ModelState.TryValidateObjectAsync(trackKeyRequest)) { return(BadRequest(ModelState)); } var mTrackKey = mapper.Map <TrackKeyItem>(trackKeyRequest); if (!trackKeyRequest.CreateSelfSigned) { try { if (!mTrackKey.Key.HasPrivateKey()) { throw new ValidationException("Private key is required."); } } catch (ValidationException vex) { logger.Warning(vex); ModelState.TryAddModelError(nameof(trackKeyRequest.Key), vex.Message); return(BadRequest(ModelState)); } } var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey { TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName }); try { if (mTrack.Key.Type != TrackKeyType.Contained) { throw new ValidationException($"Only {Api.TrackKeyType.Contained} keys is supported."); } } catch (ValidationException vex) { logger.Warning(vex); ModelState.TryAddModelError(string.Empty, vex.Message); return(BadRequest(ModelState)); } if (trackKeyRequest.CreateSelfSigned) { var certificate = await RouteBinding.CreateSelfSignedCertificateBySubjectAsync(); mTrackKey.Key = await certificate.ToFTJsonWebKeyAsync(true); } if (trackKeyRequest.IsPrimary) { mTrack.Key.Keys[0] = mTrackKey; } else { if (mTrack.Key.Keys.Count > 1) { mTrack.Key.Keys[1] = mTrackKey; } else { mTrack.Key.Keys.Add(mTrackKey); } } await tenantRepository.UpdateAsync(mTrack); return(Ok(mapper.Map <Api.TrackKeyItemsContained>(mTrack.Key))); } catch (CosmosDataException ex) { if (ex.StatusCode == HttpStatusCode.NotFound) { logger.Warning(ex, $"NotFound, Update '{typeof(Api.TrackKeyItemContainedRequest).Name}' contained by track name '{RouteBinding.TrackName}'."); return(NotFound(typeof(Api.TrackKeyItemContainedRequest).Name, RouteBinding.TrackName)); } throw; } }
protected override async ValueTask <RouteBinding> PostRouteDataAsync(TelemetryScopedLogger scopedLogger, IServiceProvider requestServices, Track.IdKey trackIdKey, Track track, RouteBinding routeBinding, string partyNameAndBinding, bool acceptUnknownParty) { routeBinding.PartyNameAndBinding = partyNameAndBinding; routeBinding.Key = await LoadTrackKeyAsync(requestServices, trackIdKey, track); routeBinding.ClaimMappings = track.ClaimMappings; routeBinding.SequenceLifetime = track.SequenceLifetime; routeBinding.MaxFailingLogins = track.MaxFailingLogins; routeBinding.FailingLoginCountLifetime = track.FailingLoginCountLifetime; routeBinding.FailingLoginObservationPeriod = track.FailingLoginObservationPeriod; routeBinding.PasswordLength = track.PasswordLength; routeBinding.CheckPasswordComplexity = track.CheckPasswordComplexity.Value; routeBinding.CheckPasswordRisk = track.CheckPasswordRisk.Value; routeBinding.AllowIframeOnDomains = track.AllowIframeOnDomains; routeBinding.SendEmail = track.SendEmail; if (!partyNameAndBinding.IsNullOrWhiteSpace()) { var partyNameBindingMatch = partyNameBindingRegex.Match(partyNameAndBinding); if (!partyNameBindingMatch.Success) { throw new ArgumentException($"Invalid party name and binding match. PartyNameAndBinding '{partyNameAndBinding}'"); } if (partyNameBindingMatch.Groups["upparty"].Success) { routeBinding.UpParty = await GetUpPartyAsync(tenantRepository, trackIdKey, partyNameBindingMatch.Groups["upparty"]); } else if (partyNameBindingMatch.Groups["downparty"].Success) { routeBinding.DownParty = await GetDownPartyAsync(tenantRepository, trackIdKey, partyNameBindingMatch.Groups["downparty"], acceptUnknownParty); if (routeBinding.DownParty?.AllowUpParties?.Count() >= 1) { if (partyNameBindingMatch.Groups["toupparty"].Success) { routeBinding.ToUpParties = await GetAllowedToUpPartyIds(scopedLogger, trackIdKey, partyNameBindingMatch.Groups["toupparty"], routeBinding.DownParty); } else { routeBinding.ToUpParties = routeBinding.DownParty.AllowUpParties.Take(1).ToList(); routeBinding.DefaultToUpParties = true; } } } else { throw new ArgumentException($"Invalid party name and binding group match. PartyNameAndBinding '{partyNameAndBinding}'"); } } return(routeBinding); }
protected virtual ValueTask <RouteBinding> PostRouteDataAsync(TelemetryScopedLogger scopedLogger, IServiceProvider requestServices, Track.IdKey trackIdKey, Track track, RouteBinding routeBinding, string partyNameAndBinding, bool acceptUnknownParty) => new ValueTask <RouteBinding>(routeBinding);
private string Issuer(RouteBinding RouteBinding) { return(UrlCombine.Combine(HttpContext.GetHost(), RouteBinding.TenantName, RouteBinding.TrackName)); }
/// <summary> /// Creates an event consumer that begins consuming events from the specified URI. /// Events are delivered to the event handler. The disposable object that is /// returned is used to define the lifetime associated with the subscription. /// </summary> /// <param name="uri">The URI.</param> /// <param name="eventHandler">The event handler.</param> /// <returns></returns> public IDisposable Subscribe(Uri uri, EventHandler<UpdateEventArgs> eventHandler) { var pathParts = uri.Segments; var exchangePath = pathParts[1].TrimEnd('/'); var routingKey = pathParts[2]; // find the exchange path binding ExchangePathBinding exchangePathBinding; if (!_exchangePathBindingTable.TryGetValue(exchangePath, out exchangePathBinding)) { exchangePathBinding = new ExchangePathBinding(); exchangePathBinding.Connection = _connectionFactory.CreateConnection(); exchangePathBinding.Channel = exchangePathBinding.Connection.CreateModel(); _exchangePathBindingTable[exchangePath] = exchangePathBinding; } // find a queue for this routingKey RouteBinding routeBinding; if (!exchangePathBinding.RoutingKeyTable.TryGetValue(routingKey, out routeBinding)) { routeBinding = new RouteBinding(); routeBinding.Queue = exchangePathBinding.Channel.QueueDeclare(); routeBinding.Consumer = new EventingBasicConsumer(); routeBinding.Consumer.Received += routeBinding.HandleEvent; exchangePathBinding.RoutingKeyTable[routingKey] = routeBinding; exchangePathBinding.Channel.QueueBind(routeBinding.Queue, exchangePath, routingKey); exchangePathBinding.Channel.BasicConsume(routeBinding.Queue, true, routeBinding.Consumer); } routeBinding.Events += eventHandler; return new TrackedDisposable( () => routeBinding.Events -= eventHandler); }
protected override ValueTask <RouteBinding> PostRouteDataAsync(TelemetryScopedLogger scopedLogger, IServiceProvider requestServices, Track.IdKey trackIdKey, Track track, RouteBinding routeBinding, string partyNameAndBinding, bool acceptUnknownParty) { routeBinding.PasswordLength = track.PasswordLength; routeBinding.CheckPasswordComplexity = track.CheckPasswordComplexity.Value; routeBinding.CheckPasswordRisk = track.CheckPasswordRisk.Value; routeBinding.Logging = track.Logging; return(new ValueTask <RouteBinding>(routeBinding)); }