laravelauthenticationjwtlumen

Login with only email in Lumen (JWT Auth)


I want to make the password optional while login into the system. If the user enters the password the login works fine and return the jwt token, when I entered to try to login only with email it gives the following error:-

Undefined index: password (500 Internal Server Error)

The following is the code of my login method

public function authenticateUser($request)
    {
        $input = $request->only('email','password');
        if (!$authorized = Auth::attempt($input, true)) {
            return $this->failure('Credentials doesnot match our records!', 401);
        } else {
            $token = $this->respondWithToken($authorized);
            return $this->success('Login Successfully !', $token, 200);
        }
    }

protected function respondWithToken($token)
    {
        return [
            'token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::factory()->getTTL() * 60,
            'user' =>  Auth::user()
        ];
    }

so basically, what I want is when a user enters an email it will login and should return the token, and if the user login with email and password then it should also work and return the token.


Solution

  • You can create a custom Authentication User Provider that will work around this potentially missing 'password' field. Though, I would probably not here. You can check the input yourself to see if there is a password or not. If there is pass it through attempt like normal. If it is not there find the user using the configured User Provider and login to the guard (what attempt is doing).

    Perhaps something like this:

    public function authenticateUser($request)
    {
        if ($request->has('password')) {
            $token = Auth::attempt($request->only(['email', 'password']));
        } else {
            $token = ($user = Auth::getProvider()->retrieveByCredentials($request->only(['email'])))
                ? Auth::login($user)
                : false;
        }
    
        return $token
            ? $this->success('Login Successfully !', $this->respondWithToken($token), 200)
            : $this->failure('Credentials do not match our records!', 401);
    }