Laravel 4.2-如何仅允许已登录/授权用户访问

时间:2014-08-19 10:32:10

标签: php laravel-4 laravel-routing

我创建了登录表单并使用Auth方法通过电子邮件和密码授权用户。登录完成是HomeControler中的doLogin功能

public function doLogin()
    {

        $rules = array(
            'email'    => 'required|email', // make sure the email is an actual email
            'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
        );


        $validator = Validator::make(Input::all(), $rules);


        if ($validator->fails()) {
            return Redirect::to('login')
                ->withErrors($validator) // send back all errors to the login form
                ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
        } else {


            $userdata = array(
                'email'     => Input::get('email'),
                'password'  => Input::get('password')
            );


            if (Auth::attempt($userdata)) {

            $id = Auth::id();

            return Redirect::to('panel');

            } else {        


                return Redirect::to('login');

            }

        }
    }

在我的routes.php文件中,我创建了通过id获取用户的路由,然后检查用户是否已登录。

Route::get('panel/{id}', array('before' => 'auth', function($id)
{   
    $user=User::find($id);
    dd($user);

}));

到目前为止,我遇到了两个问题:

  1. - 如何在doLogin函数中创建带有get参数的路由,以便在面板/ id /地址中重定向用户?
    返回Redirect :: to('panel') - > with('id',$ id);不起作用!

  2. 第二个问题是panel / {id}路由正在检查用户是否使用'before'=>登录'auth',但如果我使用用户ID 1登录然后打开地址面板/ 2 /它将打开当前路线。我如何使laravel检查记录在mit中的用户ID打开当前路由。如何让laravel检查登录的用户ID是否与路由中请求的用户ID匹配?是否在路由中请求用户ID?

1 个答案:

答案 0 :(得分:0)

只需从BaseController扩展您想要授权的所有控制器。

BaseController可能是

class BaseController extends Controller {
  public function __construct() {
    $this->beforeFilter('auth');
  }
}

然后忘掉它,它运作正常。

相关问题