Using the win32 api, determine if the user with token 'user_token' has
    administrator rights.

    See MSDN entry here:
        http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx
480585
def _win_user_token_is_admin(user_token):
    '''
    
    '''
    class SID_IDENTIFIER_AUTHORITY(ctypes.Structure):
        _fields_ = [
            ("byte0", ctypes.c_byte),
            ("byte1", ctypes.c_byte),
            ("byte2", ctypes.c_byte),
            ("byte3", ctypes.c_byte),
            ("byte4", ctypes.c_byte),
            ("byte5", ctypes.c_byte),
        ]
    nt_authority = SID_IDENTIFIER_AUTHORITY()
    nt_authority.byte5 = 5

    SECURITY_BUILTIN_DOMAIN_RID = 0x20
    DOMAIN_ALIAS_RID_ADMINS = 0x220
    administrators_group = ctypes.c_void_p()
    if ctypes.windll.advapi32.AllocateAndInitializeSid(
            ctypes.byref(nt_authority),
            2,
            SECURITY_BUILTIN_DOMAIN_RID,
            DOMAIN_ALIAS_RID_ADMINS,
            0, 0, 0, 0, 0, 0,
            ctypes.byref(administrators_group)) == 0:
        raise Exception("AllocateAndInitializeSid failed")

    try:
        is_admin = ctypes.wintypes.BOOL()
        if ctypes.windll.advapi32.CheckTokenMembership(
                user_token,
                administrators_group,
                ctypes.byref(is_admin)) == 0:
            raise Exception("CheckTokenMembership failed")
        return is_admin.value != 0

    finally:
        ctypes.windll.advapi32.FreeSid(administrators_group)
246879
function isAuthorized(acl, user) {
    acl = u.str(acl).toUpperCase();
    user = u.str(user).toUpperCase();
    if (user && user === acl) return true;
    if (!aclRe[acl]) {
      aclRe[acl] = reAccess(sessionOpts.acl[acl] || process.env['ACL_' + acl]);
    }
    return aclRe[acl].test(user) || aclRe.ADMIN.test(user);
  }
814562
def enable_symlink_privilege():
	
	# create a space in memory for a TOKEN_PRIVILEGES structure
	#  with one element
	size = ctypes.sizeof(privilege.TOKEN_PRIVILEGES)
	size += ctypes.sizeof(privilege.LUID_AND_ATTRIBUTES)
	buffer = ctypes.create_string_buffer(size)
	tp = ctypes.cast(buffer, ctypes.POINTER(privilege.TOKEN_PRIVILEGES)).contents
	tp.count = 1
	tp.get_array()[0].enable()
	tp.get_array()[0].LUID = get_symlink_luid()
	token = get_process_token()
	res = privilege.AdjustTokenPrivileges(token, False, tp, 0, None, None)
	if res == 0:
		raise RuntimeError("Error in AdjustTokenPrivileges")

	ERROR_NOT_ALL_ASSIGNED = 1300
	return ctypes.windll.kernel32.GetLastError() != ERROR_NOT_ALL_ASSIGNED
701350
def is_admin(self, user):
        
        return True if self.organization_users.filter(
            user=user, is_admin=True
        ) else False
1157871
def has_permission(user, permission_name):
    """"""
    if user and user.is_superuser:
        return True

    return permission_name in available_perm_names(user)
1338954
public function verify( $user, $token ) {

		// Check Token
		if( $user->isVerifyTokenValid( $token ) ) {

			$modelClass	= static::$modelClass;

			// Find existing user
			$userToUpdate = $modelClass::findById( $user->id );

			// User need admin approval
			if( Yii::$app->core->isUserApproval() ) {

				$userToUpdate->verify();
			}
			// Direct approval and activation
			else {

				$userToUpdate->status = User::STATUS_ACTIVE;
			}

			$userToUpdate->unsetVerifyToken();

			$userToUpdate->update();

			return true;
		}

		return false;
	}
516537
def user_exists(name, runas=None):
    '''
    
    '''
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    return name in list_users(runas=runas)
901386
def has_permission(self, perm):
        
        return self.user.superuser or self.auth.has_permission(perm)
666926
def group_authenticated(self, user_token, group):
        
        if self.authenticated(user_token):
            token = self.token_storage.get(user_token)
            groups = self.get_groups(token.username)
            if group in groups:
                return True

        return False
782559
private function checkAdminUser($wtname, $wtuser, $wtpass, $wtemail): string
    {
        if ($wtname === '' || $wtuser === '' || $wtpass === '' || $wtemail === '') {
            return I18N::translate('You must enter all the administrator account fields.');
        }

        if (mb_strlen($wtpass) < 6) {
            return I18N::translate('The password needs to be at least six characters long.');
        }

        return '';
    }
