API:Fiók létrehozása

From mediawiki.org
This page is a translated version of the page API:Account creation and the translation is 100% complete.
MediaWiki-verzió:
1.27
Ez az oldal a fióklétrehozó API MediaWiki 1.27-től való működésének dokumentációja. A korábbi verziók API-jának dokumentációja itt érhető el: Api:Account creation/pre-1.27 .

API-dokumentáció


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.
Specific parameters:
Other general parameters are available.
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 clients that are allowed higher limits).
createmessageformat

Format to use for returning messages.

One of the following values: html, none, raw, wikitext
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.

Fiók létrehozása

A folyamatnak három alapvető lépése van:

  1. A API:Authmanagerinfo mezőinek és a API:Tokens tokenjének kigyűjtése.
  2. POST-kérés küldése a megfelelő tokennel, felhasználói információkkal és más mezőkkel, és visszatérési URL-lel az API-nak.
  3. A válasz elbírálása, amely további POST-kéréseket igényelhet a további információkhoz.

1. példa: A folyamat egy speciális azonosító kiterjesztések nélküli wikin

Egy speciális azonosító kiterjesztések nélküli wiki elég egyértelmű lehet. Ha tudja a kódod, mely mezők kellenek, átugorhat a hívásban a API:Authmanagerinfo -re, és egyszerűen feltételezheti, mely mezők szükségesek (azaz felhasználónév, jelszó és újraírt jelszó, e-mail-cím, esetleg valós név).

Ha másnak készítesz fiókot, meg kell adnod az okot a egy reason paraméter hozzáadásával a POST-kéréshez. Használhatod a mailpassword-et a password és retype paraméterek helyett, hogy a MediaWiki az új felhasználónak e-mailen ideiglenes jelszót küldjön.

POST-kérés

Válasz

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

Mintakód

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 );
	} );
} );

2. példa: A folyamat egy CAPTCHA-kiterjesztéssel rendelkező wikin

Az alábbi első lépés, ha szeretnéd, két lépésben is megtehető: egy az elérhető mezők kigyűjtése a API:Authmanagerinfo -ből, egy másik a token kigyűjtése a API:Tokens -ből.

<span id="First_step:_Fetch_fields_available_from_API:Authmanagerinfo _and_token_from_API:Tokens ">

Első lépés: Az elérhető mezők kigyűjtése az API:Authmanagerinfo -ből és a token kigyűjtése a API:Tokens -ből

Eredmény
{
    "batchcomplete": "",
    "query": {
        "authmanagerinfo": {
            "canauthenticatenow": "",
            "cancreateaccounts": "",
            "preservedusername": "",
            "requests": [
                {
                    "id": "CaptchaAuthenticationRequest",
                    "metadata": {
                        "type": "image",
                        "mime": "image/png"
                    },
                    "required": "required",
                    "provider": "CaptchaAuthenticationRequest",
                    "account": "CaptchaAuthenticationRequest",
                    "fields": {
                        "captchaId": {
                            "type": "hidden",
                            "value": "16649214",
                            "label": "CAPTCHA ID",
                            "help": "This value should be sent back unchanged."
                        },
                        "captchaInfo": {
                            "type": "null",
                            "value": "/w/index.php?title=Special:Captcha/image&wpCaptchaId=16649214",
                            "label": "To help protect against automated account creation, please enter the words that appear below in the box ([[Special:Captcha/help|more info]]):",
                            "help": "Description of the CAPTCHA."
                        },
                        "captchaWord": {
                            "type": "string",
                            "label": "CAPTCHA",
                            "help": "Solution of the CAPTCHA."
                        }
                    }
                }
                ...
            ]
        },
        "tokens": {
            "createaccounttoken": "1de8d3f8023305742e69db9e16b4d5365bd82f9c+\\"
        }
    }
}

Második lépés: POST-kérés küldése egy fióklétrehozó tokennel, felhasználói információkkal és visszatérési URL-lel

