• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 607
  • Last Modified:

get user role using visual c++ without using managed code

I am writing an applicaiton in Visual C++. I have been able to get the the user of the machine using GetUserName function. Now I would like to get the role of this user in the windows operating system. Basically I want to check if the user is administrator. Based on that I can then execute certain functionality in my application.

Now can anyone help me how I can achive this without using managed code?

Thanks in advance.
0
randhirshinde
Asked:
randhirshinde
  • 2
1 Solution
 
mahesh1402Commented:
The function below shows you how to determine if the user is an administrator or not....

BOOL IsAdmin()
{

   TOKEN_GROUPS* tgTokens;
   DWORD         group_no;
   PSID          admin_psid;
   HANDLE        hToken, hProcess;

   hProcess = GetCurrentProcess();
   OpenProcessToken(hProcess, TOKEN_QUERY, &hToken);

   GetTokenInformation(hToken, TokenGroups, NULL,0, &group_no);


   tgTokens = (TOKEN_GROUPS*)new BYTE[group_no];  

   GetTokenInformation(hToken, TokenGroups, tgTokens, group_no, &group_no);


   SID_IDENTIFIER_AUTHORITY authsid = SECURITY_NT_AUTHORITY;

   AllocateAndInitializeSid(&authsid, 2, SECURITY_BUILTIN_DOMAIN_RID,DOMAIN_ALIAS_RID_ADMINS,0,0,0,0,0,0, &admin_psid);

   for (int i = 0; i < tgTokens->GroupCount; i++)
    if (EqualSid(tgTokens->Groups[i].Sid, admin_psid))            
    {
   delete [] tgTokens;
   CloseHandle(hToken);
   FreeSid(admin_psid);
   return true; // User is admin
    }

    return false;
}

-MAHESH
0
 
mahesh1402Commented:
Additionally if you have shell32.dll version 5+ you may use IsUserAnAdmin() from this dll....

e.g

typedef BOOL (WINAPI *LPFNIUA)(void);

HMODULE hShell32 = LoadLibrary(_T("shell32.dll"));
LPFNIUA pIsAdmin = NULL;

if (hShell32)
{
    pIsAdmin = (LPFNIUA)GetProcAddress(hShell32, MAKEINTRESOURCE(680));
    if (pIsAdmin)
    {
        BOOL bIsAdmin = pIsAdmin();
        _tprintf(_T("User %s an admin\r\n"), bIsAdmin ? _T("is") : _T("is not"));
    }
    FreeLibrary(hShell32);
}

Otherwise use code above

http://vcfaq.mvps.org/sdk/21.htm
http://support.microsoft.com/?id=118626


-MAHESH
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now