Laravel - Postman给予我200个没有内容的代码

a1o7rhls  于 2023-05-28  发布在  Postman
关注(0)|答案(5)|浏览(190)

我在Laravel API中有登录方法。当我尝试发送请求时,我在Postman中没有内容代码200
AuthController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use App\Services\AuthService;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;

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 App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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 App\Services;

use App\Http\Requests\LoginRequest;
use App\Http\Resources\UserResource;
use App\Repositories\UserRepository;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;

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 App\Repositories;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

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 App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

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
当我写错密码或电子邮件时,我有此Postman screen2
此消息是在波兰语“错误的电子邮件或密码”
我不知道我什么时候犯了错。。在另一个项目中,我有类似的方法,它的作品。我用圣所。

tzdcorbm

tzdcorbm1#

你有这个

if($e instanceof AuthenticationException)

如果它不是那个例外的示例呢?该代码福尔斯在控制器函数的末尾,除了200代码外不返回任何内容。
这可能是@Ali提到的findByEmail中的语法错误,它抛出了一个不同的错误。

lbsnaicq

lbsnaicq2#

我解决了我的问题。。我只是在这个项目中使用了Laravel版本9,而不是最新的10...差异在于personal_access_token表中的列。SQL错误地处理了查询...而且由于 Postman 返回给我的代码200没有内容,这个错误很难捕捉。目前,我将它重写到laravel版本10项目中,它可以工作。感谢大家的承诺。

drnojrws

drnojrws3#

我想通知你Request $request不应该在服务类或任何存储库类中使用。
更改这一行

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

然后按下按钮,然后尝试。

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

r6hnlfcb4#

这一行的问题是:$isCorrectPassword = $this->userRepository->comparePassword($request['hasło'], $user);
password字段添加到hidden属性,这意味着User模型在从数据库检索后没有这个值(它是null),并且Hash::check导致了一个错误,因为第二个参数应该是字符串
但您不会在AuthController中捕获此异常

8iwquhpp

8iwquhpp5#

正如其他人提到的,你的问题是在抛出AuthenticationException以外的异常时不返回任何东西。
抛出不同异常的bug如下:

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

应该是User::where

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

但是我也想建议你重构你的代码。

  • 不必要的try catch
  • 不必要存储库模式
  • 过度设计

存储库模式有它的位置,但这不是它的用例。它在你开发的需要灵活性的包/库中最有用。例如提供多个DB(mysql,postgres,sql等)供雄辩者使用等。
你可以把你的逻辑归结为:
AuthController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;

class AuthController extends Controller
{

    public function login(LoginRequest $request)
    {
        $user = User::where('email', $request['email'])->first();
        
        if(!$user || !Hash::check($password, $user->password)) {
            throw new AuthenticationException("Nieprawidłowy adres email lub hasło!");
        } 

        return response([
            'data' => new UserResource($user),
            'token' => $user->createToken('token')->plainTextToken
        ], 202);

    }

    public function logout(Request $request)
    {   
        $request->user()->tokens()->delete();
        return response([
            'message' => 'Wylogowanie przebiegło pomyślnie!'
        ], 200);

    }
}
  • AuthService.php -已删除
  • UserRepository.php -已删除

相关问题