简体   繁体   中英

Laravel 5.7 Auth with email/username and password using tymon/jwt

I am using jwt-auth for my Laravel 5.7 app. Currently, I'm allowing the client to enter email and password as user credentials.

However, I also want to let the client to enter their username in place of their email. So they have 2 choices: email or username.

How can I do that in my code?

My UserController@authenticate

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');
    try {
        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json([
                'status' => 401,
                'message' => 'invalid_credentials',
            ], 401);
        }
    } catch(JWTException $e) {
        return response()->json([
            'status' => 500,
            'message' => 'token_creation_failed',
        ], 500);
    }

    return response()->json(compact('token'));
}

Thanks in advance

In your AuthController, add this to the login method;

public function login()
{
    $loginField = request()->input('login');
    $credentials = null;

    if ($loginField !== null) {
        $loginType = filter_var($loginField, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        request()->merge([ $loginType => $loginField ]);

        $credentials = request([ $loginType, 'password' ]);
    } else {
        return $this->response->errorBadRequest('What do you think you\'re doing?');
    }

    if (! $token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    return $this->respondWithToken($token);
}

This is how I handled mine where user can choose either email or phone to login.

public function login(Request $request)
    {
          //validate incoming request
        $this->validate($request, [
            'email_phone' => 'required|string',
            'password' => 'required|string',
        ]);

        try {

            $login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';

            // return $login_type;

            $credentials = [$login_type => $request->email_phone, 'password'=>$request->password];

            if (! $token = Auth::attempt($credentials)) {
                return response()->json($this->customResponse("failed", "Unauthorized"), 401);
            }

            return $this->respondWithToken($token);
        } catch(JWTException $e) {

            return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM