/*
 * Copyright (c) 2000-2009 TeamDev Ltd. All rights reserved.
 * TeamDev PROPRIETARY and CONFIDENTIAL.
 * Use is subject to license terms.
 */

import com.jniwrapper.win32.security.AccessToken;
import com.jniwrapper.win32.security.TokenGroups;
import com.jniwrapper.win32.security.SidAndAttributes;
import com.jniwrapper.win32.security.Sid;
import com.jniwrapper.NoSuchFunctionException;

/**
 * This sample checks admin rights of the current process.
 *
 * @author Vadim Ridosh
 */
public class CheckAdminRightsSample
{
    public static void main(String[] args)
    {
        if (checkAdminRights())
        {
            System.out.println("Current process do have admin rights");
        }
        else
        {
            System.out.println("Current process do NOT have admin rights");
        }
    }

    private static boolean checkAdminRights()
    {
        try
        {
            return AccessToken.checkTokenMembership(null, Sid.Admins());
        }
        catch (NoSuchFunctionException e)
        {
            // checkTokenMembership throws NoSuchFunctionException - probably, Windows NT4 system

            // Empty AccessToken constructor creates access token for current user
            AccessToken token = new AccessToken();

            // Obtain groups from the token
            TokenGroups tokenGroups = token.getTokenGroups();
            if (tokenGroups != null)
            {
                // Enumerate groups
                int count = tokenGroups.getGroupCount();
                for (int group = 0; group < count; ++group)
                {
                    SidAndAttributes sidAndAttributes = tokenGroups.getGroups(group);

                    // Obtain group attribute
                    Sid sid = sidAndAttributes.getSid();

                    if (sid.equals(Sid.Admins()))
                    {
                        return true; // Admins group is inside token
                    }
                }
            }
            return false;
        }
    }
}