Lesson 4: Laravel api auth with wordpress

Somtime you need implement laravel from existing system that have existing users and password then we need to get user from original system instead of create new, for example WordPress.
In the lesson we will know how to implement authentication with existing wordpress database.
First one, Install Sanctum for authentication

composer require laravel/sanctum

Install mikemclin/laravel-wp-password for encrypt wordpress password

composer require mikemclin/laravel-wp-password

Router api.php

Route::post('/login', 'App\Http\Controllers\API\WordpressAuthController@login');
Route::post('/register', 'App\Http\Controllers\API\WordpressAuthController@register');
Route::middleware(['auth:sanctum'])->group(function(){
    Route::get('/user', 'App\Http\Controllers\API\WordpressAuthController@currentUser'); 
});

WordPressController.php file


<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Carbon\Carbon;
use MikeMcLin\WpPassword\Facades\WpPassword;
class WordPressAuthController extends Controller
{
    public function register(Request $request)
    {
        $validatedData = $request->validate([
            'user_nicename' => 'required|max:55',
            'user_email' => 'email|required|unique:wp_users',
            'user_pass' => 'required',
            'user_login' => 'required|unique:wp_users'
        ]);
        $validatedData['user_registered'] = Carbon::now()->toDateTimeString();
        $validatedData['user_pass'] = WpPassword::make($validatedData['user_pass']);

        $user = User::create($validatedData);

        $accessToken = $user->createToken('authToken')->plainTextToken;

        return response(['user' => $user, 'access_token' => $accessToken]);
    }

    public function login(Request $request)
    {
        $loginData = $request->validate([
            'email' => 'email|required',
            'password' => 'required'
        ]);
        $user = User::where('user_email', $request->email)->first();
        // $hash = WpPassword::make($loginData['password']);
        if (!$user || !WpPassword::check($request->password, $user->user_pass)) {
            return response(['msg' => 'Invalid password'], 400);
        }
        $user->id = $user->ID;
        $accessToken = $user->createToken('authToken')->plainTextToken;

        return response(['user' => $user, 'access_token' => $accessToken]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response(['msg' => 'Logout Success']);
    }
}

Model


<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Jetstream\HasTeams;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use HasTeams;
    use Notifiable;
    use TwoFactorAuthenticatable;
    protected $table = 'wp_users';
    protected $primaryKey = 'ID'; // or null
    public $timestamps = false;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_nicename', 'user_login','user_email', 'user_pass','display_name','user_registered','user_pass'
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'user_pass',
        // 'remember_token',
        // 'two_factor_recovery_codes',
        // 'two_factor_secret',
    ];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        // 'user_registered' =&gt; 'datetime',
    ];
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];

}

Leave a Reply

Your email address will not be published. Required fields are marked *