我的 laravel4 应用程序中有一个 Personcontroller 和一个 Festivalcontroller。这些控制器中的操作只能由管理员访问。
如果我的数据库只有 test@hotmail.com 的用户,该用户可以访问这 2 个控制器的路由。如果我的数据库没有 test@hotmail.com 的用户,但它有其他用户,则其他用户无法访问这 2 个控制器的路由。当我的数据库有一个用户 test@hotmail.com 并且有其他用户时,每个人都可以访问这两个控制器的路由。
我只希望使用电子邮件 test@hotmail.com 的用户访问这些控制器的路由。
我通过这样做安装了 Sentry2:
在 composer.json 文件中需要:
"cartalyst/sentry": "2.0.*"
跑
php composer.phar update
在应用 > 配置 > app.php 中:
'Cartalyst\Sentry\SentryServiceProvider',
=> 到提供者数组
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry',
=> 到别名数组
安装后我制作了 SentrySeeder 文件:
<?php
class SentrySeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
DB::table('groups')->delete();
DB::table('users_groups')->delete();
Sentry::getUserProvider()->create(array(
'email' => 'test@hotmail.com',
'password' => "test",
'activated' => 1,
));
$user = Sentry::getUserProvider()->findByLogin('test@hotmail.com');
$adminGroup = Sentry::getGroupProvider()->findByName('Test');
$user->addGroup($adminGroup);
}
}
在我的 PersonController
class PersonController extends BaseController {
public function index()
{
try
{
$user = Sentry::findUserByLogin('test@hotmail.com');
if ($user)
{
$person = Person::with('user')->orderBy('person_id')->paginate(10);
return View::make('persons.index')
->with('person', $person);
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
}
}
LoginController 中的登录操作
public function login()
{
$input = Input::all();
$rules = array(
'user_email' => 'required',
'user_password' => 'required'
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('user_password'));
}
else {
$attempt = Auth::attempt([
'user_email' => $input['user_email'],
'password' => $input['user_password']
]);
if ($attempt) {
return Redirect::to('/home');
}
else {
return Redirect::to('login');
}
}
在数据库中存储用户
public function store()
{
$input = Input::all();
$rules = array(
'user_email' => 'required|unique:users|email',
'user_username' => 'required|unique:users',
);
$validator = Validator::make($input, $rules);
if($validator->passes())
{
$password = $input['user_password'];
$password = Hash::make($password);
$location = new Location();
$person = new Person();
$user = new User();
$person->person_firstname = $input['person_firstname'];
$person->person_surname = $input['person_surname'];
$user->user_username = $input['user_username'];
$user->user_email = $input['user_email'];
$user->user_password = $password;
$location->save();
$person->save();
$user->location()->associate($location);
$user->person()->associate($person);
$user->save();
Session::flash('message', 'Successfully created user!');
return Redirect::to('login');
}
else {
return Redirect::to('persons/create')->withInput()->withErrors($validator);
}
}