Web Hosting

Membangun Aplikasi Manajemen Mahasiswa dengan Lumen, React, dan JWT: Panduan Praktis untuk Autentikasi dan Relasi Data

Berikut panduan sederhana untuk membangun aplikasi manajemen mahasiswa menggunakan Lumen (untuk API), React (sebagai frontend), dan JWT (untuk autentikasi), dengan studi kasus melibatkan dua tabel: Mahasiswa dan Kelas. Simak langkah-langkahnya, dan yuk mulai bikin aplikasimu sendiri!

Langkah 1: Setup Proyek Lumen

  1. Instal Lumen: Jika Anda belum memiliki Lumen terpasang, instal dengan perintah berikut:
    composer create-project --prefer-dist laravel/lumen lumen-api
  2. Ubah Folder: Setelah proses instalasi selesai, silahkan ketik
    cd lumen-api

Langkah 2: Tambahkan JWT Auth ke Proyek

  1. Install JWT Auth: Untuk menambahkan JWT autentikasi, jalankan:
    composer require tymon/jwt-auth
  2. Salin file .env: untuk salin file .env silahkan ketikan kode berikut:
    cp .env.example .env
  3. Generate Secret key dengan perintah berikut:
    php artisan jwt:secret
  4. Tambahkan JWT Config ke bootstrap/app.php:
    $app->configure('auth');
    $app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