Eredmény
{
    "createaccount": {
        "status": "PASS",
        "username": "Zane"
    }
}

Mintakód

Ez a kódminta elválasztja a API:Authmanagerinfo és API:Tokens kéréseket, és általánosságban feltételezi, hogy van CAPTCHA, és nincs más komplikáció.

create_account_with_captcha.py
#!/usr/bin/python3

"""
    create_account_with_captcha.py

    MediaWiki Action API Code Samples
    Demo of `createaccount` module: Create an account on a wiki with a special
    authentication extension installed. This example considers a case of a wiki
    where captcha is enabled through extensions like ConfirmEdit
    (https://www.mediawiki.org/wiki/Extension:ConfirmEdit)

    MIT license
"""

import requests
from flask import Flask, render_template, flash, request

S = requests.Session()
WIKI_URL = "https://test.wikipedia.org"
API_ENDPOINT = WIKI_URL + "/w/api.php"

# App config.
DEBUG = True
APP = Flask(__name__)
APP.config.from_object(__name__)
APP.config['SECRET_KEY'] = 'enter_your_secret_key'


@APP.route("/", methods=['GET', 'POST'])
def show_form():
    """ Render form template and handle form submission request """

    fields = get_form_fields()
    captcha = fields['CaptchaAuthenticationRequest']
    captcha_url = WIKI_URL + captcha['captchaInfo']['value']
    captcha_id = captcha['captchaId']['value']

    display_fields = []
    user_fields = []
    captcha_fields = []

    for field in fields:
        for name in fields[field]:
            details = {
                'name': name,
                'type': fields[field][name]['type'],
                'label': fields[field][name]['label']
            }

            if field != "CaptchaAuthenticationRequest":
                user_fields.append(details)
            else:
                if name == 'captchaWord':
                    captcha_fields.append(details)

    display_fields = user_fields + captcha_fields

    if request.method == 'POST':
        create_account(request.form, captcha_id)

    return render_template('create_account_form.html', \
        captcha=captcha_url, fields=display_fields)


def get_form_fields():
    """ Fetch the form fields from `authmanagerinfo` module """

    result = {}
    response = S.get(url=API_ENDPOINT, params={
        'action': 'query',
        'meta': 'authmanagerinfo',
        'amirequestsfor': 'create',
        'format': 'json'
    })
    data = response.json()

    query = data and data['query']
    authmanagerinfo = query and query['authmanagerinfo']
    fields = authmanagerinfo and authmanagerinfo['requests']

    for field in fields:
        if field['id'] in ('MediaWiki\\Auth\\UserDataAuthenticationRequest', \
            'CaptchaAuthenticationRequest', 'MediaWiki\\Auth\\PasswordAuthenticationRequest'):
            result[field['id']] = field['fields']

    return result


def create_account(form, captcha_id):
    """ Send a post request along with create account token, user information
     and return URL to the API to create an account on a wiki """

    createtoken = fetch_create_token()
    response = S.post(url=API_ENDPOINT, data={
        'action': 'createaccount',
        'createtoken': createtoken,
        'username': form['username'],
        'password': form['password'],
        'retype': form['retype'],
        'email': form['email'],
        'createreturnurl': 'http://127.0.0.1:5000/',
        'captchaId': captcha_id,
        'captchaWord': form['captchaWord'],
        'format': 'json'
    })

    data = response.json()
    createaccount = data['createaccount']

    if createaccount['status'] == "PASS":
        flash('Success! An account with username ' + \
            form['username'] + ' has been created!')
    else:
        flash('Oops! Something went wrong -- ' + \
            createaccount['messagecode'] + "." + createaccount['message'])

def fetch_create_token():
    """ Fetch create account token via `tokens` module """

    response = S.get(url=API_ENDPOINT, params={
        'action': 'query',
        'meta': 'tokens',
        'type': 'createaccount',
        'format': 'json'
    })

    data = response.json()
    return data['query']['tokens']['createaccounttoken']


