Skip to content

Instantly share code, notes, and snippets.

@LarryEitel
Forked from nasrulhazim/01.md
Created August 21, 2018 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LarryEitel/d89b328990725c88eb65eec231f1e3a8 to your computer and use it in GitHub Desktop.
Save LarryEitel/d89b328990725c88eb65eec231f1e3a8 to your computer and use it in GitHub Desktop.
Laravel Default API Login

Setup

Migration

Create new migration script:

php artisan make:migration add_api_token --table=users

Open up the migration script just created and add the following:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddApiToken extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->char('api_token', 60)->nullable()->after('password');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('api_token');
        });
    }
}

Then do the migration:

php artisan migrate

Model

Update the app/User.php $fillable property:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'api_token',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Login & Logout Route

Next, setup a simple route to login & logout form API endpoints:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
 */
 
/* Setup CORS */
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

// Route::post('login', 'Auth\LoginController@ApiLogin');
Route::post('login', function (Request $request) {
    
    if (auth()->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
        // Authentication passed...
        $user = auth()->user();
        $user->api_token = str_random(60);
        $user->save();
        return $user;
    }
    
    return response()->json([
        'error' => 'Unauthenticated user',
        'code' => 401,
    ], 401);
});

Route::middleware('auth:api')->post('logout', function (Request $request) {
    
    if (auth()->user()) {
        $user = auth()->user();
        $user->api_token = null; // clear api token
        $user->save();

        return response()->json([
            'message' => 'Thank you for using our application',
        ]);
    }
    
    return response()->json([
        'error' => 'Unable to logout user',
        'code' => 401,
    ], 401);
});

Test

Use Postman to test:

Login

  • API Endpoint: http://domain/api/login
  • HTTP Method: POST
  • Headers: Accept: application/json
  • Body
    • email [your-login]
    • password [your-password]
  • Response: You should receive your details

Logout

  • API Endpoint: http://domain/api/logout
  • HTTP Method: POST
  • Headers:
    • Accept: application/json
    • `Authorization: Bearer [login-token]
  • Body
    • email [your-login]
    • password [your-password]
  • Reponse: You should receive logout message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment