繁体   English   中英

Laravel 身份验证登录不起作用

[英]Laravel auth login not working

我是 Laravel 的新手,我正在研究 Laravel 身份验证系统,虽然注册有效,但登录没有任何作用。

用户控制器.php

class UserController extends Controller
{

    public function postSignUp(Request $request)
    {


        $email = $request['email'];
        $first_name = $request['first_name'];
        $password = bcrypt($request['password']);

        $user = new User;

        $user->email = $request->email;
        $user->first_name = $request->first_name;
        $user->password = bcrypt($request->password);

        $user->save();

        Auth::login($user);

        return redirect()->route('hotelier.index')->with('alert-success','Data has been saved successfully');


    }


    public function postSignIn(Request $request)
    {

        if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){

            return redirect()->route('hotelier.index');

        }

         return redirect()->back();

    }

}

路线(web.php)

    Route::group(['middleware' => ['web']], function (){

        Route::get('/', function () {
            return view('welcome');
        });

        Route::resource('hotelier','HotelierController');

            Route::post('/signup', [

            'uses'=> 'UserController@postSignUp',
            'as' =>'signup'

        ]);


        Route::post('/signin', [

            'uses'=> 'UserController@postSignIn',
            'as' =>'signin'

        ]);


    } );

   Auth::routes();

   Route::get('/home', 'HomeController@index')->name('home');

请告诉我如何登录

谢谢

你应该只是你的工匠命令 php artisan make:auth。 这将创建一些东西。 它将在您的 Controllers 文件夹和 view 文件夹中创建一个 auth 文件夹。 假设您使用的是 laravel 5.4,它还会添加到您的 web.php 路由文件中。 在您的 controller/auth 目录中,您将找到您的 LoginController 和 RegisterController。 从字面上看,它应该包含您需要进行身份验证的所有内容。 您需要确保您的用户模型上有电子邮件或用户名属性。 您还需要有一个密码属性。 从那里您可能希望根据您的应用程序进行一些自定义。

这是一个示例 LoginController:

<?php

