Skip to content

Instantly share code, notes, and snippets.

@timhunt
Last active February 6, 2024 15:34
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save timhunt/51987ad386faca61fe013904c242e9b4 to your computer and use it in GitHub Desktop.
Save timhunt/51987ad386faca61fe013904c242e9b4 to your computer and use it in GitHub Desktop.
<?php
require_once(__DIR__ . '/config.php');
require_once($CFG->dirroot . '/webservice/lib.php');
$systemcontext = context_system::instance();
// Enable web services and REST protocol.
set_config('enablewebservices', true);
set_config('webserviceprotocols', 'rest');
// Create a web service user.
$webserviceuser = $this->datagenerator->create_user([
'username' => 'ws-externalquiz-user', 'firstname' => 'Externalquiz grades',
'lastname' => 'User']);
// Create a web service role.
$wsroleid = create_role('WS Role for Externalquiz grades', 'ws-externalquiz-role', '');
set_role_contextlevels($wsroleid, [CONTEXT_SYSTEM]);
assign_capability('webservice/rest:use', CAP_ALLOW, $wsroleid, $systemcontext->id, true);
assign_capability('mod/externalquiz:receivegrades', CAP_ALLOW, $wsroleid, $systemcontext->id, true);
// Give the user the role.
role_assign($wsroleid, $webserviceuser->id, $systemcontext->id);
// Enable the externalquiz webservice.
$webservicemanager = new webservice();
$service = $webservicemanager->get_external_service_by_shortname('mod_externalquiz_receive_grades');
$service->enabled = true;
$webservicemanager->update_external_service($service);
// Authorise the user to use the service.
$webservicemanager->add_ws_authorised_user((object) ['externalserviceid' => $service->id,
'userid' => $webserviceuser->id]);
// Create a token for the user.
$token = external_generate_token(EXTERNAL_TOKEN_PERMANENT, $service, $webserviceuser->id, $systemcontext);
@geoffreyvanwyk
Copy link

geoffreyvanwyk commented Mar 4, 2021

Very nice!

I know this is just to demonstrate, but just for interest sake, if there are already other protocols enabled,

set_config('webserviceprotocols', 'rest');

will disable them. That is why I do:

$enabledprotocols = get_config('core', 'webserviceprotocols');
if (stripos($enabledprotocols, 'rest') === false) {
    set_config('webserviceprotocols', $enabledprotocols . ',rest');
}

@timhunt
Copy link
Author

timhunt commented Mar 4, 2021

Yes, that is better code.

@jhordanres
Copy link

Hi, sorry, any have the endpoints for use the API of Moodle ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment