DeveloperBreeze

في هذا الدرس، سنقوم بإنشاء واجهة برمجة تطبيقات (API) متقدمة باستخدام Laravel، وسنستخدم Laravel Passport لإضافة التوثيق (authentication) القائم على الـ OAuth2. هذا النوع من التوثيق يوفر أمانًا أعلى ويسمح بتصديق المستخدمين عبر رموز الوصول (access tokens).

متطلبات الدرس:

  • بيئة Laravel مثبتة (Laravel 9 أو أحدث)
  • Composer
  • MySQL أو SQLite
  • Postman لاختبار الـ API

1. إعداد مشروع Laravel

أولاً، قم بإنشاء مشروع Laravel جديد:

composer create-project --prefer-dist laravel/laravel laravel-passport-api

ثم توجه إلى مجلد المشروع:

cd laravel-passport-api

2. إعداد قاعدة البيانات

افتح ملف .env وعدل إعدادات قاعدة البيانات لتتناسب مع بيئتك:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=passport_api
DB_USERNAME=root
DB_PASSWORD=

ثم قم بإنشاء قاعدة البيانات:

php artisan migrate

3. تثبيت Laravel Passport

Laravel Passport هو مكتبة رسمية توفر أداة كاملة للتوثيق عبر OAuth2. لتثبيته، استخدم هذا الأمر:

composer require laravel/passport

ثم قم بترحيل البيانات الخاصة بـ Passport:

php artisan migrate

بعد ذلك، قم بتثبيت مفاتيح التشفير التي يستخدمها Passport:

php artisan passport:install

4. إعداد Passport في التطبيق

افتح ملف app/Providers/AuthServiceProvider.php وأضف Passport إلى إعدادات الحماية:

use Laravel\Passport\Passport;

public function boot()
{
    $this->registerPolicies();

    Passport::routes();
}

ثم تأكد من تحديث config/auth.php لضبط محرك التوثيق الخاص بـ Passport:

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

5. إنشاء واجهة API للتسجيل وتسجيل الدخول

الآن، لنقم بإنشاء بعض النقاط النهائية (endpoints) لواجهة الـ API، بما في ذلك التسجيل وتسجيل الدخول.

أولاً، أنشئ وحدة تحكم (Controller) لإدارة التوثيق:

php artisan make:controller AuthController

ثم أضف الطرق التالية إلى ملف AuthController.php:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    // تسجيل مستخدم جديد
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $token = $user->createToken('LaravelPassportAPI')->accessToken;

        return response()->json(['token' => $token], 201);
    }

    // تسجيل الدخول
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            $token = $user->createToken('LaravelPassportAPI')->accessToken;

            return response()->json(['token' => $token], 200);
        } else {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }
    }

    // الحصول على بيانات المستخدم
    public function user()
    {
        return response()->json(Auth::user(), 200);
    }
}

6. إضافة المسارات (Routes)

افتح ملف routes/api.php وأضف المسارات الخاصة بالتسجيل وتسجيل الدخول:

use App\Http\Controllers\AuthController;

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

// مسار للحصول على بيانات المستخدم المسجل
Route::middleware('auth:api')->get('/user', [AuthController::class, 'user']);

7. اختبار واجهة الـ API باستخدام Postman

الآن يمكنك اختبار واجهة الـ API باستخدام Postman.

  1. التسجيل:
  • الطريقة: POST
  • العنوان (URL): http://localhost:8000/api/register
  • الجسم (Body):
   {
       "name": "اسم المستخدم",
       "email": "email@example.com",
       "password": "كلمة المرور",
       "password_confirmation": "تأكيد كلمة المرور"
   }
  1. تسجيل الدخول:
  • الطريقة: POST
  • العنوان (URL): http://localhost:8000/api/login
  • الجسم (Body):
   {
       "email": "email@example.com",
       "password": "كلمة المرور"
   }
  1. الحصول على بيانات المستخدم:
  • الطريقة: GET
  • العنوان (URL): http://localhost:8000/api/user
  • الرأس (Header):
  • Authorization: Bearer <token>

8. الخاتمة

