MajAfy MajAfy - 1 month ago 13
PHP Question

custom Authentication on Laravel

I want to write a custom authentication on laravel, I want to know should I use default

auth
or should I write a new?

my auth workflow is:

Step 1- Show email form (in this step we will get just email address)

Step 1-2- check for email existence and if email exists we will go to Step 2 and if not exists I should redirect user to Step 3

Step 2- get the user password (validate password and if everything was OK user will login)

Step 3- show registration form and fill the email with entered user email address (validate form and register user)

What is your solution ?

Answer

//Login rules

public function user_login_rules(array $data)
{
  $messages = [
    'email.required' => 'Please enter your email'
  ];

  $validator = Validator::make($data, [
    'email' => 'required'
  ], $messages);

  return $validator;
}

Your post method

public function postSignIn(Request $request)
{ 
  $request_data = $request->all();
  $validator = $this->user_login_rules($request_data);   
  if($validator->fails())
  {
    return redirect()->back()->withErrors($validator)->withInput();
  }
  else
  {
    $email = $request_data['email'];
    $user_details = User::where('email', $email)->first();
    if(count($user_details) > 0)
    {
      $credentials = array('email'=> $email ,'password'=> $request_data['password']);        
      if ($this->auth->attempt($credentials, $request->has('remember')))
      {
        //Login successful
        return redirect()->to('/home');
      }
      else
      {
        $error = array('password' => 'Please enter a correct password');
        return redirect()->back()->withErrors($error); 
      }
    }
    else
    {    
      //Display register page with email
      return view('register')->with('email', $email);
    }     
  } 
}