Laravel技巧之Sentry2开启前后台分开用户登陆

时间:14-09-28 栏目:Laravel网站建设, SEO优化, 数据库 作者:kyle 评论:1 点击: 9,949 次

Laravel是目前正在使用的一套框架,使用起来非常顺手,目前用于开发公司内部的各种后台运行的程序和任务。

Sentry2是一套比较完整的用户管理代码,允许用户分组和登陆注册管理。非常方便。

 

最近有需求开发一套用户管理后台,需要把前台用户和后台用户的资料和帐号等等全部分开管理。于是需要对Sentry进行改进使用。

 

初步定义后台管理到时候是SentryAdmin,前台管理是Sentry。

一、定义Model数据库模型

在Model目录下面创建Admin.php

<?php
namespace App\Models;

use Eloquent;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class Admin extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {

    protected $table = 'admins';

    protected $guarded = array(
    );

    protected $fillable = array(
    );

    public static $rules = array(
    );

    /**
     * sentry methods
     */
    public function groups(){ return $this->belongsToMany('Cartalyst\Sentry\Groups\Eloquent\Group', 'admins_groups'); }
    public function getAuthIdentifier(){ return $this->getKey(); }
    public function getAuthPassword(){ return $this->password; }
    public function getReminderEmail(){ return $this->email; }

}

 

二、创建 SentryAdmin的服务提供器SentryAdminServiceProvider

1、创建目录app/lib/SentryMods

2、在这个目录建立 文件SentryAdmin.php

<?php namespace Lib\SentryMods;
use Illuminate\Support\Facades\Facade;
class SentryAdmin extends Facade {
    protected static function getFacadeAccessor(){ return 'sentry.admin'; }
}

3、再创建一个SentryAdminServiceProvider.php

<?php namespace Lib\SentryMods;
 
use Cartalyst\Sentry\Cookies\IlluminateCookie;
use Cartalyst\Sentry\Groups\Eloquent\Provider as GroupProvider;
use Cartalyst\Sentry\Hashing\BcryptHasher;
use Cartalyst\Sentry\Hashing\NativeHasher;
use Cartalyst\Sentry\Hashing\Sha256Hasher;
use Cartalyst\Sentry\Sentry;
use Cartalyst\Sentry\Sessions\IlluminateSession;
use Cartalyst\Sentry\Throttling\Eloquent\Provider as ThrottleProvider;
use Cartalyst\Sentry\Users\Eloquent\Provider as UserProvider;
use Illuminate\Support\ServiceProvider;
 
class SentryAdminServiceProvider extends ServiceProvider {
 
    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot(){
        $this->observeEvents();
    }
 
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register(){
        $this->registerHasher();
        $this->registerUserProvider();
        $this->registerGroupProvider();
        $this->registerThrottleProvider();
        $this->registerSession();
        $this->registerCookie();
        $this->registerSentry();
    }
 
    /**
     * Register the hasher used by Sentry.
     *
     * @return void
     */
    protected function registerHasher(){
        $this->app['sentry.admin.hasher'] = $this->app->share(function($app){
            $hasher = $app['config']['cartalyst/sentry::config.admin.hasher'];
 
            switch ($hasher){
                case 'native':
                    return new NativeHasher;
                    break;
 
                case 'bcrypt':
                    return new BcryptHasher;
                    break;
 
                case 'sha256':
                    return new Sha256Hasher;
                    break;
            }
 
            throw new \InvalidArgumentException("Invalid hasher [$hasher] chosen for Sentry.");
        });
    }
 
    /**
     * Register the user provider used by Sentry.
     *
     * @return void
     */
    protected function registerUserProvider(){
        $this->app['sentry.admin.user'] = $this->app->share(function($app){
            $model = $app['config']['cartalyst/sentry::config.admin.users.model'];
 
            // We will never be accessing a user in Sentry without accessing
            // the user provider first. So, we can lazily setup our user
            // model's login attribute here. If you are manually using the
            // attribute outside of Sentry, you will need to ensure you are
            // overriding at runtime.
            if (method_exists($model, 'setLoginAttribute')){
                $loginAttribute = $app['config']['cartalyst/sentry::sentry.users.login_attribute'];
                forward_static_call_array(
                    array($model, 'setLoginAttribute'),
                    array($loginAttribute)
                );
            }
 
            return new UserProvider($app['sentry.admin.hasher'], $model);
        });
    }
 
    /**
     * Register the group provider used by Sentry.
     *
     * @return void
     */
    protected function registerGroupProvider(){
        $this->app['sentry.admin.group'] = $this->app->share(function($app){
            $model = $app['config']['cartalyst/sentry::config.admin.groups.model'];
            return new GroupProvider($model);
        });
    }
 
    /**
     * Register the throttle provider used by Sentry.
     *
     * @return void
     */
    protected function registerThrottleProvider(){
        $this->app['sentry.admin.throttle'] = $this->app->share(function($app){
            $model = $app['config']['cartalyst/sentry::sentry.throttling.model'];
 
            $throttleProvider = new ThrottleProvider($app['sentry.admin.user'], $model);
 
            if ($app['config']['cartalyst/sentry::config.admin.throttling.enabled'] === false){
                $throttleProvider->disable();
            }
            if (method_exists($model, 'setAttemptLimit')){
                $attemptLimit = $app['config']['cartalyst/sentry::config.admin.throttling.attempt_limit'];
 
                forward_static_call_array(
                    array($model, 'setAttemptLimit'),
                    array($attemptLimit)
                );
            }
            if (method_exists($model, 'setSuspensionTime')){
                $suspensionTime = $app['config']['cartalyst/sentry::config.admin.throttling.suspension_time'];
                forward_static_call_array(
                    array($model, 'setSuspensionTime'),
                    array($suspensionTime)
                );
            }
            return $throttleProvider;
        });
    }
 
