😆Tạo API và Authenticate nhanh chóng với package Laravel Sanctum (ok)
https://viblo.asia/p/tao-api-va-authenticate-nhanh-chong-voi-package-laravel-sanctum-eW65G1EJZDO
Last updated
https://viblo.asia/p/tao-api-va-authenticate-nhanh-chong-voi-package-laravel-sanctum-eW65G1EJZDO
Last updated
Tham khảo: https://dev.to/shanisingh03/laravel-api-authentication-using-laravel-sanctum-edg
C:\xampp\htdocs\testauth\routes\api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/login', [AuthController::class,'login']);
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/users', [UserController::class,'index']);
});
C:\xampp\htdocs\testauth\app\Http\Controllers\AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function login(Request $request)
{
try {
$request->validate([
'email' => 'email|required',
'password' => 'required'
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials)) {
return response()->json([
'status_code' => 500,
'message' => 'Unauthorized'
]);
}
$user = User::where('email', $request->email)->first();
if (!Hash::check($request->password, $user->password, [])) {
throw new \Exception('Error in Login');
}
$tokenResult = $user->createToken('authToken')->plainTextToken;
return response()->json([
'status_code' => 200,
'access_token' => $tokenResult,
'token_type' => 'Bearer',
]);
} catch (\Exception $error) {
return response()->json([
'status_code' => 500,
'message' => 'Error in Login',
'error' => $error,
]);
}
}
}
C:\xampp\htdocs\testauth\app\Http\Controllers\UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
return response()->json([
'data' => User::all(),
]);
}
}
C:\xampp\htdocs\testauth\app\Http\Controllers\AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function login(Request $request)
{
try {
$request->validate([
'email' => 'email|required',
'password' => 'required'
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials)) {
return response()->json([
'status_code' => 500,
'message' => 'Unauthorized'
]);
}
$user = User::where('email', $request->email)->first();
if (!Hash::check($request->password, $user->password, [])) {
throw new \Exception('Error in Login');
}
$tokenResult = $user->createToken('authToken')->plainTextToken;
return response()->json([
'status_code' => 200,
'access_token' => $tokenResult,
'token_type' => 'Bearer',
]);
} catch (\Exception $error) {
return response()->json([
'status_code' => 500,
'message' => 'Error in Login',
'error' => $error,
]);
}
}
/**
* Create User
* @param Request $request
* @return User
*/
public function createUser(Request $request)
{
try {
//Validated
$validateUser = Validator::make(
$request->all(),
[
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required'
]
);
if ($validateUser->fails()) {
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
return response()->json([
'status' => true,
'message' => 'User Created Successfully',
'token' => $user->createToken("authToken")->plainTextToken
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
}