授权失败后的Laravel用户注册

时间:2018-08-28 14:03:03

标签: php laravel authentication laravel-5 authorization

Laravel 5.6中,您需要执行以下操作。

form - processesLoginController的授权,在我的情况下,我将电子邮件更改为姓名,并保留了密码。

如果这样的用户使用了这样的密码,那么我将对其进行授权,如果该用户没有这样的名称和密码,则必须使用输入的数据进行注册。

这是课程LoginController

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;


class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function redirectTo()
    {
        return '/';
    }

    public function username() {
        return 'name';
    }

    /**
     * Handle a failed authorization attempt.
     *
     * @return void
     *
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */


    protected function sendFailedLoginResponse(Request $request)
    {
        // What you need to do to register a user

    }
}

我当时想重写sendFailedLoginResponse来注册用户。以RegisterController的身份运行,并从POST请求中传输数据。

告诉我如何实现这个想法?

2 个答案:

答案 0 :(得分:0)

1。)打开文件:Illuminate\Foundation\Auth\AuthenticateUsers.php

2.)搜索方法:登录

3.)将返回$this->sendFailedLoginResponse($request);编辑到

return url('/register?username='.$request->username.'&password='.Hash::make($password));

这是最简单的方法,但不是最佳方法,最佳实践是不通过get发送密码,或者不从数据库设置其他密码。

答案 1 :(得分:0)

我认为这种实现并不完全正确。我意识到像这样

 public function login(Request $request)
 {
    $this->validate($request, [
        'name' => 'required|string',
        'password' => 'required|string'
    ]);
    $user = User::firstOrCreate([
        'name' => $request->name
    ], [
        'name' => $request->name,
        'password' => Hash::make($request->password)
    ]);

    if ($user && Hash::check($request->password, $user->password)) {
        auth()->loginUsingId($user->id);
        return redirect()->intended('/');
    } else {
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);
    }
 }