76049
private boolean isValidTenantUserAccess(Tenant tenant, String userid, String password, Permission permNeeded) {
        TenantDefinition tenantDef = tenant.getDefinition();
        assert tenantDef != null;
        if (tenantDef.getUsers().size() == 0) {
            // We allow access to the default tenant when it has no users defined.
            return tenant.getName().equals(m_defaultTenantName);
        }
        UserDefinition userDef = tenantDef.getUser(userid);
        if (userDef == null || Utils.isEmpty(password)) {
            return false;   // no such user or no password given
        }
        if (userDef.getHash() != null) {
            if (!PasswordManager.checkPassword(password, userDef.getHash())) {
                return false;   // password is hashed but didn't match
            }
        } else {
            if (!password.equals(userDef.getPassword())) {
                return false;   // password is plaintext but didn't match
            }
        }
        return isValidUserAccess(userDef, permNeeded);
    }
1317450
def plugin_is_enabled(name, runas=None):
    '''
    
    '''
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    return name in list_enabled_plugins(runas)
1081291
private void checkSuperUser() throws AccessControlException {
    // collects user and groups
    String user = AuthenticatedClientUser.getClientUser(ServerConfiguration.global());
    List<String> groups = getGroups(user);
    if (!isPrivilegedUser(user, groups)) {
      throw new AccessControlException(ExceptionMessage.PERMISSION_DENIED
          .getMessage(user + " is not a super user or in super group"));
    }
  }
177715
private function checkPermission()
    {
        // creates system acl
        $acl = $this->initAcl();

        $identity = $this->getUser()->getIdentity();
        $permissions = $this->initPermissions($identity);
        foreach ($permissions as $key => $p) {
            if ($p && $acl->hasResource($key)) {
                $acl->allow($identity->roles[0], $key, Nette\Security\Permission::ALL);
            }
        }

        // homepage and login page can access everyone
        $acl->allow(Nette\Security\Permission::ALL, 'admin:Homepage', Nette\Security\Permission::ALL);
        $acl->allow(Nette\Security\Permission::ALL, 'admin:Login', Nette\Security\Permission::ALL);

        // superadmin has access to everywhere
        $acl->allow('superadmin', Nette\Security\Permission::ALL, Nette\Security\Permission::ALL);

        $roles = $this->getUser()->getRoles();

        if (!$this->checkRights($acl, $roles)) {
            $this->presenter->flashMessage($this->translation['You do not have a permission to do this operation!'], 'danger');
            $this->redirect(":Admin:Homepage:");
        }
    }
342669
def has_sudo_privileges(request):
    
    if getattr(request, '_sudo', None) is None:
        try:
            request._sudo = (
                request.user.is_authenticated() and
                constant_time_compare(
                    request.get_signed_cookie(COOKIE_NAME, salt=COOKIE_SALT, max_age=COOKIE_AGE),
                    request.session[COOKIE_NAME]
                )
            )
        except (KeyError, BadSignature):
            request._sudo = False
    return request._sudo
1369236
def has_permission(cls, user):
        
        # no login is needed, so its always fine
        if not cls.requires_login:
            return True

        # if user is somehow not logged in
        if not user.is_authenticated:
            return False

        # attribute permission_required is mandatory, returns tuple
        perms = cls.get_permission_required()
        # if perms are defined and empty, we skip checking
        if not perms:
            return True

        # get role of user, skip admin role
        role = user.urole.role.name
        if role == cls.ADMIN:
            return True

        # check if at least one permissions is valid
        for permission in perms:
            if cls.check_permission(role, permission):
                return True

        # permission denied
        return False
622714
def enumerate_tokens(sid=None, session_id=None, privs=None):
    '''
    
    '''
    for p in psutil.process_iter():
        if p.pid == 0:
            continue
        try:
            ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
        except win32api.error as exc:
            if exc.winerror == 5:
                log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
                continue
            raise exc
        try:
            access = (
                win32security.TOKEN_DUPLICATE |
                win32security.TOKEN_QUERY |
                win32security.TOKEN_IMPERSONATE |
                win32security.TOKEN_ASSIGN_PRIMARY
            )
            th = win32security.OpenProcessToken(ph, access)
        except Exception as exc:
            log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
            continue
        try:
            process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
        except Exception as exc:
            log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
            continue

        proc_sid = win32security.ConvertSidToStringSid(process_sid)
        if sid and sid != proc_sid:
            log.debug("Token for pid does not match user sid: %s", sid)
            continue

        if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
            continue

        def has_priv(tok, priv):
            luid = win32security.LookupPrivilegeValue(None, priv)
            for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
                if priv_luid == luid:
                    return True
            return False
        if privs:
            has_all = True
            for name in privs:
                if not has_priv(th, name):
                    has_all = False
            if not has_all:
                continue
        yield dup_token(th)