skip to Main Content

I have login metod in Laravel api. When I try to send request i have code 200 without content in Postman

AuthController.php

<?php

namespace AppHttpControllers;

use AppHttpRequestsLoginRequest;
use AppServicesAuthService;
use Exception;
use IlluminateAuthAuthenticationException;
use IlluminateHttpRequest;

class AuthController extends Controller
{
    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    public function login(LoginRequest $request)
    {
        try 
        {
            $res = $this->authService->loginUser($request);
            return response($res, 202);
        } 
        catch(Exception $e)
        {
            if($e instanceof AuthenticationException)
                return response(['message' => 'Nieprawidłowy adres email lub hasło!'], 401);
        }
    }

    public function logout(Request $request)
    {   
        try
        {
            $res = $this->authService->logoutUser($request);
            return response($res, 200);
        }
        catch(Exception $e)
        {
            throw $e;
        }
    }
}

api.php

<?php

use AppHttpControllersAuthController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| 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::fallback(function () {
    return abort(404);
}); 

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/auth/login', [AuthController::class, 'login']);
Route::post('/auth/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');

AuthService.php

<?php

namespace AppServices;

use AppHttpRequestsLoginRequest;
use AppHttpResourcesUserResource;
use AppRepositoriesUserRepository;
use Exception;
use IlluminateAuthAuthenticationException;
use IlluminateHttpRequest;

class AuthService {

    protected $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    } 
    
    public function loginUser(LoginRequest $request) 
    {       
        $user = $this->userRepository->findByEmail($request['email']);
        
        if(!$user) throw new AuthenticationException();
        
        $isCorrectPassword = $this->userRepository->comparePassword($request['hasło'], $user);

        $this->validateUser($user, $isCorrectPassword);
        
        $token = $this->createToken($user);

        return $this->returnUserWithToken($user, $token);
    }

    public function createToken($user)
    {
        return $this->userRepository->createToken($user);
    }

    public function validateUser($user, $isCorrectPassword)
    {
        if (!$user || !$isCorrectPassword) throw new AuthenticationException();
    }

    public function returnUserWithToken($user, $token)
    {
        $res = [
            'data' => new UserResource($user),
            'token' => $token
        ];

        return $res;
    }

    public function logoutUser(Request $request)
    {
        try
        {
            $this->userRepository->deleteToken($request);
            return $res = ['message' => 'Wylogowanie przebiegło pomyślnie!'];
        }
        catch(Exception $e)
        {
            throw $e;
        }
    }
    
} 

UserRepository.php

<?php

namespace AppRepositories;

use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;

class UserRepository {

    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function findByEmail(string $email)
    {
        return $this->user::where('email', $email)->first();
    }

    public function comparePassword(string $password, User $user)
    {
        return Hash::check($password, $user->password);
    }

    public function createToken(User $user)
    {
        return $user->createToken('token')->plainTextToken;
    }

    public function deleteToken(Request $request)
    {
        $request->user()->tokens()->delete();
    }
}

User.php (model)

<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function product()
    {
        return $this->hasMany(Product::class);
    }
}

Postman screen

When i write wrong password or email i have this
Postman screen2

This message is in Polish "Wrong email or password"

I dont know when i have mistakes… In another project i have similar method and it’s works. I use sanctum.

3

Answers


  1. I would like to inform you that Request $request should not be used in service class or any repository class.

    Change this line

    $this->user::where('email', $email)->first();
    

    to following line and then try.

    $this->user->where('email', $email)->first();
    
    Login or Signup to reply.
  2. You have this

    if($e instanceof AuthenticationException)
    

    What if it is not an instance of that exception? The code falls to the end of the controller function and returns nothing except a 200 code.

    Its probably the syntax error in findByEmail mentioned by @Ali which is throwing a different error.

    Login or Signup to reply.
  3. The problem in this line: $isCorrectPassword = $this->userRepository->comparePassword($request['hasło'], $user);

    Password field added to hidden property, this means your User model doesn’t have this value after retrieving from database (it’s null), and Hash::check caused an error, as second parameter should be a string

    But you are not catching this exception in AuthController

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search