public static function connect_system_account($issuer, $returnurl) {
        require_capability('moodle/site:config', context_system::instance());

        // We need to authenticate with an oauth 2 client AS a system user and get a refresh token for offline access.
        $scopes = self::get_system_scopes_for_issuer($issuer);

        // Allow callbacks to inject non-standard scopes to the auth request.

        $client = new client($issuer, $returnurl, $scopes, true);

        if (!optional_param('response', false, PARAM_BOOL)) {
            $client->log_out();
        }

        if (optional_param('error', '', PARAM_RAW)) {
            return false;
        }

        if (!$client->is_logged_in()) {
            redirect($client->get_login_url());
        }

        $refreshtoken = $client->get_refresh_token();
        if (!$refreshtoken) {
            return false;
        }

        $systemaccount = self::get_system_account($issuer);
        if ($systemaccount) {
            $systemaccount->delete();
        }

        $userinfo = $client->get_userinfo();

        $record = new stdClass();
        $record->issuerid = $issuer->get('id');
        $record->refreshtoken = $refreshtoken;
        $record->grantedscopes = $scopes;
        $record->email = isset($userinfo['email']) ? $userinfo['email'] : '';
        $record->username = $userinfo['username'];

        $systemaccount = new system_account(0, $record);

        $systemaccount->create();

        $client->log_out();
        return true;
    }