واجهة برمجة التطبيقات:إنشاء حساب

From mediawiki.org
This page is a translated version of the page API:Account creation and the translation is 100% complete.
إصدار ميدياويكي:
1.27
توثق هذه الصفحة واجهة برمجة التطبيقات لإنشاء حساب بدءا من نسخة ميدياويكي 1.27. أما التوثيق الخاص بواجهة برمجة التطبيقات كما هي في النسخ السابقة متوفر هنا: Api:Account creation/pre-1.27 .

توثيق واجهة برمجة التطبيقات


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.

إنشاء حساب

هذه العملية تنقسم إلى ثلاثة أقسام:

  1. استدعاء الحقول من API:Authmanagerinfo والإشارة من واجهة برمجة التطبيقات:Tokens .
  2. إرسال طلب POST مستخدما الإشارة المجلوبة مع معلومات المستخدم وحقول أخرى، ورد معرف الموارد الموحد إلى واجهة برمجة التطبيقات.
  3. التعامل مع الرد، الذي قد يتطلب طلبات POST أخرى لإضافة مزيد من المعلومات.

مثال 1: عملية على موقع ويكي لا يحتوي على امتدادات تصديق خاصة

تكون الأمور على موقع ويكي لا يستخدم امتدادات تصديق خاصة أيسر وأقصر زمنا. لو كان كودك البرمجي يعلم ما هي الحقول المطلوبة، قد يتخطى الاستدعاء من API:Authmanagerinfo ويفترض ما هي الحقول المطلوبة (أي اسم المستخدم وكلمة المرور وإعادة إدخال كلمة المرور وعنوان البريد الإلكتروني وربما يطلب الاسم الحقيقي).

لو كنت تنشئ حساب لشخص آخر، سوف تحتاج لتحديد سبب ذلك عن طريق إضافة متغير reason إلى طلب POST. يمكنك أيضا استخدام المتغير mailpassword بدلا من المتغيرات password و retype كي ترسل برمجيات ميدياويكي إلى المستخدم الجديد كلمة مرور مؤقتة عن طريق البريد الإلكتروني.

طلب POST

النتيجة

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

عينة من الكود البرمجي

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: عملية على موقع ويكي يستخدم امتداد CAPTCHA

لاحظ أن الخطوة الأولى تاليا، إن كنت ترغب، يمكن تقسيمها إلى خطوتين: خطوة أولى لجلب الحقول المتاحة من API:Authmanagerinfo وخطوة أخرى لجلب الإشارة من واجهة برمجة التطبيقات:Tokens .

<span id="First_step:_Fetch_fields_available_from_API:Authmanagerinfo _and_token_from_واجهة برمجة التطبيقات:Tokens ">

الخطوة الأولى: جلب الحقول المتاحة من API:Authmanagerinfo والإشارة من واجهة برمجة التطبيقات:Tokens

النتيجة
{
    "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+\\"
        }
    }
}

الخطوة الثانية: إرسال طلب POST مع إشارة إنشاء حساب ومعلومات المستخدم ورد معرف الموارد الموحد

النتيجة
{
    "createaccount": {
        "status": "PASS",
        "username": "Zane"
    }
}

عينة من الكود البرمجي

لاحظ أن هذه العينة من الكود البرمجي تفصل بين طلبي API:Authmanagerinfo و واجهة برمجة التطبيقات:Tokens ، وتفترض بوجه عام وجود CAPTCHA ولا تعقيدات أخرى.

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: إنشاء حساب على موقع ويكي يستخدم CAPTCHA وتفعيل كلا من امتداد OpenID وامتداد التصديق باستخدام عاملين اثنين

<span id="First_step:_Fetch_fields_available_from_API:Authmanagerinfo _and_token_from_واجهة برمجة التطبيقات:Tokens ">

الخطوة الأولى: جلب الحقول المتاحة من API:Authmanagerinfo والإشارة من واجهة برمجة التطبيقات:Tokens

خطوة جلب API:Authmanagerinfo و واجهة برمجة التطبيقات:Tokens بوجه عام لا تتغير كثيرا عن المثال السابق، ولهذا السبب لن نكررها هنا. سوف تشتمل قائمة الطلبات المردودة من API:Authmanagerinfo على تعريفات لكلا من امتداد CAPTCHA وامتداد OpenID.

الخطوة الثانية: الإجابة على CAPTCHA واختيار تصديق OpenID.

النتيجة
{
    "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"
                    },
                }
            }
        ]
    }
}

نتوقع من الجهاز العميل إعادة توجيه متصفح المستخدم إلى صفحة redirecttarget المحددة.

سيتولى مقدم خدمة OpenID التصديق ومن ثم إعادة التوجيه إلى صفحة Special:OpenIDConnectReturn على موقع الويكي، التي سوف تتولى التثبت من رد OpenID ومن ثم إعادة التوجيه إلى createreturnurl شريطة أن تضاف المتغيرات code و state إلى طلب POST الأول المقدم إلى واجهة برمجية التطبيقات.

ستنتقل السيطرة على العملية إلى جهاز العميل مرة أخرى عند هذه الخطوة ومن ثم يرسل طلب واجهة برمجة التطبيقات التالي.

الخطوة الثالثة: رجوعا من OpenID.

سوف يرسل جهاز العميل كلا من code و state إلى واجهة برمجة التطبيقات. سيعرض رد واجهة برمجة التطبيقات امتداد المصادقة باستخدام عاملين اثنين الذي يحث المستخدم على إعداد العامل الثاني للمصادقة.

النتيجة
{
    "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"
                    }
                }
            }
        ]
    }
}

سيتولى الجهاز العميل إشعار المستخدم ليعد حساب جديد في تطبيق التصديق باستخدام عاملين اثنين الذي يستخدمه وإدخال الكود الرقمي الحالي، أو يسمج للمستخدم أن يتخطى إعداد المصادقة باستخدام عاملين اثنين. لم لا نفترض أن المستخدم سوف يعد التصديق باستخدام عاملين اثنين.

الخطوة الرابعة: إعداد التصديق باستخدام عاملين اثنين.

تكللت عملية إنشاء حساب بالنجاح.

لو حدث في أي خطوة وفشلت عملية إنشاء الحساب، سوف يعرض رد مع الحالة FAIL وكذلك message تعرض على المستخدم.

الأخطاء المحتملة

الكود معلومات
badtoken إشارة إنشاء حساب غير صالحة
notoken يجب تعيين الوسيط token.
mustpostparams تم العثور على الوسائط في سلسلة الاستعلام، ولكن يجب أن يكون في نص POST: createtoken.
missingparam مطلوب واحد على الأقل من الوسائط "createcontinue" و "createreturnurl".
authmanager-create-no-primary الاعتمادات الموفرة لم يمكن استخدامها لإنشاء الحساب.
noemailcreate عليك تقديم عنوان بريد إلكتروني صالح
invalidemailaddress لا يمكن قبول عنوان البريد الإلكتروني حيث تبدو صيغته خاطئة.

ضع عنوانا مضبوطا أو أفرغ هذا الحقل.

badretype كلمات السر التي أدخلتها لا تتطابق.
userexists اسم المستخدم الذي تم إدخاله مستعمل بالفعل.

الرجاء اختيار اسم مختلف.

captcha-createaccount-fail كابتشا غير صحيحة أو مفقودة.
acct_creation_throttle_hit قام زوار هذا الويكي باستخدام عنوان الآيبي الخاص بك بإنشاء 1 حساب في اليوم الأخير، وهو الحد الأقصى المسموح به في هذه الفترة الزمنية،

نتيجة لذلك; لا يمكن للزوار الذين يستخدمون عنوان الآيبي هذا إنشاء المزيد من الحسابات في الوقت الحالي.

إذا كنت في حدث تساهم فيه مشاريع ويكيميديا، يُرجَى الاطلاع على طلب رفع مؤقت لقبعة الآيبي للمساعدة في حل هذه المشكلة.

ملاحظات إضافية

لو كنت مسجل الدخول، سوف يسجل اسم مستخدمك أيضا حينما تنشئ حساب.

  • بينما تنفذ قصاصات الكود البرمجي المبينة في هذه الصفحة، تذكر ما يلي:
    • حال إنشاء حساب على موقع ويكي، لا يمكن محو هذا الحساب.
    • استخدم دائما https://test.wikipedia.org/w/api.php ليكون نقطة النهاية، حتى لا تنشئ حسابات دون قصد على مواقع ويكي الإنتاج.
  • يمكن لكلا من إداري موقع و مطوري امتدادات ميدياويكي تعطيل سمة واجهة برمجة التطبيقات هذه عن طريق إضافة السطر التالي إلى ملف الضبط:
$wgAPIModules['createaccount'] = 'ApiDisabled';

انظر أيضا