2replies
-
eric. tremblay
You can get the WindowsUserName of the current logged on user and check if they are member of a specific Active Directory group and set the visibility of certain controls if they are authorized.
Here's some example code to let you do that:
using AxiomCore2.Client; using AxiomCore2.ControlProperties; using AxiomCore2.Controls; using AxiomCore2.Data; using AxiomCore2.Events; using AxiomCore2.Legacy; using AxiomCore2.Log; using AxiomCore2.Managers; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Collections; using System.Drawing; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; namespace AxiomScript { public partial class ScreenScript : IDisposable { // axiom references public ControlApplication Application { get; } = ControlApplication.Instance; public ControlFactoryManager ControlFactory { get; } = ControlFactoryManager.Instance; public IDataProvider DataProvider { get; } = DataProviderManager.CreateInstance(); public ILog Log { get; } = ClientLog.UserScript; public NavigationManager Navigation { get; } = NavigationManager.Instance; public ControlScreen Screen => _screen; public void OnScreenVisible() { // get arguments used to create the application var args = (AxiomCore2.SerializableSandboxArgs)ClientInfo.Instance.GetType().GetField("_sandboxArgs",System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(ClientInfo.Instance); // get the WindowsUserName property var userName = args.WindowsUserName; // check if the user is member of a specific Active Directory group var authorized = IsUserInGroup(userName, "CanaryAdministrators"); // set the visibility of certain controls if the user is authorized SetControlsVisibility(authorized); Log.Info($"User: {userName} Authorized: {authorized}"); } public void OnScreenInvisible() { } public void Dispose() { } public void SetControlsVisibility(bool authorized){ Label2.IsVisible = authorized; ValueBox2.IsVisible = authorized; } public static bool IsUserInGroup(string userName, string groupName) { // based on example on stackoverflow https://stackoverflow.com/a/76893395/10188134 try { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) { var gp = GroupPrincipal.FindByIdentity(pc, groupName); var up = UserPrincipal.FindByIdentity(pc, userName); if (gp == null || up == null) { return false; } DirectoryEntry user = new DirectoryEntry($"LDAP://{up.DistinguishedName}"); DirectorySearcher mySearcher = new DirectorySearcher(user) { SearchScope = SearchScope.Subtree, Filter = $"(memberOf:1.2.840.113556.1.4.1941:={gp.DistinguishedName})" // takes also subgroups }; return !(mySearcher.FindOne() == null); } } catch (Exception) { return false; } } } }