Link to home
Start Free TrialLog in
Avatar of mece
mece

asked on

Detect PowerUser or Admin

How can i detect the user type (poweruser or administrator or normal user)
ASKER CERTIFIED SOLUTION
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Robn
Robn

type
  TTriBool = (tbUnknown, tbTrue, tbFalse);

var
  USER_ADMIN: TTriBool = tbUnknown;

function IsUserAdministrator: Boolean;
const
  DOMAIN_ALIAS_RID_ADMINS = $220;
  SECURITY_BUILTIN_DOMAIN_RID = $20;
var
  i: Integer;
  hProcess, hAccessToken: THandle;
  InfoBuffer: array[0..1023] of UCHAR;
  dwInfoBufferSize: DWORD;
  siaNtAuthority: TSIDIdentifierAuthority;
  psidAdministrators: Pointer;
  ptgGroups: PTokenGroups;
begin
  if USER_ADMIN = tbUnknown then begin
    result := False;
    USER_ADMIN := tbFalse;

    FillChar(ptgGroups, sizeof(ptgGroups), 0);
    FillChar(siaNtAuthority, sizeof(siaNtAuthority), 0);
    siaNtAuthority.Value[5] := 5;

    hProcess := GetCurrentProcess;

    if not OpenProcessToken(hProcess,TOKEN_READ,hAccessToken) then Exit;

    if not GetTokenInformation(hAccessToken, TokenGroups, @InfoBuffer, 1024, dwInfoBufferSize) then Exit;

    AllocateAndInitializeSid(siaNtAuthority, 2,
       SECURITY_BUILTIN_DOMAIN_RID,
       DOMAIN_ALIAS_RID_ADMINS,
       0, 0, 0, 0, 0, 0,
       psidAdministrators);

    ptgGroups := PTokenGroups(@InfoBuffer);

    for i := 0 to ptgGroups^.GroupCount - 1 do begin
       if EqualSid(psidAdministrators, ptgGroups^.Groups[i].Sid) then begin
         USER_ADMIN := tbTrue;
         Break;
       end;
    end;

    FreeSid(psidAdministrators);
  end;
  result := USER_ADMIN = tbTrue;
end;

Hope this helps,
Rob