Langkah 3: Buat dan Konfigurasi Tabel users

  1. Buat Migration untuk Tabel users: Buat file migration untuk tabel users, kelas dan mahasiswa:
    php artisan make:migration create_users_table --create=users
    php artisan make:migration create_kelas_table --create=kelas
    php artisan make:migration create_mahasiswa_table --create=mahasiswa
  2. Edit Migration File: Di dalam file migration (database/migrations/yyyy_mm_dd_create_nama_tabel_table.php), tambahkan kolom berikut:
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    return new class extends Migration {
        /**
         * Run the migrations.
         */
        public function up(): void
        {
            Schema::create('users', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('email')->unique();
                $table->string('password');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         */
        public function down(): void
        {
            Schema::dropIfExists('users');
        }
    };

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    return new class extends Migration {
        /**
         * Run the migrations.
         */
        public function up(): void
        {
            Schema::create('kelas', function (Blueprint $table) {
                $table->id();
                $table->string('nama_kelas');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         */
        public function down(): void
        {
            Schema::dropIfExists('kelas');
        }
    };

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    return new class extends Migration {
        /**
         * Run the migrations.
         */
        public function up(): void
        {
            Schema::create('mahasiswa', function (Blueprint $table) {
                $table->id();
                $table->string('nim')->unique();
                $table->string('nama');
                $table->string('email')->unique();
                $table->foreignId('kelas_id')->constrained('kelas');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         */
        public function down(): void
        {
            Schema::dropIfExists('mahasiswa');
        }
    };
  3. Jalankan Migration: Untuk membuat tabel users, kelas dan mahasiswa di database, jalankan:
    php artisan migrate

Langkah 4: Buat Model User dan Implementasikan JWTSubject

  1. Buat Model User: Buat file User.php di app/Models/:
    namespace App\Models;
    use Illuminate\Auth\Authenticatable;
    use Illuminate\Database\Eloquent\Model;
    use Tymon\JWTAuth\Contracts\JWTSubject;
    use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
    class User extends Model implements AuthenticatableContract, JWTSubject
    {
        use Authenticatable;
        protected $fillable = [
            'name', 'email', 'password',
        ];
        public function getJWTIdentifier()
        {
            return $this->getKey();
        }
        public function getJWTCustomClaims()
        {
            return [];
        }
    }
  2. Buat Model Kelas: Buat file Kelas.php di app/Models/:
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Kelas extends Model
    {
        protected $fillable = ['nama_kelas'];
    
        public function mahasiswas()
        {
            return $this->hasMany(Mahasiswa::class);
        }
    }
  3. Buat Model Mahasiswa: Buat file Mahasiswa.php di app/Models/:
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Mahasiswa extends Model
    {
        protected $table = 'mahasiswa';
        protected $fillable = ['nim', 'nama', 'email', 'kelas_id'];
    
        public function kelas()
        {
            return $this->belongsTo(Kelas::class);
        }
    }

Langkah 5: Konfigurasi Middleware dan Guard

  1. Konfigurasi Auth Guard di File Config: Buat file konfigurasi config/auth.php (jika belum ada):
    return [
        'defaults' => [
            'guard' => 'api',
        ],
        'guards' => [
            'api' => [
                'driver' => 'jwt',
                'provider' => 'users',
            ],
        ],
        'providers' => [
            'users' => [
                'driver' => 'eloquent',
                'model' => App\Models\User::class,
            ],
        ],
    ];
    
  2. Tambahkan Middleware Autentikasi JWT di bootstrap/app.php:
    $app->routeMiddleware([
        'auth' => App\Http\Middleware\Authenticate::class,
    ]);
  3. Buat Middleware Autentikasi di app/Http/Middleware/Authenticate.php:
    namespace App\Http\Middleware;
    use Closure;
    use Illuminate\Contracts\Auth\Factory as Auth;
    class Authenticate
    {
        protected $auth;
        public function __construct(Auth $auth)
        {
            $this->auth = $auth;
        }
        public function handle($request, Closure $next, $guard = null)
        {
            if ($this->auth->guard($guard)->guest()) {
                return response('Unauthorized.', 401);
            }
            return $next($request);
        }
    }

Langkah 6: Buat Controller untuk Autentikasi (Register & Login)

  1. Buat AuthController di app/Http/Controllers/AuthController.php:
    namespace App\Http\Controllers;
    use App\Models\User;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Hash;
    use Tymon\JWTAuth\Facades\JWTAuth;
    class AuthController extends Controller
    {
        public function register(Request $request)
        {
            $this->validate($request, [
                '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 = JWTAuth::fromUser($user);
            return response()->json(compact('user', 'token'), 201);
        }
        public function login(Request $request)
        {
            $credentials = $request->only('email', 'password');
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
            return response()->json(compact('token'));
        }
        public function me()
        {
            return response()->json(auth()->user());
        }
    }

Langkah 7: Tambahkan Route untuk Autentikasi

  1. Tambahkan Route Autentikasi di routes/web.php:
    $router->group(['prefix' => 'auth'], function () use ($router) {
        $router->post('register', 'AuthController@register');
        $router->post('login', 'AuthController@login');
        $router->get('me', ['middleware' => 'auth', 'uses' => 'AuthController@me']);
    });

Langkah 8: Testing API

  1. Jalankan Server Lumen: Jalankan server Lumen:
    php -S localhost:8000 -t public
        
  2. Test Register: Gunakan POST ke http://localhost:8000/auth/register:
    {
        "name": "John Doe",
        "email": "johndoe@example.com",
        "password": "password123",
        "password_confirmation": "password123"
    }
  3. Test Login: Kirim POST ke http://localhost:8000/auth/login:
    {
        "email": "johndoe@example.com",
        "password": "password123"
    }
  4. Test Akses Terproteksi: Kirim GET ke http://localhost:8000/auth/me dengan Authorization Header:
    Authorization: Bearer 

Setelah mengikuti langkah-langkah di atas, aplikasi Lumen Anda akan memiliki sistem autentikasi berbasis JWT yang berfungsi sepenuhnya.

Rendi Julianto

Experienced programming developer with a passion for creating efficient, scalable solutions. Proficient in Python, JavaScript, and PHP, with expertise in web development, API integration, and software optimization. Adept at problem-solving and committed to delivering high-quality, user-centric applications.

Posting Komentar (0)
Lebih baru Lebih lama