>  기사  >  백엔드 개발  >  Laravel5.4에서 다중 필드 로그인을 구현하는 방법에 대한 자세한 설명

Laravel5.4에서 다중 필드 로그인을 구현하는 방법에 대한 자세한 설명

*文
*文원래의
2018-01-03 15:28:411315검색

최근 직장에서 필요하다고 느꼈던 다중 필드 로그인의 효과 중 하나는 바로 휴대폰, 이메일 등 어떤 방법으로든 로그인이 가능하다는 점입니다. 이제 해결 과정을 공유해드리겠습니다. 도움이 필요한 친구 기반 솔루션을 주로 소개한 글에서는 Laravel5.4의 다중 필드 로그인 기능 구현에 대한 관련 정보를 참조할 수 있습니다. 그것이 모두에게 도움이 되기를 바랍니다.

머리말

최근 프로젝트에 다중 필드 로그인 기능을 구현해야 합니다. 간단히 말하면 사용자 이름, 이메일 또는 휴대폰 번호를 사용하여 로그인할 수 있습니다. 그래서 이번 글에서는 Laravel5.4 다중 필드 로그인에 대한 관련 내용을 소개하고 참고 및 학습을 위해 공유하겠습니다. 더 이상 고민하지 말고 자세한 소개를 살펴보겠습니다.

다음 내용은 laravel5.4를 기준으로 작성되었습니다

방법은 다음과 같습니다.

먼저 artisan 도구를 통해 인증 모듈을 생성합니다

php artisan make:auth

이때, Auth 디렉토리는 등록 및 로그인과 관련된 컨트롤러인 AppHttpControllers 디렉터리에 추가하면 등록 및 로그인과 관련된 일부 보기도 resourcesviews 디렉터리에 생성됩니다.

Laravel의 공식 문서에 따르면 사용자의 수동 인증은 다음의 시도 방법을 사용해야 한다고 나와 있습니다. IlluminateSupportFacadesAuth 클래스는 다음과 같습니다:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
 /**
  * Handle an authentication attempt.
  *
  * @return Response
  */
 public function authenticate()
 {
  if (Auth::attempt([&#39;email&#39; => $email, &#39;password&#39; => $password])) {
   // Authentication passed...
   return redirect()->intended(&#39;dashboard&#39;);
  }
 }
}

이 메소드는 전달한 내용을 기반으로 합니다. 입력된 매개변수는 데이터베이스에 일치하는 사용자가 있는지 여부를 결정하며, 비밀번호가 정확하면 true를 반환하고, 그렇지 않으면 false를 반환합니다. 그런 다음 이 메서드를 LoginController에 추가했지만 효과가 없는 것 같았습니다. 그래서 LoginController의 구현 메커니즘을 관찰하기 시작했고 AuthenticatesUsers의 특성을 구현하고 이 특성의 정의 파일을 추적한 결과 이 ​​파일이 발견되었습니다.

그 안에는 로그인 로직 처리를 담당하는 로그인 메소드가 있습니다.

/**
  * Handle a login request to the application.
  *
  * @param \Illuminate\Http\Request $request
  * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
  */
 public function login(Request $request)
 {
  // 表单验证
  $this->validateLogin($request);

  // If the class is using the ThrottlesLogins trait, we can automatically throttle
  // the login attempts for this application. We&#39;ll key this by the username and
  // the IP address of the client making these requests into this application.
  // 防止暴力破解,多次登录失败会根据IP锁定
  if ($this->hasTooManyLoginAttempts($request)) {
   $this->fireLockoutEvent($request);

   return $this->sendLockoutResponse($request);
  }
  
  // 这个就是主要的负责判断数据库中是否存在相应的账号和密码的地方,我们需要重写的就是attemptLogin方法
  if ($this->attemptLogin($request)) {
   return $this->sendLoginResponse($request);
  }

  // If the login attempt was unsuccessful we will increment the number of attempts
  // to login and redirect the user back to the login form. Of course, when this
  // user surpasses their maximum number of attempts they will get locked out.
  // 登录失败,失败次数++,防止暴力破解
  $this->incrementLoginAttempts($request);

  // 返回失败响应
  return $this->sendFailedLoginResponse($request);
 }

이 파일의 웨이브를 분석해 보니, 로그인 판단을 위한 주요 메소드는 tryLogin 메소드만 필요하다는 것을 알았습니다. 먼저 원본이 어떻게 작성되었는지 살펴보고 원본에 따라 다시 작성해 보겠습니다.

/**
  * Attempt to log the user into the application.
  *
  * @param \Illuminate\Http\Request $request
  * @return bool
  */
 protected function attemptLogin(Request $request)
 {
  return $this->guard()->attempt(
   $this->credentials($request), $request->has(&#39;remember&#39;)
  );
 }

LoginController를 다시 작성한 후:

public function attemptLogin(Request $request)
 {
  $username = $request->input(&#39;username&#39;);
  $password = $request->input(&#39;password&#39;);

  // 验证用户名登录方式
  $usernameLogin = $this->guard()->attempt(
   [&#39;username&#39; => $username, &#39;password&#39; => $password], $request->has(&#39;remember&#39;)
  );
  if ($usernameLogin) {
   return true;
  }

  // 验证手机号登录方式
  $mobileLogin = $this->guard()->attempt(
   [&#39;mobile&#39; => $username, &#39;password&#39; => $password], $request->has(&#39;remember&#39;)
  );
  if ($mobileLogin) {
   return true;
  }

  // 验证邮箱登录方式
  $emailLogin = $this->guard()->attempt(
   [&#39;email&#39; => $username, &#39;password&#39; => $password], $request->has(&#39;remember&#39;)
  );
  if ($emailLogin) {
   return true;
  }

  return false;
 }

단 여러 판단에는 시도 방법을 사용해야 합니다. 성공하면 true를 반환합니다. 성공하지 못하면 계속해서 다른 필드를 사용하여 판단합니다.

테스트하면 다중 필드 로그인 효과를 얻을 수 있습니다

관련 권장 사항:

Laravel 5.5의 해당 인터페이스를 사용하는 방법은 무엇입니까?

Laravel 5.5는 프론트엔드와 백엔드 로그인을 구현합니다

Laravel이 동일한 대기열 작업을 반복적으로 실행하는 이유

위 내용은 Laravel5.4에서 다중 필드 로그인을 구현하는 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.