2016-04-12 3 views
0

Я сейчас делаю webapp с laravel. Я использую встроенную систему аутентификации laravel и добавляю ранги самостоятельно. Однако, когда вы вошли в систему, вы не можете попасть на страницу регистрации. Я хочу, чтобы только администраторы могли создавать новых пользователей.Laravel 5.2 Auth Страница регистрации заблокирована

Мои маршруты:

Route::group(['middleware' => ['web']], function() { 
    Route::get('login', ['as' => 'auth.login', 'uses' => 'Auth\[email protected]']); 
    Route::post('login', ['as' => 'auth.login', 'uses' => 'Auth\[email protected]']); 
    Route::get('logout', ['as' => 'auth.logout', 'uses' => 'Auth\[email protected]']); 

// Password Reset Routes... 
    Route::get('password/reset/{token?}', ['as' => 'auth.password.reset', 'uses' => 'Auth\[email protected]']); 
    Route::post('password/email', ['as' => 'auth.password.email', 'uses' => 'Auth\[email protected]']); 
    Route::post('password/reset', ['as' => 'auth.password.reset', 'uses' => 'Auth\[email protected]']); 

    Route::get('/home', '[email protected]'); 
}); 

Route::group(['middleware' => ['CheckAdmin']], function() { 
    // Registration Routes... 
    Route::get('/register', 'Auth\[email protected]'); 
    Route::post('/register', 'Auth\[email protected]'); 
}); 

Мои AuthController

<?php 

namespace App\Http\Controllers\Auth; 

use App\Models\User; 
use Validator; 
use App\Http\Controllers\Controller; 
use Illuminate\Foundation\Auth\ThrottlesLogins; 
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; 
use Illuminate\Support\Facades\Auth; 

class AuthController extends Controller 
{ 
    /* 
    |-------------------------------------------------------------------------- 
    | Registration & Login Controller 
    |-------------------------------------------------------------------------- 
    | 
    | This controller handles the registration of new users, as well as the 
    | authentication of existing users. By default, this controller uses 
    | a simple trait to add these behaviors. Why don't you explore it? 
    | 
    */ 

    use AuthenticatesAndRegistersUsers; 

    protected $redirectTo = '/admin'; 

    /** 
    * Create a new authentication controller instance. 
    * 
    * @param \Illuminate\Contracts\Auth\Guard $auth 
    * @param \Illuminate\Contracts\Auth\Registrar $registrar 
    * @return void 
    */ 
    public function __construct() 
    { 
     $this->middleware('guest', ['except' => 'logout']); 
    } 

    public function getRegister() 
    { 
     return redirect('/'); 
    } 

    public function postRegister() 
    { 
     return redirect('/'); 
    } 

    /** 
    * 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, [ 
      '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 
    */ 
    protected function create(array $data) 
    { 
     return User::create([ 
      'name' => $data['name'], 
      'email' => $data['email'], 
      'password' => bcrypt($data['password']), 
     ]); 
    } 

    /** 
    * Returns either ADMIN or USER based on user's rank 
    * Returns false if user is not logged in 
    */ 
    public static function getType() 
    { 
     if (Auth::check()) { 
      return Auth::user()->type; 
     } 
     else { 
      return false; 
     } 
    } 
} 

Я пробовал много учебников найти в Интернете, но ни один из тех, кто работает для меня. У кого-нибудь есть решение для меня? Заранее спасибо!

+0

есть вы создаете администраторский middleware'? –

+0

У меня есть да, это называется CheckAdmin. Это хорошо работает, насколько я знаю –

ответ

1

Попробуйте это несколько вещей, чтобы добавить:

Создать администратор межплатформенное с:

public function handle($request, Closure $next) 
    { 
    if (Auth::check() && Auth::user()->isAdmin()) 
    { 
     return $next($request); 
    } 
    return redirect('/home'); 
} 

Затем добавьте эту строку в Kernel.php под $ routeMiddleware:

'admin' => \App\Http\Middleware\Admin::class, 

Put администратор маршруты in:

Route::group(['middleware' => ['auth', 'admin']], function() { 
    //here 
}); 

Это идет внутри промежуточного слоя => веб-групп

Других маршрутов здесь:

Route::group(['middleware' => 'web'], function() { 
    //here 
}); 

Добавьте к каждому контроллеру у вас есть:

public function __construct() { $this->middleware('auth'); } 
+0

Спасибо за ответ, Однако, добавив это: 'public function __construct() {$ this-> middleware ('auth'); } ' делает крушение сайта для гостей или как только я выхожу из системы. Я смог попасть на страницу регистрации как admin now –

+0

Попробуйте перетасовать маршруты. Каждый маршрут, включая маршруты группы администратора, должен быть в промежуточной веб-группе –

+0

Ты мой герой! Это привело меня к правильному пути! В AuthController.php я просто должен был изменить конструктор для этого: 'общественной функция __construct() { $ this-> промежуточного программного обеспечения ('CheckAdmin', [ 'кроме' => 'отключала']); } ' –