using BeWo.Data; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Channels; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml; using System.ServiceModel.Dispatcher; using BeWo.Service.Core; using BS.Shared.Extensions; using BeWo.Service.ServiceUtils; using BS.Shared.Attributes; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; namespace BeWo.Service.ServiceBehavior { public class AdminMultitenancyContextInitializer : ICallContextInitializer { public void AfterInvoke(object pCorrelationState) { if (pCorrelationState is MultitenancyOperationContextExt) { OperationContext.Current.Extensions.Remove((MultitenancyOperationContextExt)pCorrelationState); } } public object BeforeInvoke(InstanceContext pInstanceContext, IClientChannel pChannel, Message pMessage) { string lTenant = null; // Hole Interface string lInterface = null; var segments = pChannel.LocalAddress.Uri.Segments; for (int i = 0; i < segments.Length; i++) { var seg = segments[i].Trim('/'); if (seg.EndsWith(".svc")) { lInterface = "I" + seg.Substring(0, seg.Length - 4); } } if (string.IsNullOrWhiteSpace(lInterface)) { throw new ArgumentException($"Zugriff verweigert. Interface unbekannt"); } // Hole Methode string lMethod = pMessage.Properties[WebHttpDispatchOperationSelector.HttpOperationNamePropertyName] as string; if (string.IsNullOrWhiteSpace(lMethod)) { throw new ArgumentException($"Zugriff verweigert. Methode unbekannt"); } // RequireNoTenant var lTemp = ServiceHelper.GetCustomAttribute(lInterface, lMethod); if (lTemp is object) { return null; } // Hole tenant aus Query // Wird erstmal nicht benötigt. Per Header besser // Ungefähr auf einem Level wie Username //if (pMessage.Properties?.Via is Uri uri) //{ // var query = HttpUtility.ParseQueryString(uri.Query); // var tenant = query["tenant"]; // lTenant = tenant; //} // Hole tenant aus Header if (string.IsNullOrWhiteSpace(lTenant)) { var prop = (HttpRequestMessageProperty)pMessage.Properties[HttpRequestMessageProperty.Name]; lTenant = prop?.Headers["tenant"]; } // Wenn kein Tenant gefunden wird, if (string.IsNullOrWhiteSpace(lTenant)) { throw new ArgumentException($"Zugriff verweigert. Tenant (\'{lTenant}\') darf nicht leer sein.", nameof(lTenant)); } var lExt = new MultitenancyOperationContextExt { Tenant = lTenant }; OperationContext.Current.Extensions.Add(lExt); return lExt; } } }