0

I'm on Shared Server.

Laravel v8.15.0 (PHP v7.3.23)

unable to set it up properly.

Sanctum & Passport both tried but that crashes with 500 Internal Server Error. So removed them.

https://townies.pk/api/v1/getCart is working. Another GET route for fetching Images is also working.

But https://townies.pk/api/register POST or https://townies.pk/api/v1/register POST not working. 500 Internal Server Error.

And https://townies.pk/api/login POST or https://townies.pk/api/v1/login POST not working. 500 Internal Server Error.

api.php

<?php

use App\Models\User;
use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\DB;

/*
|--------------------------------------------------------------------------
| 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:api')->get('/user', function (Request $request) {
    return $request->user();
});*/

Route::get('/v1/getCart', function(Request $request){
    return response()->json([
        'success'=> true, 
        'msg'=> "yes",
        'cartItems' => ['Beef Salaami Large: Rs. 780/-', 'Chicken Supreme Small: Rs. 290/-', 'Super Supreme Medium: Rs. 530/-' ]
    ])
    ->header('Content-Type', 'application/json');
});

Route::post('/v1/register', [AuthController::class, 'register'])->name('register');
Route::post('/v1/login', [AuthController::class, 'login'])->name('login');

AuthController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if($validator->fails())
        {
            Log::error('Something is really going wrong.');
            return response()->json(['status_code' => 400, 'message' => 'Bad Request']);
        }

        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = algo($request->password);
        $user->save();

        return response()->json([
            'status_code' => 201,
            'message' => 'User Registration Successful.'
        ]);
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if($validator->fails())
        {
            return response()->json(['status_code' => 400, 'message' => 'Bad Request']);
        }

        $credentials = request(['email', 'password']);

        if(!Auth::attempt($credentials))
        {
                return response()->json([
                    'status_code' => 401,
                    'message' => 'Unauthorised'
                ]);
        }

        $user = User::where('email', $request->email)->first();

        $tokenResult = $user->createToken('authToken')->plaitTextToken;

        return response()->json([
            'status_code' => 200,
            'token' => $tokenResult
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json([
            'status_code' => 200,
            'message' => 'LogOut Successful'
        ]);
    }
}

My Database Schema

Database Schema

Ronnie Depp
  • 159
  • 3
  • 12
  • You'll want the contents of that 500 to debug this further. Also my gut says this is not a bug in Laravel since you also posted in the tracker there, but a misconfiguration on your end. – Connor Tumbleson Nov 28 '20 at 17:22
  • yes, i know it's a misconfig on my end. but can't figure it out for 2 days now. i can only do GET requests. but no POST requests. – Ronnie Depp Nov 28 '20 at 22:16

1 Answers1

1

Next time, please share the exception message from your logs. It is much easier and faster to debug errors when we have a clear picture on the error message itself.

I tried with Laravel Sanctum and /register works fine after adding the missing imports to AuthController and HasApiTokens trait to User model, as outlined below.

/login was still failing until fixing a typo on this line:

$tokenResult = $user->createToken('authToken')->plaitTextToken;

plaitTextToken is misspelled. Should be: plainTextToken.

These are the imports missing on AuthController:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

Also, be sure to:

  • Add the Laravel\Sanctum\HasApiTokens trait to the User model
  • Add the middleware needed for Sanctum into ./app/Http/Kernel.php under the api middleware group
  • Publish and run Laravel Sanctum migrations

All these are outlined on Laravel Sanctum installation guide, please be sure to follow the installation guide very closely:

https://laravel.com/docs/8.x/sanctum#installation

After applying the changes above I tried with PHPStorm HTTP Client using these requests:

POST http://my-app.test/api/v1/register
Accept: application/json
Content-Type: application/json

{"name": "bar", "email": "bar@example.com", "password": "password"}

###

POST http://my-app.test/api/v1/login
Accept: application/json
Content-Type: application/json

{"email": "bar@example.com", "password": "password"}

###

With these corresponding responses:

POST http://my-app.test/api/v1/register

HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-cache, private
Date: Sun, 29 Nov 2020 01:26:22 GMT
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Access-Control-Allow-Origin: *

{
  "status_code": 200,
  "message": "User Registration Successful."
}

Response code: 200 (OK); Time: 80ms; Content length: 61 bytes

And

POST http://my-app.test/api/v1/login

HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-cache, private
Date: Sun, 29 Nov 2020 01:27:17 GMT
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
Access-Control-Allow-Origin: *

{
    "status_code": 200,
    "token": "1|5ImkzdVQgNhQyotxlZzs5Hr2YDkTPKfpfovthx1o"
}

Response code: 200 (OK); Time: 86ms; Content length: 72 bytes
Dharman
  • 30,962
  • 25
  • 85
  • 135
rodrigopedra
  • 56
  • 4
  • 11
  • let me try it again. Typo must be removed. I don't have error or debug logs, on this shared server. let me update you once i test it again.. thanks – Ronnie Depp Nov 29 '20 at 01:41
  • @RonnieDepp you should have a writeable folder called `./storage/logs` under your application root folder. Otherwise Laravel will be blowup every time it tries to write something to the logs, for example when an exception happens. I am not talking about system logs, but the regular application logs. Also please read the full response, it wasn't just the typo, imports and traits were missing, and I am not sure if you have all the tables needed by running the migrations after installing Sanctum properly. – rodrigopedra Nov 29 '20 at 01:44
  • **Storage/logs** is all 755. but still not a single log is there. Storage folder has views, sessions, cache, all are updated date/time wise files created by Laravel. I will update you once i implement it successfully as you described. Also I'm attaching IMAGE of DB-SCHEMA in main question. – Ronnie Depp Nov 29 '20 at 16:06
  • i'm stuck. Whenever I add Auth:Sanctum middleware to API route-group i get 500 Internal Server Error. No Error details logged automatically by laravel. It's my **mobile application** which will make api requests. **SinglePageApplication SPA** will also access these API routes. **laravel.log** file is being written only when i explicitly **Log::error("some error occured");** - imports **done** - typo **corrected** - sanctum middleware added to **kernel file**. - Trait **Added** to Model. - routes outside **auth:sanctum** are not accessible after enabing Sanctum. – Ronnie Depp Dec 21 '20 at 04:14
  • table **personal_access_tokens** is empty. – Ronnie Depp Dec 21 '20 at 04:16
  • i need at least one route to work so i can get a Sanctum Token for subsequent Mobile App & SPA requests. Although i placed an API route outside the Auth:Sanctum middleware group. But it also isn't working, once i enable Sanctum. – Ronnie Depp Dec 21 '20 at 04:20
  • `Route::middleware(['throttle:30,1', 'auth:sanctum'])->group(function () {` is this correct way to enclose all API routes? – Ronnie Depp Dec 21 '20 at 04:25