namespace AppHttpControllers;
use AppModelsAdmin;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesFile;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
use TymonJWTAuthFacadesJWTAuth;
class AdminAuthController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (! $token = auth('admin')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function register(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:admins',
'password' => 'required|string|min:6',
]);
$admin = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = JWTAuth::fromUser($admin);
return response()->json(compact('admin', 'token'), 201);
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('admin')->factory()->getTTL() * 60
]);
}
public function fetch(){
// Check if the admin is authenticated
if (! Auth::guard('admin')->check()) {
return response()->json(['error' => 'Unauthorized'], 401);
} else {
// If authenticated, proceed
$data = Auth::guard('admin')->user(); // Use guard to get the admin data
return response()->json($data);
}
}
}
namespace AppModels;
use IlluminateFoundationAuthUser as Authenticatable; // Important!
use IlluminateNotificationsNotifiable;
use TymonJWTAuthContractsJWTSubject; // For JWT support
class Admin extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
// This is needed for JWT
public function getJWTIdentifier()
{
return $this->getKey();
}
}
}
this are the code by help to add the jwt auth into you laravel project