Skip to content

add simple token auth for api (random string) #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions app/Http/Controllers/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
Expand Down Expand Up @@ -36,4 +38,64 @@ public function __construct()
{
$this->middleware('guest')->except('logout');
}

/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function login(Request $request)
{
$this->validateLogin($request);

// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);

return $this->sendLockoutResponse($request);
}

if ($this->attemptLogin($request)) {
$user = $this->guard()->user();
$user->generateToken();

if ($request->ajax())
return response()->json([
'data' => $user->toArray(),
]);
else
return $this->sendLoginResponse($request);
}

// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);

return $this->sendFailedLoginResponse($request);
}

public function logout(Request $request)
{
$user = Auth::user();

if ($user) {
$user->api_token = null;
$user->save();
}

$this->guard()->logout();

$request->session()->invalidate();

if ($request->ajax())
return response()->json(['data' => 'User logged out.'], 200);
else
return redirect('/');
}
}
16 changes: 16 additions & 0 deletions app/Http/Controllers/Auth/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
Expand Down Expand Up @@ -69,4 +70,19 @@ protected function create(array $data)
'password' => Hash::make($data['password']),
]);
}

/**
* The user has been registered.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function registered(Request $request, $user)
{
$user->generateToken();

if ($request->ajax())
return response()->json(['data' => $user->toArray()], 201);
}
}
8 changes: 8 additions & 0 deletions app/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,12 @@ class User extends Authenticatable
protected $hidden = [
'password', 'remember_token',
];

public function generateToken()
{
$this->api_token = str_random(60);
$this->save();

return $this->api_token;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

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

class AddsApiTokenToUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 60)->unique()->nullable();
});
}

public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['api_token']);
});
}
}
28 changes: 28 additions & 0 deletions database/seeds/CompaniesSeeder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

use Illuminate\Database\Seeder;
use App\Company;

class CompaniesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Company::truncate();

$faker = \Faker\Factory::create();

for ($i = 0; $i < 10; $i++) {
Company::create([
'name' => $faker->company,
'address' => $faker->address,
'website' => $faker->domainName,
'email' => $faker->email,
]);
}
}
}
2 changes: 1 addition & 1 deletion database/seeds/DatabaseSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ class DatabaseSeeder extends Seeder
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
$this->call(CompaniesSeeder::class);
}
}
2 changes: 2 additions & 0 deletions resources/assets/js/bootstrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
*/

let token = document.head.querySelector('meta[name="csrf-token"]');
let apiToken = document.head.querySelector('meta[name="api-token"]');

if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + apiToken.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
Expand Down
1 change: 1 addition & 0 deletions resources/views/layouts/app.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="api-token" content="{{ Auth::user()->api_token ?? "" }}">

<title>{{ config('app.name', 'Laravel') }}</title>

Expand Down
2 changes: 1 addition & 1 deletion routes/api.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?php

Route::group(['prefix' => '/v1', 'namespace' => 'Api\V1', 'as' => 'api.'], function () {
Route::group(['prefix' => '/v1', 'namespace' => 'Api\V1', 'as' => 'api.', 'middleware' => 'auth:api'], function () {
Route::resource('companies', 'CompaniesController', ['except' => ['create', 'edit']]);
});
Empty file modified storage/logs/.gitignore
100644 → 100755
Empty file.