Skip to content

Commit 2993982

Browse files
author
Syed Abidi
committed
✨ Securing Rest API in Laravel 7 with ReactJS | Laravel 7 with Laradock | Tutorial 04
1 parent d0df813 commit 2993982

23 files changed

+6093
-125
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
namespace App\Http\Controllers;
4+
5+
use App\User;
6+
use Illuminate\Http\Request;
7+
use Illuminate\Support\Facades\Auth;
8+
use Illuminate\Support\Facades\Validator;
9+
10+
class AuthController extends Controller
11+
{
12+
public $successStatus = 200;
13+
14+
public function login()
15+
{
16+
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
17+
$user = Auth::user();
18+
$success['token'] = $user->createToken('ReactWithLaravel')->accessToken;
19+
20+
return response()->json(['success' => $success], $this->successStatus);
21+
} else {
22+
return response()->json(['error' => 'Unauthorised'], 401);
23+
}
24+
}
25+
26+
public function register(Request $request)
27+
{
28+
$validator = Validator::make($request->all(), [
29+
'name' => 'required',
30+
'email' => 'required|email',
31+
'password' => 'required',
32+
'c_password' => 'required|same:password',
33+
]);
34+
35+
if ($validator->fails()) {
36+
return response()->json(['error' => $validator->errors()], 401);
37+
}
38+
39+
$input = $request->all();
40+
$input['password'] = bcrypt($input['password']);
41+
$user = User::create($input);
42+
$success['token'] = $user->createToken('ReactWithLaravel')->accessToken;
43+
$success['name'] = $user->name;
44+
45+
return response()->json(['success' => $success], $this->successStatus);
46+
}
47+
}

app/Providers/AuthServiceProvider.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
66
use Illuminate\Support\Facades\Gate;
7+
use Laravel\Passport\Passport;
78

89
class AuthServiceProvider extends ServiceProvider
910
{
@@ -24,7 +25,7 @@ class AuthServiceProvider extends ServiceProvider
2425
public function boot()
2526
{
2627
$this->registerPolicies();
27-
28+
Passport::routes();
2829
//
2930
}
3031
}

app/User.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
use Illuminate\Contracts\Auth\MustVerifyEmail;
66
use Illuminate\Foundation\Auth\User as Authenticatable;
77
use Illuminate\Notifications\Notifiable;
8+
use Laravel\Passport\HasApiTokens;
89

910
class User extends Authenticatable
1011
{
11-
use Notifiable;
12+
use Notifiable, HasApiTokens;
1213

1314
/**
1415
* The attributes that are mass assignable.

composer.json

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"fruitcake/laravel-cors": "^1.0",
1414
"guzzlehttp/guzzle": "^6.3",
1515
"laravel/framework": "^7.0",
16+
"laravel/passport": "^9.3",
1617
"laravel/tinker": "^2.0",
1718
"laravel/ui": "^2.0"
1819
},

0 commit comments

Comments
 (0)