بهذا نكون قد أنشأنا واجهة API متقدمة باستخدام Laravel Passport للتوثيق. يمكنك الآن استخدام هذا الأساس لبناء واجهة برمجة تطبيقات أكثر تعقيدًا تشمل مزيدًا من العمليات مثل إدارة الملفات الشخصية، التحديثات، وحذف المستخدمين.

مواضيع متقدمة للتطوير:

  • إضافة الأدوار والصلاحيات (Roles and Permissions)
  • حماية النقاط النهائية باستخدام مختلف أساليب التوثيق
  • إدارة تجديد رموز الوصول (refresh tokens)

إذا كنت ترغب في التوسع، يمكنك كتابة دروس إضافية حول كيفية تحسين هذه الواجهة، مثل تحسين إدارة المستخدمين والأدوار، أو كيفية إنشاء نظام إشعارات متكامل.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

Use Infura when you need to interact with the Ethereum blockchain in real-time. Infura allows you to send transactions, deploy contracts, and interact with smart contracts. It is essential for decentralized applications (dApps) and any use case where you need to write to the blockchain.

const ethers = require('ethers');

// Replace with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Replace with your wallet's private key
const privateKey = 'YOUR_PRIVATE_KEY';

// Create a wallet instance and connect it to Infura
const wallet = new ethers.Wallet(privateKey, infuraProvider);

// Replace with the recipient's Ethereum address
const recipientAddress = '0xRecipientEthereumAddress';

// Amount to send (in Ether)
const amountInEther = '0.01';

async function sendTransaction() {
  try {
    const tx = {
      to: recipientAddress,
      value: ethers.utils.parseEther(amountInEther),
      gasLimit: 21000, // Gas limit for a basic transaction
      gasPrice: await infuraProvider.getGasPrice() // Get current gas price from Infura
    };

    // Send the transaction
    const transaction = await wallet.sendTransaction(tx);
    console.log('Transaction Hash:', transaction.hash);

    // Wait for the transaction to be mined
    const receipt = await transaction.wait();
    console.log('Transaction Confirmed:', receipt);
  } catch (error) {
    console.error('Error sending transaction:', error);
  }
}

sendTransaction();

Oct 24, 2024
Read More
Tutorial

Creating Personal Access Tokens for a Custom Model in Laravel

Let's assume you have a custom model called Customer. We'll configure this model to issue personal access tokens.

use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Customer extends Authenticatable
{
    use HasApiTokens;

    protected $fillable = ['name', 'email'];

    // Define the relationship with tokens
    public function tokens()
    {
        return $this->morphMany(\Laravel\Sanctum\PersonalAccessToken::class, 'tokenable');
    }
}

Oct 24, 2024
Read More
Tutorial
javascript

بناء تطبيق ويب متقدم باستخدام React.js وNode.js

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
});

// Hash the password before saving
UserSchema.pre('save', async function (next) {
    if (!this.isModified('password')) return next();
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
});

module.exports = mongoose.model('User', UserSchema);

1. إنشاء مشروع React:

Sep 27, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'body'];
}

React will interact with Laravel’s backend through API endpoints. We'll create a controller and define routes for CRUD operations.

Aug 14, 2024
Read More
Tutorial
python

Advanced Pybit Tutorial: Managing Leverage, Stop-Loss Orders, Webhooks, and More

Managing open orders and closing positions is essential for effective trading. Pybit makes it straightforward to close orders.

Use the following function to close an open order:

Aug 14, 2024
Read More
Tutorial
python

A Beginner's Guide to Pybit: Interacting with the Bybit API

Use the following code to fetch the latest price of BTC/USD:

   def get_latest_price(symbol):
       response = session.latest_information_for_symbol(symbol=symbol)
       price = response['result'][0]['last_price']
       return price

   latest_price = get_latest_price('BTCUSD')
   print(f"Latest BTC/USD price: {latest_price}")

Aug 14, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

pip install Flask
mkdir flask_rest_api
cd flask_rest_api

Aug 03, 2024
Read More
Code
bash

Various cURL Examples for API Interactions

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Bybit Futures API Integration Using ccxt Library with Error Handling

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!