Create Custom Passport Authentication in Laravel Framework

13-03-2020

config/auth.php file

'guards' => [
    'crm_account' => [
    'provider' => 'crm_accounts',
    'driver' => 'passport',
    'hash' => true,
    ],
],

'providers' => [
    'crm_accounts' => [
    'driver' => 'eloquent',
    'model' => App\Models\CrmAccount::class,
    'table' => 'crm_accounts',
    ],
],

CrmAccount Model:

namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class CrmAccount extends Authenticatable
{
    use HasApiTokens;
    public $fillable = [
    'id',
    'name',
    ]
    .
    .
    .
    .
}

routes/api.php

Route::prefix( "/users" )->middleware(  ['auth:crm_account'] )->group( function () {
    Route::get('/','UserController@index');
    Route::post('forget-password','UserController@forgetPassword');
});

Controller Class

class UserController extends Controller {
    public function login(Request $request)
    {
        $input = $request->all();
        $crmAccount = CrmAccount::where('username', $input['username'])
        ->where('password', $input['password'])->first();
        $token = $crmAccount->createToken($crmAccount->name)->accessToken;
        return Response::json(ResponseUtil::makeResponse('', ['access_token' => $token]));
    }
    public function forgetPassword(Request $request)
    {
        
        $crmAccount=Auth::user();
        $password= StringUtil::generateRandomDigit(8);
        $message = 'Şifreniz başarıyla oluşturuldu. Giriş yapmak için şifreniz: ' . $password;
        SmsHelper::sendViaPostaGuvercini($crmAccount->phone, $message);
        $crmAccount->password=crypt($password, 'ib_salt');
        $crmAccount->save();
        return Response::json(ResponseUtil::makeResponse('', ['access_token' => $token]));
    }
}

When you call Auth::user() function, you will get logged user.

© 2019 All rights reserved. Codesenior.COM