1

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);
  }
Usman Hafeez
  • 357
  • 1
  • 7
  • 20
  • I want to store user data in guard when credentials and account name matches after where I commented in login method // storing the authenticated user to the guard session – Usman Hafeez Dec 27 '17 at 07:46
  • 1
    lumen doesn't have session support, what do you mean by 'guard session'? – lagbox Dec 27 '17 at 09:35
  • first of all thanks a lot for reply, if I want to return auth_token from all responses, can you please brief which approach should be better for – Usman Hafeez Dec 27 '17 at 10:15

0 Answers0