Usman Hafeez
Usman Hafeez

Reputation: 365

Lumen Custom Authentication with custom Fields and Store in Auth Guard

I am using lumen for API development. I have an issue in Lumen Custom Authentication. I want to login a user when his credentials and account_name matches with stored record. In the credentials filed there is not username and password type data.

here my login method

public function login(Request $request)
{

    $this->validate($request,[
        'data.credentials' => 'required',
        'data.account_name' => 'required',
    ]);

    try {
        $credentials=$request->data['credentials'];
        $account_name=$request->data['account_name'];
        $user=User::where('account_name',$account_name)->where('credentials',$credentials)->first();

        if($user){
            // storing the authenticated user to the guard session

            $auth_token=Hash::make($account_name . ":" . $credentials);

            // update user auth token
            $user->auth_token=$auth_token;
            $user->update();

            $data="Some Data";

            return response()->json([
                "auth_token"=> $auth_token,
                "data"=>$data,
                "request_id"=> uniqid(),
                "status"=> "success"
            ]);


        }

    } catch (\Exception $e) {
        return response()->json(array(
            'error' => $e->getMessage(),
            'status' => 'failed',
            'status_code' => 500
        ));
    }

}

I authenticated user with credentials I want to store that user in guard that can be default guard or custom and want to return auth_token from every response. if I use following code it give me an error.

Auth::guard()->attempt(['credentials'=>$credentials,'account_name'=>$account_name]);

It give an error that attempt_undefined_method. and If I use the following code

Auth::guard()->check(['credentials'=>$credentials,'account_name'=>$account]);

it returns the false value and do not store user in guard. I want such type of response from every request where I applied auth middleware

return response()->json([
        "auth_token"=> auth()->user()->auth_token,
        "data"=>$data,
        "request_id"=> uniqid(),
        "status"=> "success
]);

following is my AuthMiddleware.php code

$header=$request->header('Auth-Token');
if(Auth::guard('api')){
        // we can use $user variable for further :)
        return $next($request);
  }

Upvotes: 1

Views: 1901

Answers (0)

Related Questions