API:Criação de contas

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page API:Account creation and the translation is 6% complete.

Other languages:
Deutsch • ‎English • ‎Türkçe • ‎dansk • ‎español • ‎français • ‎italiano • ‎polski • ‎português • ‎română • ‎русский • ‎العربية • ‎ไทย • ‎中文 • ‎日本語 • ‎한국어
MediaWiki version: 1.27
This page documents the account creation API as of MediaWiki 1.27. Documentation of the API as it existed in earlier versions is available here: Api:Account creation/pre-1.27 .

API documentation


action=createaccount (create)

(main | createaccount)
  • This module requires write rights.
  • This module only accepts POST requests.
  • Source: MediaWiki
  • License: GPL-2.0-or-later

Create a new user account.

The general procedure to use this module is:

  1. Fetch the fields available from action=query&meta=authmanagerinfo with amirequestsfor=create, and a createaccount token from action=query&meta=tokens.
  2. Present the fields to the user, and obtain their submission.
  3. Post to this module, supplying createreturnurl and any relevant fields.
  4. Check the status in the response.
    • If you received PASS or FAIL, you're done. The operation either succeeded or it didn't.
    • If you received UI, present the new fields to the user and obtain their submission. Then post to this module with createcontinue and the relevant fields set, and repeat step 4.
    • If you received REDIRECT, direct the user to the redirecttarget and wait for the return to createreturnurl. Then post to this module with createcontinue and any fields passed to the return URL, and repeat step 4.
    • If you received RESTART, that means the authentication worked but we don't have a linked user account. You might treat this as UI or as FAIL.
Parameters:
createrequests

Only use these authentication requests, by the id returned from action=query&meta=authmanagerinfo with amirequestsfor=create or from a previous response from this module.

Separate values with | or alternative. Maximum number of values is 50 (500 for bots).
createmessageformat

Format to use for returning messages.

One of the following values: html, wikitext, raw, none
Default: wikitext
createmergerequestfields

Merge field information for all authentication requests into one array.

Type: boolean (details)
createpreservestate

Preserve state from a previous failed login attempt, if possible.

If action=query&meta=authmanagerinfo returned true for hasprimarypreservedstate, requests marked as primary-required should be omitted. If it returned a non-empty value for preservedusername, that username must be used for the username parameter.

Type: boolean (details)
createreturnurl

Return URL for third-party authentication flows, must be absolute. Either this or createcontinue is required.

Upon receiving a REDIRECT response, you will typically open a browser or web view to the specified redirecttarget URL for a third-party authentication flow. When that completes, the third party will send the browser or web view to this URL. You should extract any query or POST parameters from the URL and pass them as a createcontinue request to this API module.

createcontinue

This request is a continuation after an earlier UI or REDIRECT response. Either this or createreturnurl is required.

Type: boolean (details)
createtoken

A "createaccount" token retrieved from action=query&meta=tokens

This parameter is required.
*
This module accepts additional parameters depending on the available authentication requests. Use action=query&meta=authmanagerinfo with amirequestsfor=create (or a previous response from this module, if applicable) to determine the requests available and the fields that they use.

Creating an account

The process has three general steps:

  1. Fetch the fields from API:Authmanagerinfo and the token from API:Tokens .
  2. Send a POST request with the fetched token, user information and other fields, and return URL to the API.
  3. Deal with the response, which might involve further POST requests to supply more information.

Example 1: Process on a wiki without special authentication extensions

A wiki without special authentication extensions can be rather straightforward. If your code knows which fields will be required, it might skip the call to API:Authmanagerinfo and just assume which fields will be needed (i.e. username, password & retyped password, email, possibly realname).

If you are creating an account for someone else, you'll need to specify a reason for the same by including a reason parameter to the POST request. You could also use mailpassword in place of password and retype parameters to have MediaWiki send the new user a temporary password via email.

POST request

Response

{
    "createaccount": {
        "status": "PASS",
        "username": "Zane"
    }
}

Sample code

Python

#!/usr/bin/python3

"""
    create_account.py

    MediaWiki API Demos
    Demo of `createaccount` module: Create an account on a wiki without the
    special authentication extensions

    MIT license
"""

import requests

S = requests.Session()

WIKI_URL = "http://dev.wiki.local.wmftest.net:8080"
API_ENDPOINT = WIKI_URL + "/w/api.php"

# First step
# Retrieve account creation token from `tokens` module

PARAMS_0 = {
    'action':"query",
    'meta':"tokens",
    'type':"createaccount",
    'format':"json"
}

R = S.get(url=API_ENDPOINT, params=PARAMS_0)
DATA = R.json()

TOKEN = DATA['query']['tokens']['createaccounttoken']

# Second step
# Send a post request with the fetched token and other data (user information,
# return URL, etc.)  to the API to create an account

PARAMS_1 = {
    'action': "createaccount",
    'createtoken': TOKEN,
    'username': 'your_username',
    'password': 'your_password',
    'retype': 'retype_your_password',
    'createreturnurl': WIKI_URL,
    'format': "json"
}

R = S.post(API_ENDPOINT, data=PARAMS_1)
DATA = R.json()

print(DATA)

PHP

<?php

/*
    create_account.php

    MediaWiki API Demos
    Demo of `createaccount` module: Create an account on a wiki without the
    special authentication extensions
    MIT license
*/

$wikiUrl = "http://dev.wiki.local.wmftest.net:8080";
$endPoint = $wikiUrl . "/w/api.php";

$createAccount_Token = getCreateAccountToken(); // Step 1
createAccount( $createAccount_Token ); // Step 2

// Step 1: GET Request to fetch createaccount token
function getCreateAccountToken() {
	global $endPoint;

	$params1 = [
		"action" => "query",
		"meta" => "tokens",
		"type" => "createaccount",
		"format" => "json"
	];

	$url = $endPoint . "?" . http_build_query( $params1 );

	$ch = curl_init( $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	$result = json_decode( $output, true );
	return $result["query"]["tokens"]["createaccounttoken"];
}

// Step 2: POST Request with the fetched token and other data (user information,
// return URL, etc.)  to the API to create an account
function createAccount( $createAccount_Token ) {
	global $endPoint, $wikiUrl;

	$params2 = [
		"action" => "createaccount",
		"createtoken" => $createAccount_Token,
		"username" => "your_username",
		"password" => "your_password",
		"retype" => "retype_your_password",
		"createreturnurl" => $wikiUrl,
		"format" => "json"
	];

	$ch = curl_init();

	curl_setopt( $ch, CURLOPT_URL, $endPoint );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params2 ) );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	echo( $output );
}

JavaScript

/*  
    create_account.js
 
    MediaWiki API Demos
    Demo of `createaccount` module: Create an account on a wiki without the
    special authentication extensions

    MIT license
*/

var request = require('request').defaults({jar: true}),
    wikiUrl = "http://dev.wiki.local.wmftest.net:8080",
    endPoint = wikiUrl + "/w/api.php";

// Step 1: GET Request to fetch createaccount token
function getCreateAccountToken() {
    var params_0 = {
        action: "query",
        meta: "tokens",
        type: "createaccount",
        format: "json"
    };

    request.get({ url: endPoint, qs: params_0 }, function (error, res, body) {
        if (error) {
            return;
        }
        var data = JSON.parse(body);
        createaccount(data.query.tokens.createaccounttoken);
    });
}

// Step 2: POST Request with the fetched token and other data (user information,
// return URL, etc.)  to the API to create an account
function createaccount(createaccount_token) {
    var params_1 = {
        action: "createaccount",
        username: "your_username",
        password: "your_password",
        retype: "retype_your_password",
        createreturnurl: wikiUrl,
        createtoken: createaccount_token,
        format: "json"
    };

    request.post({ url: endPoint, form: params_1 }, function (error, res, body) {
        if (error) {
            return;
        }
        console.log(body);
    });
}

// Start From Step 1
getCreateAccountToken();

MediaWiki JS

/*
	create_account.js

	MediaWiki API Demos
    Demo of `createaccount` module: Create an account on a wiki without the
    special authentication extensions

	MIT License
*/