    /**
     * Register the session driver used by Sentry.
     *
     * @return void
     */
    protected function registerSession()
    {
        $this->app['sentry.admin.session'] = $this->app->share(function($app)
        {
            return new IlluminateSession($app['session']);
        });
    }
 
    /**
     * Register the cookie driver used by Sentry.
     *
     * @return void
     */
    protected function registerCookie()
    {
        $this->app['sentry.admin.cookie'] = $this->app->share(function($app)
        {
            return new IlluminateCookie($app['cookie']);
        });
    }
 
    /**
     * Takes all the components of Sentry and glues them
     * together to create Sentry.
     *
     * @return void
     */
    protected function registerSentry()
    {
        $this->app['sentry.admin'] = $this->app->share(function($app)
        {
            // Once the authentication service has actually been requested by the developer
            // we will set a variable in the application indicating such. This helps us
            // know that we need to set any queued cookies in the after event later.
            $app['sentry.admin.loaded'] = true;
 
            return new Sentry(
                $app['sentry.admin.user'],
                $app['sentry.admin.group'],
                $app['sentry.admin.throttle'],
                $app['sentry.admin.session'],
                $app['sentry.admin.cookie'],
                $app['request']->getClientIp()
            );
        });
    }
 
    /**
     * Sets up event observations required by Sentry.
     *
     * @return void
     */
    protected function observeEvents()
    {
        // Set the cookie after the app runs
        $app = $this->app;
        $this->app->after(function($request, $response) use ($app)
        {
            if (isset($app['sentry.admin.loaded']) and $app['sentry.admin.loaded'] == true and ($cookie = $app['sentry.admin.cookie']->getCookie()))
            {
                $response->headers->setCookie($cookie);
            }
        });
    }
 
}

 

三、新建Config文件。

文件位于app/config/cartalyst/sentry/config.php

添加如下代码

'admin'=>array(
        'driver' => 'eloquent',
        'hasher' => 'native',
        'groups' => array(
            'model' => 'Cartalyst\Sentry\Groups\Eloquent\Group',
        ),
        'cookie' => array(
            'key' => 'cartalyst_sentry',
        ),
        'users' => array(
            'model' => 'App\Models\Admin',
            'login_attribute' => 'login',
        ),
        'throttling' => array(
            'enabled' => true,
            'model' => 'Cartalyst\Sentry\Throttling\Eloquent\Throttle',
            'attempt_limit' => 5,
            'suspension_time' => 15,
        ),
    ),

 

四、准备数据库,把原来的users和groups复制一个出来变成admin_users和admin_groups

 

五、自动加载配置的类库

在composer.json里面添加节autoload里面加上"app/lib"

 

六、测试是否正确加载

<?php
print_r(Sentry::getUserProvider());
print_r(SentryAdmin::getUserProvider());
?>

置于任何模板载入即可判断是否加载成功。

 

上面是国外的资料显示的方法,实践证明还有些需要改。

七、在app/app.php里面

providers节增加:'Lib\SentryMods\SentryAdminServiceProvider'

aliases节增加:'SentryAdmin' => 'Lib\SentryMods\SentryAdmin'

 

八、Model目录的admin.php还需要增加

    public function getRememberToken()
    {
        return $this->remember_token;
    }

    public function setRememberToken($value)
    {
        $this->remember_token = $value;
    }

    public function getRememberTokenName()
    {
        return 'remember_token';
    }

 

九、SentryAdminServiceProvider.php还需要修改一下

observeEvents()方法里面的getCookies()改成get()。即可完成。

 

Sentry官方又出来一个升级 的sentinel框架。可以管理多组用户,功能更强大,还可以防DDOS。不过现在需要付费使用,75刀3个月。

等过段时间看看再升级了。

 

要快速搭建属于你自己的注册登陆验证激活后台,使用这个是不二之选。方便快捷。

成都SEO小五嚎2句: 本文是(成都SEO小五)辛苦弄出来的,转载成都SEO小五原创的请保留链接: Laravel技巧之Sentry2开启前后台分开用户登陆,3Q

Laravel技巧之Sentry2开启前后台分开用户登陆:目前有1 条留言,牛逼吧!

  1. 沙发
    321111:

    😛 😛 🙁 🙁 👿 ❗

    2015-04-24 9:29 am [回复]

来给哥评论评论


------====== 小五公告 ======------
成都SEO小五,专注成都搜索引擎优化。
小五善长站内外优化,C#、PHP开发,中英文SEO,Google中英文和百度优化技术。欢迎群内交流。伸手党请绕路,求资源的请绕开,求问题解答的请进群内交流。开放了一个QQ交流群:160750032。加入验证时请标注任何SEO相交字眼。友情链接直接Q我,收录正常,内容大部份原创、SEO或者程序开发、网络营销、线上推广等相关行业即可。

常用工具

赞助广告

来看过哥的人