不知道爲何,不喜歡Lumen的Auth,把TP的Auth遷移過來了

看到lumen auth 要更改幾個文件,不是很喜歡。 就把Thinkphp上的auth權限驗證遷移到lumen上了。 文件位置php

\Service\General\Auth.php
複製代碼

感悟: 熟悉了whereIn,join的用法。 whereIn數據庫

$rules =DB::table($this->_config['tab_auth_rule'])->where($map)->whereIn('id',$ids)->get(['condition','name']);

複製代碼

joinjson

$user_groups = DB::table($this->_config['tab_auth_group_access'] .' as a')
            ->join($this->_config['tab_auth_group']." as g", function(JoinClause $join) use($uid){
                $join->on('g.id', '=', 'a.group_id')
                    ->where('a.uid',  '=', $uid)
                ;
            })
複製代碼

Controller用法數組

public function test()
    {

        $service    =   new AuthService();
        $cauth  =   $service->check('admin/index/index',6) == false ? 0 : 1;

        return $cauth;  //0爲失敗,1爲成功
    }
複製代碼

查表語法已經修正,可用.bash

<?php
/**
 * Created by PhpStorm.
 * User: whoami
 * Date: 19-1-25
 * Time: 下午1:04
 */

namespace App\Service\General;

use App\Models\funx\TabAuthGroupAccess;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\JoinClause;

/**
 * Class AuthService
 * @package App\Service\General
 * 用戶驗證流程
 */
class AuthService
{
    protected $_config = array(
        'auth_on'           => true,                      // 認證開關
        'auth_type'         => 1,                         // 認證方式,1爲實時認證;2爲登陸認證。
        'tab_auth_group'        => 'tab_auth_group',        // 用戶組數據表名
        'tab_auth_group_access' => 'tab_auth_group_access', // 用戶-用戶組關係表
        'tab_auth_rule'         => 'tab_auth_rule',         // 權限規則表
        'tab_auth_user'         => 'tab_users'             // 用戶信息表
    );
    public function __construct() {
        $t=config('auth_config');
        if (config('auth_config')) {
            //可設置配置項 auth_config, 此配置項爲數組。
            $this->_config = array_merge($this->_config, config('auth_config'));
        }
    }
    /**
     * 檢查權限
     * @param name string|array  須要驗證的規則列表,支持逗號分隔的權限規則或索引數組
     * @param uid  int           認證用戶的id
     * @param string mode        執行check的模式
     * @param relation string    若是爲 'or' 表示知足任一條規則即經過驗證;若是爲 'and'則表示需知足全部規則才能經過驗證
     * @return boolean           經過驗證返回true;失敗返回false
     */
    public function check($name, $uid, $type=1, $mode='url', $relation='or') {
        if (!$this->_config['auth_on'])
            return true;
        $authList = $this->getAuthList($uid,$type); //獲取用戶須要驗證的全部有效規則列表
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = array($name);
            }
        }
        $list = array(); //保存驗證經過的規則名
        if ($mode=='url') {
            $REQUEST = unserialize( strtolower(serialize($_REQUEST)) );
        }
        foreach ( $authList as $auth ) {
            $query = preg_replace('/^.+\?/U','',$auth);
            if ($mode=='url' && $query!=$auth ) {
                parse_str($query,$param); //解析規則中的param
                $intersect = array_intersect_assoc($REQUEST,$param);
                $auth = preg_replace('/\?.*$/U','',$auth);
                if ( in_array($auth,$name) && $intersect==$param ) {  //若是節點相符且url參數知足
                    $list[] = $auth ;
                }
            }else if (in_array($auth , $name)){
                $list[] = $auth ;
            }
        }
        if ($relation == 'or' && !empty($list)) {
            return true;
        }

        $diff = array_diff($name, $list);

        if ($relation == 'and' && empty($diff)) {
            return true;
        }
        return false;
    }

    /**
     * 根據用戶id獲取用戶組,返回值爲數組
     * @param  uid int     用戶id
     * @return array       用戶所屬的用戶組 array(
     *     array('uid'=>'用戶id','group_id'=>'用戶組id','title'=>'用戶組名稱','rules'=>'用戶組擁有的規則id,多個,號隔開'),
     *     ...)
     */
    public function getGroups($uid) {
        static $groups = array();
        if (isset($groups[$uid]))
            return $groups[$uid];
        $user_groups = DB::table($this->_config['tab_auth_group_access'] .' as a')
            ->join($this->_config['tab_auth_group']." as g", function(JoinClause $join) use($uid){
                $join->on('g.id', '=', 'a.group_id')
                    ->where('a.uid',  '=', $uid)
                ;
            })
            ->where([['a.uid',$uid],['g.status',1]])//"a.uid".$uid.' and g.status='1'" ->select(['uid','group_id','title','rules']); // print_r(json_decode(json_encode($user_groups),true));exit; $groups[$uid] = !empty($user_groups) ? $user_groups->get() : array(); return $groups[$uid]; } /** * 得到權限列表 * @param integer $uid 用戶id * @param integer $type */ protected function getAuthList($uid,$type) { static $_authList = array(); //保存用戶驗證經過的權限列表 $t = implode(',',(array)$type); if (isset($_authList[$uid.$t])) { return $_authList[$uid.$t]; } if( $this->_config['auth_type']==2 && isset($_SESSION['_auth_list_'.$uid.$t])){ return $_SESSION['_auth_list_'.$uid.$t]; } //讀取用戶所屬用戶組 $groups = $this->getGroups($uid); $groups = obj2arr($groups); //對象轉換 $ids = array();//保存用戶所屬用戶組設置的全部權限規則id foreach ($groups as $g) { $ids = array_merge($ids, explode(',', trim($g['rules'], ','))); } $ids = array_unique($ids); if (empty($ids)) { $_authList[$uid.$t] = array(); return array(); } $map=[ ['type',$type], ['status',1] ]; //讀取用戶組全部權限規則 $rules =DB::table($this->_config['tab_auth_rule'])->where($map)->whereIn('id',$ids)->get(['condition','name']); $rules = obj2arr($rules); //循環規則,判斷結果。 $authList = array(); // foreach ($rules as $rule) { if (!empty($rule['condition'])) { //根據condition進行驗證 $user = $this->getUserInfo($uid);//獲取用戶信息,一維數組 $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']); //dump($command);//debug @(eval('$condition=(' . $command . ');')); if ($condition) { $authList[] = strtolower($rule['name']); } } else { //只要存在就記錄 $authList[] = strtolower($rule['name']); } } $_authList[$uid.$t] = $authList; if($this->_config['auth_type']==2){ //規則列表結果保存到session $_SESSION['_auth_list_'.$uid.$t]=$authList; } return array_unique($authList); } /** * 得到用戶資料,根據本身的狀況讀取數據庫 */ protected function getUserInfo($uid) { static $userinfo=array(); if(!isset($userinfo[$uid])){ $userinfo[$uid]=DB::table($this->_config['tab_auth_user'])->where('uid',$uid)->get(); } return $userinfo[$uid]; } } 複製代碼
相關文章
相關標籤/搜索