namespace App\Http\Controllers\Auth;

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

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 = '/customer';

    /**
     * Create a new controller instance.
     *
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');

    }

    protected $username = 'email';

    public function loginNameOrEmail(Request $request)
    {
        $field = filter_var($request->input('email'), FILTER_VALIDATE_EMAIL) ? 'email_address' : 'username';

        $request->merge([$field => $request->input('email')]);

        $this->username = $field;

        return $this->login($request);

    }


    public function username()
    {
        return $this->username;
    }

}

注册控制器:

<?php

namespace App\Http\Controllers\Auth;

use App\Email;
use App\PersonName;
use App\Location;

use App\Contact;

use App\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'first-name' => 'required|string|max:255',
            'middle-name' => 'required|string|max:255',
            'last-name' => 'required|string|max:255',
            'address' => 'required|string|max:255',
            'city' => 'required|string|max:255',
            'state' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'password' => 'required|string|min:4|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        $email_address = $data['email'];

        $email = new Email();

        $email->setEmail($email_address);


        $location = new Location([
            'address'   =>  $data['address'],
            'city'      =>  $data['city'],
            'state'     =>  $data['state'],
            'zipcode'   =>  $data['zip']
        ]);

        $location->save();

        $location->createCoordinates();

        $personname = new PersonName([
            'first_name'        =>  $data['first-name'],
            'last_name'         =>  $data['middle-name'],
            'middle_name'       =>  $data['last-name'],
            'preferred_name'    =>  $data['preferred-name'],
            'title'             =>  $data['title']
        ]);

        $personname->save();

        $contact = new Contact();

        $contact->email_id = $email->id;
        $contact->location_id = $location->id;
        $contact->personname_id = $personname->id;

        $contact->save();

        $user = new User();
        $user->contact_id = $contact->id;
        $user->email_address = $email_address;
        $user->setPassword($data['password']);
        $user->username = $user->getEmailUsername();
        $user->save();




        return $user;
    }
}

路线/ web.php :

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function(){
   return view('auth.login');
});

Auth::routes();

Route::post('login', 'Auth\LoginController@loginNameOrEmail');
//Route::get('/test')

// auth middleware //

Route::group(['middleware' => ['auth']], function () {

    // Enums Route //

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/dashboard', 'DashboardController@index')->name('dashboard');


Route::get('/customer', 'CustomerController@index');

Route::post('/customer', 'CustomerController@show');

Route::get('/titleEnum', 'EnumController@title');

Route::get('/genderEnum', 'EnumController@gender');

Route::get('/test', 'TestController@test');


});

为什么不是用户模型:

<?php

namespace App;


use Mockery\Exception;
use Illuminate\Support\Facades\Hash;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

use App\Model as Model;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{

    use Authenticatable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'contact', 'username', 'email_address'
    ];

    /**
     * The column name of the "remember me" token.
     *
     * @var string
     */
    protected $rememberTokenName = 'remember_token';

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'remember_token', 'active'
    ];

    /**
     * the attributes that should be guarded from Mass Assignment
     *
     * @var array
     */
    protected $guarded = [
        'created_at', 'updated_at', 'password_hash'
    ];

    /**
     * Define table to be used with this model. It defaults and assumes table names will have an s added to the end.
     *for instance App\User table by default would be users
     */
    protected $table = "user";

    /**
     * We have a non incrementing primary key
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * relationships
     */
    public function contact(){
//        return $this->hasOne(Contact::class, 'id', 'contact_id');
        return $this->hasOne(Contact::class);
    }


    public function customers(){
//        return $this->hasOne(Contact::class, 'id', 'contact_id');
        return $this->hasMany(Customer::class);
    }

    /**
     * User constructor.
     * @param array $attributes
     */
    public function __construct($attributes = array())  {
        parent::__construct($attributes); // Eloquent
        // Your construct code.

        $this->active = 1;

        return $this;
    }


    /**
     * @param $password string
     * set user password_hash
     * @return $this
     */
    public function setPassword($password){
        // TODO Password Validation
        try{
            $this->isActive();
            $this->password_hash = Hash::make($password);
            $this->save();
        } catch(\Exception $e) {
            dump($e->getMessage());
        }
        return $this;
    }


    /**
     * Returns whether or not this use is active.
     *
     * @return bool
     */
    public function isActive(){
        if($this->active) {
            return true;
        } else {
            Throw new Exception('This user is not active. Therefore you cannot change the password', 409);
        }
    }


    public function getEmailUsername(){
        $contact = Contact::getObjectById($this->contact_id);

        $email = Email::getObjectById($contact->email_id);

        return $email->username_prefix;
    }


    /**
     * @return string
     *
     * getFullName
     * returns concatenated first and last name of user.
     */
    public function getFullName(){
        return $this->first_name . ' ' . $this->last_name;
    }


    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName(){
        return $this->getKeyName();

    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier(){
        return $this->{$this->getAuthIdentifierName()};
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword(){
        return $this->password_hash;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken(){
        if (! empty($this->getRememberTokenName())) {
            return $this->{$this->getRememberTokenName()};
        }
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value){
        if (! empty($this->getRememberTokenName())) {
            $this->{$this->getRememberTokenName()} = $value;
        }
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName(){
        return $this->rememberTokenName;
    }

    /**
     * Get the e-mail address where password reset links are sent.
     *
     * @return string
     */
    public function getEmailForPasswordReset(){

    }

    /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token){

    }

    public function validateAddress(){

    }


}

可能为时已晚,但可能会帮助其他人。 您是否注意到您的User模型中的protected $fillable = [...]Illuminate\\Foundation\\Auth\\User as Authenticatable扩展Illuminate\\Foundation\\Auth\\User as Authenticatable 确保为用户模型设置了所有在protected $fillable = [...]定义的属性,然后尝试使用Auth::login($user); 我的用户模型看起来像命名空间 App\\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    // Make sure you set these properties for the model
    protected $fillable = ['name', 'username', 'email', 'password', 'contact',];
.
.
.
}

在您的登录控制器中使用它

 $email = $request->input('email');
        $password = $request->input('password');
        if (Auth::attempt(['email' => $email, 'password' => $password])) 

我知道这是一个迟到的答案,但我刚刚使用Auth::login()而不是使用auth()->login()解决了这个问题。

我认为这应该是一样的,但我不知道为什么它适用于Auth::login()而不是auth()->login()主要原因。

当登录用户发出请求时,Laravel 使用用户实例的属性从数据库中检索用户详细信息。 此属性是 Authenticatable 对象的 getAuthIdentifier() 方法返回的值。 如果您使用的是 \\App\\Models\\User 类,则该方法返回“id”。 因此,请确保在您提供给 Auth::login() 的用户实例上设置了 id 属性。

Illuminate\\Auth\\SessionGuard.php:

public function login(AuthenticatableContract $user, $remember = false)
    {
        $this->updateSession($user->getAuthIdentifier());

        // If the user should be permanently "remembered" by the application we will
        // queue a permanent cookie that contains the encrypted copy of the user
        // identifier. We will then decrypt this later to retrieve the users.
        if ($remember) {
            $this->ensureRememberTokenIsSet($user);

            $this->queueRecallerCookie($user);
        }

        // If we have an event dispatcher instance set we will fire an event so that
        // any listeners will hook into the authentication events and run actions
        // based on the login and logout events fired from the guard instances.
        $this->fireLoginEvent($user, $remember);

        $this->setUser($user);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM