Backend API - shibotsu/obs-clone GitHub Wiki

📡 API Routes

This page documents the available API endpoints for the backend of the project. All endpoints return JSON responses and follow RESTful conventions where possible. First of all, after downloading Laravel Sanctum, there should be an api.php file in the routes folder. In that file, all routes for the backend are defined, and all of them start with /api. It is also important to create a new guard that will use JWT for middleware.

To create a new guard, you need to access a file in the config folder called auth.php.

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

After this change, you can use middleware on your routes based on JWT. Middleware checks if the user's token is valid, and if it is not, it sends a JSON response. If the user is authenticated, everything will work fine. Every route calls a specific function in a designated Controller, so there shouldn't be any further issues.

🛡️ Authentication

Authentication is very basic because we wanted to include as many features as possible. This authentication validates users and returns JSON with a JWT. There is no expiration for the token, which is a security risk, but for running the project locally, it is not important. Here are some important routes:

POST /api/register

Registers a user and returns a JWT token. It is important to mention that the date of birth must be in a specific format so that Laravel validation can process it.

Request Body:

{
    "username": "user",
    "email": "[email protected]",
    "password": "password123",
    "birthday": "2001-12-12"
}

POST /api/login

Authenticates a user and returns a JWT token and user data. The user data is sent in the JSON response, so the backend can use it to display the username and profile picture.

Request Body:

{
  "login": "[email protected]",
  "password": "password123"
}

Notes:

  • A user can log in using either a username and password or an email and password. The login variable stores the username or email.

Controller Logic:

public function store()
{
    $credentials = request()->validate([
        'login' => ['required', 'string'],
        'password' => ['required', 'string', 'min:8'],
    ]);

    try {
        $login_type = filter_var($credentials['login'], FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (!$token = JWTAuth::attempt([
            $login_type => $credentials['login'],
            'password' => $credentials['password'],
        ])) {
            return response()->json(['error' => 'Invalid credentials'], 401);
        }

        return response()->json(['token' => $token], 200);
    } catch (\Exception $e) {
        return response()->json(['error' => 'Could not create token'], 500);
    }
}

Explanation:

  • The FILTER_VALIDATE_EMAIL filter determines whether the login field contains an email or a username.
  • After validation and filtering, the user is authenticated.
  • The try-catch block ensures robust error handling, returning appropriate JSON responses for success or failure.

POST /api/logout

The logout function is straightforward. The only important thing is that the route is protected by the middleware guard auth:api, so only authenticated users can log out. It is important that the request for logging out includes a bearer token so that everything works properly.

Route Definition:

Route::middleware('auth:api')->post('/logout', [SessionController::class, 'destroy']);