Skip to content

Commit 0fab76e

Browse files
author
qiang.sun
committed
多表登录、单页面API认证
1 parent 9da54b1 commit 0fab76e

25 files changed

+635
-19
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@ Homestead.yaml
1111
npm-debug.log
1212
yarn-error.log
1313
.env
14-
.phpunit.result.cache
14+
.phpunit.result.cache

app/Admin.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
namespace App;
4+
5+
use Illuminate\Foundation\Auth\User as Authenticatable;
6+
use Illuminate\Notifications\Notifiable;
7+
8+
class Admin extends Authenticatable
9+
{
10+
use Notifiable;
11+
12+
/**
13+
* The attributes that are mass assignable.
14+
*
15+
* @var array
16+
*/
17+
protected $fillable = [
18+
'name', 'email', 'password',
19+
];
20+
21+
/**
22+
* The attributes excluded from the model's JSON form.
23+
*
24+
* @var array
25+
*/
26+
protected $hidden = [
27+
'password', 'remember_token',
28+
];
29+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
namespace App\Extentions;
3+
4+
use Illuminate\Support\Str;
5+
use Illuminate\Auth\EloquentUserProvider as BaseUserProvider;
6+
7+
class EloquentUserProvider extends BaseUserProvider
8+
{
9+
/**
10+
* Retrieve a user by the given credentials.
11+
*
12+
* @param array $credentials
13+
* @return \Illuminate\Contracts\Auth\Authenticatable|null
14+
*/
15+
public function retrieveByCredentials(array $credentials)
16+
{
17+
if (empty($credentials) ||
18+
(count($credentials) === 1 &&
19+
array_key_exists('password', $credentials))) {
20+
return;
21+
}
22+
23+
// First we will add each credential element to the query as a where clause.
24+
// Then we can execute the query and, if we found a user, return it in a
25+
// Eloquent User "model" that will be utilized by the Guard instances.
26+
$query = $this->createModel()->newQuery();
27+
28+
// 用于标识是否是第一个登录字段,如果包含多个登录字段,使用 OR 查询
29+
$flag = false;
30+
foreach ($credentials as $key => $value) {
31+
if (Str::contains($key, 'password')) {
32+
continue;
33+
}
34+
35+
if ($flag) {
36+
$query->orWhere($key, $value);
37+
} else {
38+
$query->where($key, $value);
39+
$flag = true;
40+
}
41+
}
42+
43+
return $query->first();
44+
}
45+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
namespace App\Http\Controllers\Admin;
4+
5+
use Illuminate\Foundation\Auth\AuthenticatesUsers;
6+
use Illuminate\Http\Request;
7+
use App\Http\Controllers\Controller;
8+
use Illuminate\Support\Facades\Auth;
9+
10+
class LoginController extends Controller
11+
{
12+
use AuthenticatesUsers;
13+
14+
protected $redirectTo = '/admin';
15+
16+
public function __construct()
17+
{
18+
$this->middleware('guest:admin')->except('logout');
19+
}
20+
21+
public function showLoginForm()
22+
{
23+
return view('admin.login');
24+
}
25+
26+
protected function guard()
27+
{
28+
return Auth::guard('admin');
29+
}
30+
31+
protected function loggedOut(Request $request)
32+
{
33+
return redirect(route('admin.login'));
34+
}
35+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
namespace App\Http\Controllers\Admin;
4+
5+
use App\Admin;
6+
use Illuminate\Foundation\Auth\RegistersUsers;
7+
use Illuminate\Http\Request;
8+
use App\Http\Controllers\Controller;
9+
use Illuminate\Support\Facades\Auth;
10+
use Illuminate\Support\Facades\Hash;
11+
use Illuminate\Support\Facades\Validator;
12+
13+
class RegisterController extends Controller
14+
{
15+
use RegistersUsers;
16+
17+
protected $redirectTo = '/admin';
18+
19+
public function __construct()
20+
{
21+
$this->middleware('guest:admin');
22+
}
23+
24+
public function showRegistrationForm()
25+
{
26+
return view('admin.register');
27+
}
28+
29+
protected function guard()
30+
{
31+
return Auth::guard('admin');
32+
}
33+
34+
/**
35+
* Get a validator for an incoming registration request.
36+
*
37+
* @param array $data
38+
* @return \Illuminate\Contracts\Validation\Validator
39+
*/
40+
protected function validator(array $data)
41+
{
42+
return Validator::make($data, [
43+
'name' => 'required|string|max:255',
44+
'email' => 'required|string|email|max:255|unique:users',
45+
'password' => 'required|string|min:6|confirmed',
46+
]);
47+
}
48+
49+
/**
50+
* Create a new user instance after a valid registration.
51+
*
52+
* @param array $data
53+
* @return \App\User
54+
*/
55+
protected function create(array $data)
56+
{
57+
return Admin::create([
58+
'name' => $data['name'],
59+
'email' => $data['email'],
60+
'password' => Hash::make($data['password']),
61+
]);
62+
}
63+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
namespace App\Http\Controllers;
4+
5+
use Illuminate\Http\Request;
6+
7+
class AdminController extends Controller
8+
{
9+
/**
10+
* Create a new controller instance.
11+
*
12+
* @return void
13+
*/
14+
public function __construct()
15+
{
16+
$this->middleware('auth:admin');
17+
}
18+
19+
/**
20+
* Show the application dashboard.
21+
*
22+
* @return \Illuminate\Http\Response
23+
*/
24+
public function index()
25+
{
26+
return view('admin.home');
27+
}
28+
}

app/Http/Controllers/Auth/LoginController.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use App\Http\Controllers\Controller;
66
use Illuminate\Foundation\Auth\AuthenticatesUsers;
7+
use Illuminate\Http\Request;
78

89
class LoginController extends Controller
910
{
@@ -27,6 +28,14 @@ class LoginController extends Controller
2728
*/
2829
protected $redirectTo = '/home';
2930

31+
// 单位时间内最大登录尝试次数
32+
//protected $maxAttempts = 3;
33+
// 单位时间值
34+
//protected $decayMinutes = 30;
35+
36+
// 支持的登录字段
37+
protected $supportFields = ['name', 'email'];
38+
3039
/**
3140
* Create a new controller instance.
3241
*
@@ -36,4 +45,21 @@ public function __construct()
3645
{
3746
$this->middleware('guest')->except('logout');
3847
}
48+
49+
/*public function username()
50+
{
51+
return 'name';
52+
}*/
53+
54+
// 将支持的登录字段都传递到 UserProvider 进行查询
55+
public function credentials(Request $request)
56+
{
57+
$credentials = $request->only($this->username(), 'password');
58+
foreach ($this->supportFields as $field) {
59+
if (empty($credentials[$field])) {
60+
$credentials[$field] = $credentials[$this->username()];
61+
}
62+
}
63+
return $credentials;
64+
}
3965
}

app/Http/Controllers/HomeController.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Http\Controllers;
44

55
use Illuminate\Http\Request;
6+
use Illuminate\Support\Facades\Auth;
67

78
class HomeController extends Controller
89
{

app/Http/Controllers/TaskController.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,15 @@ public function home()
1414

1515
public function index()
1616
{
17+
dd('tasks');
1718
return view('task.index')->with('tasks', Task::all());
1819
}
1920

21+
public function index2()
22+
{
23+
dd('tasks2');
24+
}
25+
2026
public function create()
2127
{
2228

app/Http/Kernel.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class Kernel extends HttpKernel
3535
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
3636
\App\Http\Middleware\VerifyCsrfToken::class,
3737
\Illuminate\Routing\Middleware\SubstituteBindings::class,
38+
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
3839
],
3940

4041
'api' => [

app/Http/Middleware/Authenticate.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@
22

33
namespace App\Http\Middleware;
44

5+
use Illuminate\Auth\AuthenticationException;
56
use Illuminate\Auth\Middleware\Authenticate as Middleware;
67

78
class Authenticate extends Middleware
89
{
10+
protected $redirectTo = '';
11+
912
/**
1013
* Get the path the user should be redirected to when they are not authenticated.
1114
*
@@ -16,4 +19,27 @@ protected function redirectTo($request)
1619
{
1720
return route('login');
1821
}
22+
23+
protected function authenticate($request, array $guards)
24+
{
25+
if (empty($guards)) {
26+
$guards = [null];
27+
}
28+
29+
foreach ($guards as $guard) {
30+
if ($this->auth->guard($guard)->check()) {
31+
return $this->auth->shouldUse($guard);
32+
}
33+
}
34+
35+
// 这里我们以 guards 传入的第一个参数为准选择跳转到的登录页面
36+
$guard = $guards[0];
37+
if ($guard == 'admin') {
38+
$this->redirectTo = route('admin.login');
39+
}
40+
41+
throw new AuthenticationException(
42+
'Unauthenticated.', $guards, $this->redirectTo ? : $this->redirectTo($request)
43+
);
44+
}
1945
}

app/Http/Middleware/RedirectIfAuthenticated.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ class RedirectIfAuthenticated
1818
public function handle($request, Closure $next, $guard = null)
1919
{
2020
if (Auth::guard($guard)->check()) {
21+
if ($guard == 'admin') {
22+
return redirect('/admin');
23+
}
2124
return redirect('/home');
2225
}
2326

app/Providers/AuthServiceProvider.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22

33
namespace App\Providers;
44

5+
use App\Extentions\EloquentUserProvider;
6+
use Illuminate\Support\Facades\Auth;
57
use Illuminate\Support\Facades\Gate;
68
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
9+
use Laravel\Passport\Passport;
710

811
class AuthServiceProvider extends ServiceProvider
912
{
@@ -25,7 +28,12 @@ public function boot()
2528
{
2629
$this->registerPolicies();
2730

28-
//
31+
// 通过自定义的 EloquentUserProvider 覆盖系统默认的
32+
Auth::provider('eloquent', function ($app, $config) {
33+
return new EloquentUserProvider($app->make('hash'), $config['model']);
34+
});
35+
36+
Passport::routes();
2937
}
3038

3139
}

app/User.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@
99
use Illuminate\Notifications\Notifiable;
1010
use Illuminate\Contracts\Auth\MustVerifyEmail;
1111
use Illuminate\Foundation\Auth\User as Authenticatable;
12+
use Laravel\Passport\HasApiTokens;
1213

1314
class User extends Authenticatable
1415
{
15-
use Notifiable;
16+
use HasApiTokens, Notifiable;
1617

1718
/**
1819
* The attributes that are mass assignable.
@@ -67,9 +68,9 @@ protected static function boot()
6768
parent::boot();
6869

6970
//static::addGlobalScope(new EmailVerifiedAtScope());
70-
static::addGlobalScope('email_verified_at_scope', function (Builder $builder) {
71+
/*static::addGlobalScope('email_verified_at_scope', function (Builder $builder) {
7172
return $builder->whereNotNull('email_verified_at');
72-
});
73+
});*/
7374
}
7475

7576
public function profile()

0 commit comments

Comments
 (0)