Laravel-自定义身份验证查询

时间:2018-07-11 13:22:29

标签: php sql laravel laravel-5.6 laravel-authentication

如何将using Newtonsoft.Json; using System; namespace UsersJSON { public class UsersRepository { public User[] Users; } public class User { public int serialNo; public UserDetails details; } public class UserDetails { public string name; public string job; } class Program { static void Main(string[] args) { var json = @"{ users: [ { serialNo: 1, details: {name: 'John', job: 'Receptionist'} }, { serialNo: 2, details: {name: 'Alan', job:'Salesman'} }] }"; var usersList = JsonConvert.DeserializeObject<UsersRepository>(json); Console.WriteLine(usersList.Users[0].details.name); // prints "John" Console.ReadLine(); } } } 添加到默认登录SQL查询中?

我的意思是默认情况下是

DESC

如何添加

select * from users where name = user_name limit 1

我知道name列应仅包含唯一值,我的登录系统有所不同(另一个表中有一些预定义用户),并且我需要使用相同名称进行多个用户注册。我只想登录数据库中的最后一条记录。请帮我如何在laravel中自定义模型提供程序?我不知道要修改哪些文件才能正常工作。

这是我的LoginController.php,但您可以忽略它(我添加了它,因为某些用户需要它),只需查看select * from users where name = user_name ORDER BY id DESC limit 1中的默认loginController

php artisan make:auth

我的LoginController中的所有方法都覆盖<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Session; 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 = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } /** * Check either username or email. * @return string */ 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'll key this by the username and // the IP address of the client making these requests into this application. if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } 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); } public function username() { $identity = Session::get('table_id'); $fieldName = 'name'; request()->merge([$fieldName => $identity]); return $fieldName; } /** * Validate the user login. * @param Request $request */ protected function validateLogin(Request $request) { $this->validate( $request, [ 'password' => 'required|string', ], [ 'password.required' => 'Password is required', ] ); } /** * @param Request $request * @throws ValidationException */ protected function sendFailedLoginResponse(Request $request) { $request->session()->put('login_error', trans('auth.failed')); throw ValidationException::withMessages( [ 'error' => [trans('auth.failed')], ] ); } protected function attemptLogin(Request $request) { $remember = true; return $this->guard()->attempt( $this->credentials($request), $remember ); } } 中的方法

4 个答案:

答案 0 :(得分:2)

用以下内容替换LoginController。我已经删除了username()方法,并替换了tryLogin()方法,以根据您的会话值'table_id'获取数据库中的最后一个用户。

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Session;
use App\User;
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 = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->middleware('guest')->except('logout');
        $this->user = $user;
    }
/**
     * Check either username or email.
     * @return string
     */

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'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        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);
    }

    /**
     * Validate the user login.
     * @param Request $request
     */
    protected function validateLogin(Request $request)
    {
        $this->validate(
            $request,
            [
                'password' => 'required|string',
            ],
            [
                'password.required' => 'Password is required',
            ]
        );
    }
    /**
     * @param Request $request
     * @throws ValidationException
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $request->session()->put('login_error', trans('auth.failed'));
        throw ValidationException::withMessages(
            [
                'error' => [trans('auth.failed')],
            ]
        );
    }

protected function attemptLogin(Request $request, User $user)
{
    if (session()->has('table_id') != true) return redirect()->back()->withErrors(['error' => 'No username is set.']);
    $userName = $user->where('name', session('table_id'))->orderBy('id', 'desc')->first()->name;
    $remember = true;
    if (Auth::attempt(['name' => $userName, 'password' => request('password')], $remember)) {
        return redirect()->intended();
    }
}

}

答案 1 :(得分:0)

您不应更改/删除任何框架文件和代码。 在您的登录控制器顶部,只需添加以下特征:

use AuthenticatesUsers;

然后您可以覆盖所有登录功能。

用于验证用户名/密码的密码只需覆盖 attemptLogin()函数。

答案 2 :(得分:0)

因此,如果我理解您的问题是对的,那么您想要更改默认的sql查询,以便在验证时选择用户。 在attemptLogin方法中,您调用attempt,它在StatefulGuard接口中,实现在/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php中,因此您需要覆盖完整的attempt方法,或者其中的任何方法。

答案 3 :(得分:0)

我找到了另一个可行的解决方案,但我相信它会搞乱(我不确定),这就是为什么我将Polaris的答案投票为正确的解决方案的原因。

您可以保留默认的LoginController并修改App / User.php,如下所示: 它基本上会覆盖retrieveByCredentials中使用的Illuminate\Auth\EloquentUserProvider;方法。问题是,我认为通常不会直接从Users.php访问此方法,因此您不会直接覆盖它。但是由于某种原因它起作用:))。     

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'password',
    ];

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

        public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials) ||
           (count($credentials) === 1 &&
            array_key_exists('password', $credentials))) {
            return;
        }

        // First we will add each credential element to the query as a where clause.
        // Then we can execute the query and, if we found a user, return it in a
        // Eloquent User "model" that will be utilized by the Guard instances.
        $query = $this->createModel()->newQuery();

        foreach ($credentials as $key => $value) {
            if (Str::contains($key, 'password')) {
                continue;
            }

            if (is_array($value) || $value instanceof Arrayable) {
                $query->whereIn($key, $value);
            } else {
                $query->where($key, $value);
            }
        }

       return $query->orderBy('id', 'desc')->first();
    }
}