To save system resources, privileges will only be checked (once) if this method is called
@param bool $recheck
@return Privileges
348528
final public function permissions(bool $recheck = false): Privileges
    {
        if (!$this->privileges || $recheck) {
            $this->privileges = new Privileges($this->path);
        }

        return $this->privileges;
    }
1098711
public function detachAllPermissions($reload = true)
    {
        if ($this->permissions->isEmpty()) return 0;

        event(new DetachingAllPermissionsFromRole($this));
        $results = $this->permissions()->detach();
        event(new DetachedAllPermissionsFromRole($this, $results));

        $this->loadPermissions($reload);

        return $results;
    }
1042305
public function startCheck()
    {
        $masterPool = getInstance()->getAsynPool($this->master);
        if (!$masterPool) {
            $masterPool = new MysqlAsynPool(getInstance()->config, $this->master);
            getInstance()->addAsynPool($this->master, $masterPool, true);
        }

        foreach ($this->slaves as $slavePoolName) {
            $slavePool = getInstance()->getAsynPool($slavePoolName);
            if (!$slavePool) {
                $slavePool = new MysqlAsynPool(getInstance()->config, $slavePoolName);
                getInstance()->addAsynPool($slavePoolName, $slavePool, true);
            }
        }

        return $this;
    }
24253
public function setAuthorizerAccessToken($token, $expires = 7200)
    {
        return $this->cache->save($this->getAuthorizerAccessTokenKey(), $token, $expires);
    }
695981
public function forceSave(array $data = [], $recursive = false)
    {
        return ($recursive) ? $this->recurse('save', $data) : $this->saveRecord($data);
    }
1259642
public function grant()
    {
        if (!$this->name) {
            throw new UnexpectedValueException(
                'Cannot grant privileges to a user with no name'
            );
        }
        if (!$this->grants) {
            throw new UnexpectedValueException(
                'Cannot grant privileges without being told what privileges to grant'
            );
        }
        if (!$this->grantLevel) {
            throw new UnexpectedValueException(
                'Cannot grant privileges without being told on what to grant them'
            );
        }

        $params = array();
        $parts = array(
            sprintf(
                'GRANT %s ON %s',
                strtolower($this->grants) == 'all'
                    ? 'ALL PRIVILEGES'
                    : $this->grants,
                $this->grantLevel
            )
        );

        $parts[] = 'TO :user';
        $params[':user'] = $this->name;

        if ($this->host) {
            $parts[] = '@:host';
            $params[':host'] = strtolower($this->host) == 'any' ? '%' : $this->host;
        }

        if ($this->grantGrant) {
            $parts[] = 'WITH GRANT OPTION';
        }
        
        // Wrap in 'FLUSH PRIVILEGES' commands to update in-memory state
        $this->client->execute('FLUSH PRIVILEGES');
        $this->client->execute(implode(' ', $parts), $params);
        $this->client->execute('FLUSH PRIVILEGES');
    }
89892
protected function throwUnauthorizedException(array $exceptionStack)
    {
        $exception = array_shift($exceptionStack);

        if ($exception === null) {
            $exception = new UnauthorizedException('Failed to authenticate because of bad credentials or an invalid authorization header');
        }

        throw $exception;
    }
79669
function rollback() {
		$this->savepoint--;

		if ($this->savepoint == 0) {
			$this->dbh->rollBack();
		}
		else { // not finished with transaction
			$this->dbh->exec('ROLLBACK TO SAVEPOINT save'.$this->savepoint);
		}

		return $this;
	}