var params = {
		action: 'query',
		meta: 'tokens',
		type: 'createaccount',
		format: 'json'
	},
	api = new mw.Api();

api.get( params ).done( function ( data ) {
	var token = data.query.tokens.createaccounttoken,
		params1 = {
			action: 'createaccount',
			username: 'your_username',
			password: 'your_password',
			retype: 'retype_your_password',
			createreturnurl: 'http:' + mw.config.get( 'wgServer' ),
			createtoken: token,
			format: 'json'
		};

	api.post( params1 ).done( function ( data ) {
		console.log( data );
	} );
} );


Example 2: Process on a wiki with a CAPTCHA extension

Note the first step below could, if you'd rather, be done as two steps: one to fetch the fields available from API:Authmanagerinfo and another to fetch the token from API:Tokens .

First step: Fetch fields available from API:Authmanagerinfo and token from API:Tokens

Second step: Send a post request along with a create account token, user information and return URL

Sample Code

Note this code sample separates the API:Authmanagerinfo and API:Tokens requests, and generally assumes there will be a CAPTCHA and no other complications.

Example 3: Account creation on a wiki with a CAPTCHA, an OpenID extension, and a two-factor authentication extension enabled

First step: Fetch fields available from API:Authmanagerinfo and token from API:Tokens

The fetching of API:Authmanagerinfo and API:Tokens is largely the same as in the previous example, and so is not repeated here. The list of requests returned by API:Authmanagerinfo will include definitions for both the CAPTCHA extension and the OpenID extension.

Second step: Answer the CAPTCHA and select OpenID authentication.

The client would be expected to redirect the user's browser to the provided redirecttarget.

The OpenID provider would authenticate, and redirect to Special:OpenIDConnectReturn on the wiki, which would validate the OpenID response and then redirect to the createreturnurl provided in the first POST to the API with the code and state parameters added.

The client gets control of the process back at this point and makes its next API request.

Third step: Back from OpenID.

The client posts the code and state back to the API. The API's response has the two-factor authentication extension prompting the user to set up their second factor.

Now the client would prompt the user to set up a new account in their two-factor authentication app and enter the current code, or allow the user to skip 2FA setup. Let's assume the user does set up 2FA.

Fourth step: Set up two-factor authentication.

The account creation has finally succeeded.

If at any point account creation fails, a response with status FAIL will be returned, along with a message to display to the user.

Possible errors

Code Info
badtoken Invalid create account token
notoken O parâmetro token tem de ser definido.
mustpostparams O seguinte parâmetro foi encontrado no texto da pesquisa, mas têm de estar no corpo do POST: createtoken.
missingparam Pelo menos um dos parâmetros "createcontinue" e "createreturnurl" é obrigatório.
authmanager-create-no-primary Não foi possível criar uma conta com as credenciais fornecidas.
invalidemailaddress O endereço de correio eletrónico não pode ser aceite porque parece ter um formato inválido.

Introduza um endereço formatado corretamente ou deixe o campo vazio.

badretype As palavras-passe que introduziu não coincidem.
userexists O nome de utilizador introduzido já existe.

Escolha um nome diferente, por favor.

captcha-createaccount-fail O código CAPTCHA está incorreto ou não foi preenchido.
acct_creation_throttle_hit Visitantes desta wiki com o seu endereço IP criaram 1 conta no último dia, que é o máximo permitido nesse período.

Em resultado, os visitantes que utilizem este endereço não podem criar mais contas neste momento.

Se estiver num evento onde o foco é a contribuição para projetos da Wikimedia, consulte Pedir remoção temporária do limite IP para ajudar a resolver este problema, por favor.

Additional notes

Se tiver iniciado uma sessão, o seu nome de utilizador também será gravado ao criar uma conta.

  • While executing the code snippets provided on this page, remember:
    • Once an account on a wiki is created, it cannot be deleted.
    • Always use https://test.wikipedia.org/w/api.php as the endpoint, so that you don't accidentally create accounts on production wikis.
  • MediaWiki site administrators and extension developers can disable this API feature by inserting the following line in the configuration file:
$wgAPIModules['createaccount'] = 'ApiDisabled';


See also