laravel 後臺登陸
阿新 • • 發佈:2019-01-08
一: 新建管理員表admins,欄位和users一致,其餘欄位可以自定義新增
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAdminsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('admins', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->nullable(); $table->string('password'); $table->string('salt'); $table->integer('login_num')->comment('登陸次數'); $table->integer('last_login')->comment('最後登陸時間'); $table->integer('admin_rank_id')->comment('等級id'); $table->foreign('admin_rank_id')->references('id')->on('admin_rank'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('admins'); } }
二: 後臺新增管理員
controller
request/** * 建立新管理員表單頁面 * * @return Response */ public function create() { $admin = $this->dispatch(new AdminFormFields()); $admin_ranks = AdminRank::all(); return view('admin/admin/create', ['admin' => $admin, 'admin_ranks' => $admin_ranks]); } /** * 將新建立的管理員儲存到儲存器 * * @param Request $request * @return Response */ public function store(AdminRequest $request) { if($request->input('password') != $request->input('confirm_password')) { return redirect('admin/admins'); } $admin = Admin::create($request->fillData()); return redirect('admin/admins'); }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'email' => 'required', 'password' => 'required', ]; } /** * Return the fields and values to create a new post from */ public function fillData() { $salt = mt_rand(1000, 9999); $password = $this->password.$salt; return [ 'name' => $this->name, 'email' => $this->email, 'password' => bcrypt($password), 'salt' => $salt, 'login_num' => 1, 'last_login' => time(), 'admin_rank_id' => $this->admin_rank_id, ]; }
form
protected $fieldList = [
'name' => '',
'email' => '',
'password' => '',
'admin_rank_id' => '',
];
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($id = null)
{
$this->id = $id;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$fields = $this->fieldList;
if ($this->id) {
$fields = Admin::findOrFail($this->id);
}
return $fields;
}
三:新增auth的admin配置:config/auth.php,並新增路由
auth.php配置
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
路由:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function(){
// 控制器在 "App\Http\Controllers\Admin" 名稱空間下
Route::resource('admins', 'AdminController');
Route::resource('admin_ranks','AdminRankController');
Route::get('login', '[email protected]');
Route::post('login', '[email protected]_in');
Route::get('logout', '[email protected]');
});
四:自定義登陸中介軟體
middware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminAuthMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('admin/login');
}
}
return $next($request);
}
}
將中介軟體新增到kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'auth.admin' => \App\Http\Middleware\AdminAuthMiddleware::class,
];
為路由新增中介軟體
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function(){
// 控制器在 "App\Http\Controllers\Admin" 名稱空間下
Route::group(['middleware' => 'auth.admin:admin'], function () {
Route::resource('admins', 'AdminController');
Route::resource('admin_ranks','AdminRankController');
});
Route::get('login', '[email protected]');
Route::post('login', '[email protected]_in');
Route::get('logout', '[email protected]');
});
五: 登陸
登陸表單直接使用使用者表單就可以
登陸後臺
<?php
namespace App\Http\Controllers\Admin;
use App\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class AuthController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = 'admin/friend_links'; //這個是登入成功的重定向連結,有時候需要修改。
protected $guard = 'admin';
public function login()
{
return view('admin/auth/login');
}
public function login_in(Request $request)
{
$name = $request->input('user_name');
$password = $request->input('password');
if(empty($name) || empty($password))
{
return redirect('admin/login');
}
$has_user = Admin::where('name', $name)->count();
if($has_user > 0){
$user = Admin::where('name', $name)->first();
$password = $password.$user['salt'];
if (Auth::guard('admin')->attempt(['name' => $name, 'password' => $password]))
{
$admin = Auth::guard('admin')->user();
return redirect('admin/friend_links');
} else {
return redirect('admin/login');
}
} else {
return redirect('admin/login');
}
}
public function logout(Request $request)
{
Auth::guard('admin')->logout();
$request->session()->forget($this->guard()->getName());
$request->session()->regenerate();
return redirect('admin/login');
}
/**
* 自定義認證驅動
* @return mixed
*/
protected function guard()
{
return Auth::guard($this->guard);
}
/**
* 重寫驗證時使用的使用者名稱欄位
*/
//public function username()
//{
// return 'name';
//}
}
?>