How to test if user is ‘Admin’ in Rhino 8 / .NET 7? – Rhino Developer


Hi all,

I wonder if someone can help with this?


Rhino-7 Behavior [Working]:

In Rhino 7, in a GhPython GH Component, I used to use an is_user_admin python function to see if the current user had opened Rhino using the ‘Run as administrator’ mode.

This function used the System.Security.Principal module and looked like this:

import System.Security.Principal as sec

def is_user_admin():
    identity = sec.WindowsIdentity.GetCurrent()
    principal = sec.WindowsPrincipal(identity)
    is_admin = principal.IsInRole(sec.WindowsBuiltInRole.Administrator)
    return is_admin

print is_user_admin()

This worked fine in the .NET 4 Rhino 7 environment. It returned ‘True’ if in admin mode, and ‘False’ otherwise.


Rhino-8 Behavior [Not Working]:

In Rhino 8 however, for some reason those properties are not available any longer? Now, when I query System.Security.Principal I see only:

['GenericIdentity', 'GenericPrincipal', 'IIdentity', 'IPrincipal', 'PrincipalPolicy', 'TokenImpersonationLevel']

but no WindowsIdentity, WindowsPrincipal, or WindowsBuiltInRole ?


So:

  • Is there a better way to check if the current user opened Rhino ‘in admin’ mode?
  • Is there a way to still access those ‘missing’ methods in the new .NET 7 environment? I rummaged around in there for a bit but could not seem to find anything?
  • I am assuming this change is related to the .NET switch, but perhaps it is cause by something else?

any advice is much appreciated.
Thanks!
@ed.p.may


Environment:

  • Macbook 2021, Apple M1 Max
  • macOS 13.6.1 (Ventura)
  • Parallels Desktop for Mac 19.1.1 (54734)
  • Windows 11 Home v 21H2 (22000.2538)
  • Rhino Version 8 (8.3.24002.13001, 2024-01-02)

Hi @ed.p.may ,
You can use ctypes

import ctypes

def is_user_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except Exception as e:
        print("Error: " + str(e))
        return False

Hope this helps,
Farouk



1 Like

This works for me in a Python 3 script in Grasshopper:

 import System.Threading as thr
import System.Security.Principal as princip

mydom = thr.Thread.GetDomain()
mydom.SetPrincipalPolicy(princip.PrincipalPolicy.WindowsPrincipal)
curprincip = thr.Thread.CurrentPrincipal

IsUser = curprincip.IsInRole("BUILTIN\\Users")
IsAdmin = curprincip.IsInRole("BUILTIN\\Administrators")

With Rhino started as admin:



1 Like

Thanks @nathanletwory , @farouk.serragedine ,

Both of those solutions are working perfectly – exactly what I was looking for.

Thank you!
@ed.p.may



Source link

Leave a Comment