if __name__ == "__main__":
    APP.run()
create_account_form.html
<!DOCTYPE html>
  <title>MediaWiki Create Account</title>
 <!-- CSS files are in here: https://github.com/srish/MediaWiki-Action-API-Code-Samples/tree/master/static -->
  <link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="static/css/account_form.css">

<div class="container">
  <h2>Create MediaWiki Account</h2>
  <form method="POST">
    <div class="form-group">
      <div class="form-field">
        <div class="label-field">Enter your username</div>
        <input name="username">
      </div>
      <div class="form-field">
        <div class="label-field">Password</div>
        <input type="password" name="password">
      </div>
      <div class="form-field">
        <div class="label-field">Confirm password</div>
        <input type="password" name="confirm-password">
      </div>
      <div class="form-field">
        <div class="label-field">Enter address (optional)</div>
        <input name="email">
      </div>
      <div class="form-field">
        <div class="label-field">Enter the text you see on the image below</div>
        <input name="captcha-word">
      </div>
      <img src="{{ captcha }}">
    </div>
    <button type="submit" class="btn btn-success">Create your account</button>
  </form>

  <br>
  {% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
  {% for message in messages %}
  <div class="alert alert-info">
    {{ message[1] }}
  </div>
  {% endfor %}
  {% endif %}
  {% endwith %}
</div>
<br>
</div>
</div>

3. példa: Fióklétrehozás engedélyezett CAPTCHA-val, OpenID- és kétfaktoros azonosítást lehetővé tevő kiterjesztéssel

<span id="First_step:_Fetch_fields_available_from_API:Authmanagerinfo _and_token_from_API:Tokens ">

Első lépés: Az elérhető mezők kigyűjtése az API:Authmanagerinfo -ből és a token kigyűjtése a API:Tokens -ből

A kigyűjtés a API:Authmanagerinfo -ből és a API:Tokens -ből nagyjából ugyanaz, mint az előző példában, ezért nincs itt megismételve. A API:Authmanagerinfo által visszakapott kérések listája tartalmazza a definíciókat a CAPTCHA- és az OpenID-kiterjesztésre is.

Második lépés: a CAPTCHA megválaszolása és az OpenID-azonosítás kiválasztása.

Eredmény
{
    "createaccount": {
        "status": "REDIRECT",
        "redirecttarget": "https://openid.example.net/openid-auth.php?scope=openid&response_type=code&client_id=ABC&redirect_uri=https://wiki.example.org/wiki/Special:OpenIDConnectReturn&state=XYZ123",
        "requests": [
            {
                "id": "OpenIdConnectResponseAuthenticationRequest",
                "metadata": {},
                "required": "required",
                "provider": "OpenID Connect at example.net",
                "account": "",
                "fields": {
                    "code": {
                        "type": "string",
                        "label": "OpenID Code",
                        "help": "OpenID Connect code response"
                    },
                    "state": {
                        "type": "string",
                        "label": "OpenID State",
                        "help": "OpenID Connect state response"
                    },
                }
            }
        ]
    }
}

A kliens a felhasználó böngészőjét várhatóan a megadott redirecttargetre irányítja át.

Az OpenID-biztosító azonosít, és átirányít a wiki Speciális:OpenIDConnectReturn oldalára, amely érvényesíti az OpenID-választ, és átirányít az API-nak küldött első POST-kérésben szereplő, a code és state paraméterekkel kiegészített createreturnurl-re.

A kliens visszakapja a folyamat irányítását e ponton, és létrehozza a következő API-kérését.

Harmadik lépés: Vissza az OpenID-ből.

A kliens visszaküldi a code és state változókat az API-hoz. Az API válasza a kétfaktoros azonosítást lehetővé tevő kiterjesztéssel megkéri a felhasználót a második faktor felállítására.

Eredmény
{
    "createaccount": {
        "status": "UI",
        "message": "Set up two-factor authentication",
        "requests": [
            {
                "id": "TwoFactorAuthenticationRequest",
                "metadata": {
                    "account": "Alice",
                    "secret": "6CO3 2AKV EP2X MIV5"
                },
                "required": "optional",
                "provider": "",
                "account": "",
                "fields": {
                    "2FAInfo": {
                        "type": "null",
                        "label": "A bunch of text describing how to set up two-factor auth.",
                        "help": "Two-factor authentication setup instructions"
                    },
                    "code": {
                        "type": "string",
                        "label": "Code",
                        "help": "Two-factor authentication code"
                    }
                }
            },
            {
                "id": "MediaWiki\\Auth\\ButtonAuthenticationRequest:skip2FASetup",
                "metadata": {},
                "required": "optional",
                "provider": "MediaWiki\\Auth\\ButtonAuthenticationRequest",
                "account": "MediaWiki\\Auth\\ButtonAuthenticationRequest:skip2FASetup",
                "fields": {
                    "skip2FASetup": {
                        "type": "button",
                        "label": "Skip",
                        "help": "Skip two-factor authentication setup"
                    }
                }
            }
        ]
    }
}

Ekkor a kliens a felhasználót új fiók létrehozására és a jelenlegi kód megadására kéri a kétfaktoros bejelentkezéshez használt alkalmazásában, vagy lehetővé teszi a kétfaktoros bejelentkezés felállításának kihagyását. Tegyük fel, hogy a felhasználó 2FA-t használ.

Negyedik lépés: a kétfaktoros azonosítás engedélyezése.

A fióklétrehozás sikerült.

Ha bármely ponton a fióklétrehozás sikertelen, egy FAIL állapotú válasz érkezik vissza egy, a felhasználónak megmutatott message-dzsel.

Lehetséges hibák

Kód Információ
badtoken Érvénytelen fióklétrehozási token
notoken The token parameter must be set.
mustpostparams The following parameter was found in the query string, but must be in the POST body: createtoken.
missingparam At least one of the parameters "createcontinue" és "createreturnurl" is required.
authmanager-create-no-primary A megadott hitelesítő adatok nem használhatók fióklétrehozásra.
noemailcreate Meg kell adnod egy valós e-mail-címet.
invalidemailaddress A megadott e-mail-cím érvénytelen formátumú. Kérlek, adj meg egy érvényes e-mail-címet vagy hagyd üresen azt a mezőt.
badretype A megadott jelszavak nem egyeznek.
userexists A megadott felhasználónév már foglalt.

Kérlek, válassz másikat!

captcha-createaccount-fail Hibás vagy hiányzó ellenőrző kód.
acct_creation_throttle_hit A wiki látogatói ezt az IP-címet használva num fiókot hoztak létre az elmúlt egy napban. Ez a megengedett maximum ezen időtartam alatt, így az erről a címről látogatók jelenleg nem hozhatnak létre újabb fiókokat.

Ha épp egy Wikimédiás témájú eseményen veszel részt, a megoldásért kérlek olvasd el az IP-korlátozás ideiglenes emelése útmutatót.

További megjegyzések

Ha be vagy jelentkezve, a felhasználóneved fel lesz jegyezve a fiók létrehozásakor.

  • Az itt látható kódrészletek végrehajtásakor ne felejtsd el:
    • Ha egy fiók létrejön egy wikin, nem törölhető.
    • Mindig használd a https://test.wikipedia.org/w/api.php-t végpontként, hogy ne hozz létre véletlenül fiókokat valódi wikiken.
  • A MediaWiki oldaladminisztrátorai és kiterjesztésfejlesztői letilthatják ezt az API-funkciót az alábbi sor beillesztésével a konfigurációs fájlba:
$wgAPIModules['createaccount'] = 'ApiDisabled';

Lásd még