Laravel privilege control collation--Auth

Keywords: Laravel Database PHP Session

User authentication

1. Customer Authentication

brief introduction

Laravel makes it very easy to implement authentication mechanisms. In fact, almost all settings are done by default. Configuration files for authentication are placed in config/auth.php, and they also contain good annotations describing the corresponding authentication services for each option.

Laravel includes an App User model driven by default Eloquent authentication in the app folder by default.  
Note: When designing the database structure for this authentication model, the password field has at least 60 character widths. Similarly, before you start, make sure that your users (or other synonyms) database table contains a string type named remember_token with a length of 100 and an acceptable null field. This field will be used to store session token for "Remember Me". You can also use the $table-rememberToken(); method in the migration file. Of course, these fields are already set in migrations that come with Laravel 5.

If your application is not using Eloquent, you can also use Laravel's query constructor as a database authentication driver.

Authentication

Laravel has preset two authentication-related controllers. AuthController handles new user registration and login, while PasswordController can help registered users reset their passwords.

Each controller uses trait to introduce the desired method. In most applications, you don't need to modify these controllers. The views used by these controllers are placed in the resources/views/auth directory. You can modify these views as required.

Table structure

Laravel's own authentication includes user registration, login, password reset, as well as the data structure required for these functions.
Under database migrations, after configuring the database, all migrations are performed:

php artisan migrate
  • 1

The database is automatically generated: users (user table), password_resets (reset password table), migrations (migration table)

User registration

To modify the form fields used by the application to register new users, you can modify the App Services Registrar class. This class is responsible for validating and building new users of the application.

Registrar's validator method contains validation rules for new users, while Registrar's create method is responsible for creating a new User record in the database. You are free to modify these methods. The Registrar method is called through Authenticates AndRegisters Users trait's Authenticates Controller.  
Take a look at the source code:

class Registrar implements RegistrarContract {
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    public function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    public function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

2. Manual User Authentication

If you don't want to use the default AutoController, you need to use Laravel's authentication class directly to manage user authentication. Don't worry, it's very simple! First, let's look at the attempt method:

<?php namespace App\Http\Controllers;
use Auth;
use Illuminate\Routing\Controller;
class AuthController extends Controller {
    /**
     * Handle an authentication attempt.
     *
     * @return Response
     */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password]))
        {
            return redirect()->intended('dashboard');
        }
    }
}
  •  

The attempt method can accept an array of key-value pairs as the first parameter. The password value is hashed first. Other values in the array are used to query users in the data table. So, in the example above, the user is identified based on the value of the email column. If the user is found, the hashed password stored in the database is compared with the hashed password value in the array. Assuming that the two hashed passwords are the same, the authenticated session will be restarted for the user.

If the authentication is successful, attempt returns true. Otherwise, return false.

** Note: In the above example, it is not necessary to use the email field, which is just an example. You should use any key value that corresponds to "username" in the data table.

The intended method redirects to the URL the user is trying to access, and its value is saved before authentication filtering. You can also pass a default URI to this method to prevent the redirected site from being unavailable.

Authenticate Users with Specific Conditions

In the authentication process, you may want to add additional authentication conditions:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1]))
{
    // The user is active, not suspended, and exists.
}

As you can see, an active field is added to the validation.

Authenticate the user and "remember" him

If you want to provide "remember me" functionality in your application, you can pass in a Boolean value as the second parameter of the attempt method, so that the user's authenticated identity can be retained (or until he manually logs out). Of course, your users table must include a string-type remember_token column to store the "remember me" identifier.

if (Auth::attempt(['email' => $email, 'password' => $password], $remember))
{
    // The user is being remembered...
}

If you use the "remember me" function, you can use viaRemember method to determine whether the user has a "remember me" cookie to determine user authentication:

if (Auth::viaRemember())
{
    //
}

3. Determine whether the user has been authenticated

To determine whether a user has logged in, you can use the check method:

if (Auth::check())
{
    // The user is logged in...
}

4. Verify not to log in only

validate allows you to authenticate user credentials without actually landing applications.

if (Auth::validate($credentials))
{
    //
}

5. Login users within a single request

You can also use the once method to allow users to login within a single request. No session or cookie will be generated:

if (Auth::once($credentials))
{
    //
}

6. User instance login

If you need to login an existing user instance to the application, you can call the login method and pass in the user instance:

Auth::login($user);
  •  

Safe Exit

Of course, assuming you use Laravel's built-in authentication controller, preset provides a way for users to log out.

Auth::logout();
  •  

Get an authenticated user instance

1. Obtained from Auth facade

<?php namespace App\Http\Controllers;
use Illuminate\Routing\Controller;
class ProfileController extends Controller {
    /**
     * Update the user's profile.
     *
     * @return Response
     */
    public function updateProfile()
    {
        if (Auth::user())
        {
            // Auth::user() returns an instance of the authenticated user...
        }
    }
}

2. Illuminate Http Request instance acquisition

<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class ProfileController extends Controller {
    /**
     * Update the user's profile.
     *
     * @return Response
     */
    public function updateProfile(Request $request)
    {
        if ($request->user())
        {
            // $request->user() returns an instance of the authenticated user...
        }
    }
}

3. Use Illuminate Contracts Auth Authenticatable contract type prompt

<?php namespace App\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Contracts\Auth\Authenticatable;
class ProfileController extends Controller {
    /**
     * Update the user's profile.
     *
     * @return Response
     */
    public function updateProfile(Authenticatable $user)
    {
        // $user is an instance of the authenticated user...
    }
}

Posted by keithh0427 on Tue, 18 Jun 2019 17:14:29 -0700