Laravel rest api

Egy rest api-t készítünk, authentikációval.

Json web token-es authentikációt fogunk használni. Tegyük fel a következő csomagot:
 
# composer require tymon/jwt-auth

A routing-nál a routes/api.php -ban csinálhatunk group-okat és a jwt middleware-eket felhasználva minden végpontunk headerjébe belekerül a jtw token:
 
Route::group(['middleware' => ['jwt.verify', 'jwt.refresh', 'cors']], function () {

Az app/Http/Middleware/JwtMiddleware.php tartalma:
 
<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
                return response()->json(['status' => 'Token is Invalid', 'error' => ['message' => 'Token is Invalid']], 401);
            } else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
                return response()->json(['status' => 'Token is Expired', 'error' => ['message' => 'Token is Expired']], 401);
            } else {
                return response()->json(['status' => 'Authorization Token not found', 'error' => ['message' => 'Authorization Token not found']], 401);
            }
        }
        return $next($request);
    }
}

Az app\Http\Kernel.php fájlban bekell állítanunk a routeMiddleware-ben a jwt-t és a cors-ot is:
 
    protected $routeMiddleware = [
        ...
        'jwt.verify' => \App\Http\Middleware\JwtMiddleware::class,
        'cors' => \Barryvdh\Cors\HandleCors::class
    ];

Az AuthController tartalma, authentikáció és új token kérés:
 
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function authenticate(Request $request)
    {
        $credentials = $request->only('username', 'password');

        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => ["message"=>'invalid_credentials']], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        return response()->json(['token' => $token, 'expires_in' => JWTAuth::setToken($token)->getPayload($token)->get('exp')]);
    }

    public function refresh(Request $request)
    {
        $token = JWTAuth::getToken();
        $new_token = JWTAuth::refresh($token);

        return response()->json(['token' => $new_token, 'expires_in' => JWTAuth::setToken($new_token)->getPayload($new_token)->get('exp')]);
    }

Ezután már csak a controllerekben a végpontokat kell létrehozni. Használhatunk swaggert is a végpontokat dokumentálni (az egy másik leírásban található).

Lista:
 
     /*
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cities = CoreCities->get();

        return $cities;
    }

Beszúrás:
 
     /*
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $cities = CoreCities::create([
            'name' => $request->get('name'),
            'post_code' => $request->get('post_code')
        ]);

        return response($cities);
    }

Show:
 
    /*
     * @param  \App\Models\CoreCities  $coreCities
     * @return \Illuminate\Http\Response
     */
    public function show(CoreCities $coreCities)
    {
        return response($coreCities);
    }

Módosítás:
 
     /*
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\CoreCities  $coreCities
     * @return \Illuminate\Http\Response
     */
    public function update(CoreCitiesRequest $request, CoreCities $coreCities)
    {
        $coreCities->update([
            'name' => $request->get('name'),
            'post_code' => $request->get('post_code')
        ]);

        return response($coreCities);
    }

Törlés:
 
     /*
     * @param  \App\Models\CoreCities  $coreCities
     * @return \Illuminate\Http\Response
     */
    public function destroy(CoreCities $coreCities)
    {
        $coreCities->delete();

        return response($coreCities);
    }


https://www.toptal.com/laravel/restful-laravel-api-tutorial
2019.08.24.