350228
function save() {

		if ($this->cacheConf['type'] == 'noop') {
			// do nothing
		}
		else { // non-noop

			$stateCopy = $this->state;
			$stateCopy['loaded'] = [];

			if ($this->cacheConf['type'] == 'file') {
				$username = \get_current_user();
				$cacheDir = realpath($this->syspath.'/'.\trim($this->cacheConf['path'], '\\/'));
				$cachePath = $cacheDir.'/freia.'.(\php_sapi_name() === 'cli' ? 'cli' : 'server').'.'.$username.'.symbols.json';
				if ($this->file_exists($cacheDir)) {
					try {
						$this->file_put_contents($cachePath, \json_encode($stateCopy, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
						if ( ! $this->chmod($cachePath, $this->filePermission())) {
							$this->error_log("Unable to set permissions on cache file: $cachePath");
						}
					}
					catch (\Exception $e) {
						$this->error_log('Failed to save state to cache file ['.$cachePath.'] Error: '.$e->getMessage());
					}
				}
				else {
					$this->error_log('Missing cache directory: '.$this->cacheConf['path']);
				}
			}
			else if ($this->cacheConf['type'] == 'memcached') {
				$mc = $this->memcachedInstance();
				$success = $mc->set('freia-symbols', $stateCopy, time() + 604800);
				if ( ! $success) {
					$this->error_log("Memcached failed to store key freia-symbols, code: ".$mc->getResultCode());
				}
			}
		}
	}
871750
private function doChecks($checks)
    {
        $errors = [];
        foreach ($checks as $check) {
            try {
                $check();
            } catch (Exception $e) {
                $errors[] = $e;
            }
        }
        if (count($errors)) {
            throw (new MultipleExceptions)->setExceptions($errors);
        }
    }
1203051
public function restart($wait = true)
    {
        return $this->forge->restartWorker($this->serverId, $this->siteId, $this->id, $wait);
    }
1126219
public function setDncChecks($dnc_checks)
    {
        if (is_array($dnc_checks)) {
            $dnc_checks = implode(',', $dnc_checks);
        }
        $this->isChanged('dncChecks', $dnc_checks);
        $this->dnc_checks = $dnc_checks;

        return $this;
    }
99476
public function hasToken($tokenCheck, $forceExpire = true)
	{
		$stored = $this->get('session.token');

		if ($stored !== $tokenCheck) {

			if ($forceExpire) {
				$this->_state = self::STATE_EXPIRED;
			}

			return false;
		}

		return true;
	}
596830
public function performRemoteCheck($httpClient = null) {
        if(empty($this->sessionToken)) { return false; }

        $json = $this->fetchUrl($this->getSessionCheckUrl(), $httpClient);
        if ($json) {
            $response = json_decode($json,true);

            if ($response['valid'] == "true" && $response['recheck'] != null) {
                $this->recheck = new DateTime($response['recheck']);
                return true;
            }
        }

        return false;
    }
1223850
public function getUser($check = true)
    {
        if ($check === true && $this->user === null) {
            $this->check();
        }

        return $this->user;
    }
731994
public function renewAccessToken($clientSecret)
    {
        if (null === $this->_state->token->data->refresh_token) {
            throw new \Exception(
                'The refresh token is not set or no permission for'
                    . ' \'wl.offline_access\' was given to renew the token'
            );
        }

        $values = [
            'client_id'     => $this->clientId,
            'client_secret' => $clientSecret,
            'grant_type'    => 'refresh_token',
            'refresh_token' => $this->_state->token->data->refresh_token,
        ];

        $response = $this->httpClient->post(
            self::TOKEN_URL,
            ['form_params' => $values]
        );

        $body = $response->getBody();
        $data = json_decode($body);

        if ($data === null) {
            throw new \Exception('json_decode() failed');
        }

        $this->_state->token = (object) [
            'obtained' => time(),
            'data'     => $data,
        ];
    }
657316
def reenroll!
      unless @reenrolling
        @reenrolling = true
        begin
          info("Triggering re-enroll after unsuccessful communication check", to_console = true)
          cmd = "rs_reenroll"
          cmd += " -v" if @options[:verbose]
          cmd += '&' unless RightScale::Platform.windows?
          # Windows relies on the command protocol to terminate properly.
          # If rchk terminates itself, then rchk --stop will hang trying
          # to connect to this rchk.
          terminate unless RightScale::Platform.windows?
          system(cmd)
          # Wait around until rs_reenroll has a chance to stop the checker
          # otherwise we may restart it
          sleep(5)
        rescue Exception => e
          error("Failed re-enroll after unsuccessful communication check", e, abort = true)
        end
        @reenrolling = false
      end
      true
    end