fastAdmin 框架api模块认证问题

fastAdmin 自带三个模块分别是:admin模块,api模块,index前台模块

admin模块使用app\admin\library\Auth.php作为认证基类,在app\common\controller\Backend.php中被定义

api模块和index模块使用app\common\library\Auth.php作为认证基类,在app\common\controller\Api.php和Frontend.php中被定义

那么就会出现一个问题,api应用和index应用只能认证会员,admin应用只能认证管理员。对于一下简单应用,我想直接已管理员身份调用api,就需要重写api模块认证基类。

配置app\common\controller\Api.php

//重写的api认证类
namespace app\common\controller;

use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;
use app\common\library\AdminAuth;
use think\exception\ValidateException;
use think\exception\HttpResponseException;

/**
 * API控制器基类
 */
class Api{ 
 
   /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize(){
        /*
         * 初始化认证基类 修改为AdminAuth
         */
        $this->auth = AdminAuth::instance();
    }
}

实现app\common\controller

// 辅助app\common\controller\Auth.php
// 修改init() 和 direct()方法
namespace app\common\library;

use think\Db;
use think\Hook;
use fast\Random;
use think\Config;
use think\Request;
use think\Validate;
use think\Exception;
use app\admin\model\Admin;

/**
 * Auth认证类
 */
class AdminAuth{
  
    /**
     * 根据Token初始化
     *
     * @param string $token Token
     * @return boolean
     */
    public function init($token){
        if ($this->_logined) {
            return true;
        }
        if ($this->_error) {
            return false;
        }
        $data = Token::get($token);
        if (!$data) {
            return false;
        }
        $user_id = intval($data['user_id']);
        
        if ($user_id > 0) {
           // 修改下面代码
            $user = Admin::get($user_id);
            if (!$user) {
                $this->setError('Account not exist');
                return false;
            }
            if ($user['status'] != 'normal') {
                $this->setError('Account is locked');
                return false;
            }
            $this->_user = $user;
            $this->_logined = true;
            $this->_token = $token;
            //初始化成功的事件
            Hook::listen("user_init_successed", $this->_user);
            return true;
        } else {
            $this->setError('You are not logged in');
            return false;
        }
    }

    /**
     * 直接登录账号
     * @param int $user_id
     * @return boolean
     */
    public function direct($user_id){
        $user = Admin::get($user_id);
        if ($user) {
            Db::startTrans();
            try {
                $ip = request()->ip();
                $time = time();
                // 注释下面代码
                // if ($user->logintime < \fast\Date::unixtime('day')) {
                //     $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
                //     $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
                // }
                // $user->prevtime = $user->logintime;
                // //记录本次登录的IP和时间
                // $user->loginip = $ip;
                // $user->logintime = $time;
                //重置登录失败次数
                $user->loginfailure = 0;
                $user->save();
                $this->_user = $user;
                $this->_token = Random::uuid();
                Token::set($this->_token, $user->id, $this->keeptime);
                $this->_logined = true;
                //登录成功的事件
                Hook::listen("user_login_successed", $this->_user);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->setError($e->getMessage());
                return false;
            }
            return true;
        } else {
            return false;
        }
    }
}
Posted in php | Leave a comment

php 控制台打印二维数组

使用

use console\models\PrintTable;

$arr=[
    ['a'=>'aaaa','b'=>'bbbb','c'=>'cbbbb','d'=>'dbbb','e'=>'ebbb','f'=>'fbbb','g'=>'gbbb'],
    ['a'=>'a','b'=>'b','c'=>'c','d'=>'d','e'=>'e','f'=>'f','g'=>'g'],
    ['a'=>'a','b'=>'b','c'=>'c','d'=>'d','e'=>'e','f'=>'f','g'=>'g'],
    ['a'=>'a','b'=>'b','c'=>'c','d'=>'d','e'=>'e','f'=>'f','g'=>'g'],
    ['a'=>'a','b'=>'b','c'=>'c','d'=>'d','e'=>'e','f'=>'f','g'=>'g'],
    ['a'=>'a','b'=>'b','c'=>'c','d'=>'d','e'=>'e','f'=>'f','g'=>'g'],
];
echo PrintTable::Print_table($arr);

效果

效果

实现

namespace console\models;

/**
 * 控制台输入二维数组
 * Class PrintTable
 * @package common\models\tool
 */
class PrintTable{

    /**
     * 计算中文个数
     * @param string $str
     * @return mixed
     */
    private static function getStrLen(string $str){
      return  (strlen($str)- mb_strlen($str))/2;
    }

    /**
     * 计算字符串的字节数
     * @param $str
     * @return bool|false|int|mixed
     */
    private static function getStrByteNumber($str){
       return  mb_strlen($str) + self::getStrLen($str);
    }

    /**
     * 计算数组的最大长度
     * @param $arr
     * @return array
     */
    private static function columnMaxStrLen($arr){
        $keys = array_keys($arr[0]);
        //计算数组的key的长度
        $number_arr=[];
        foreach ($keys as $key){
            $number_arr[] = self::getStrByteNumber($key);
        }
        //计算数组的值长度
        $i=0;
        foreach ($keys as $key){
            $column = array_column($arr ,$key);
            foreach ( $column as $value){
                $str = (string) $value;
                //字符串字节数
                $strNumber =self::getStrByteNumber($str);
                if($number_arr[$i] < $strNumber ){
                    $number_arr[$i] =   $strNumber;
                }
            }
            $i++;
        }
        return $number_arr;
    }

    /**
     * 将一个字符拼接多次
     * @param $int
     * @param string $str
     * @return string
     */
    private static function dump_number($int ,$str ='-'){
        $res ='';
        for ($i=1;$i<=$int;$i++){
            $res .=$str;
        }
        return $res;
    }

    /**
     * 构造分割线
     * @param $maxLens
     * @return string
     */
    private static function intervalStr($maxLens){
        $str ='';
        foreach ($maxLens as $value){
            $str .="+".self::dump_number($value+2 ,'-');
        }
        return $str."-+";
    }

    /**
     * 拼接二维数组的一行
     * @param $maxLens
     * @param $row
     * @return string
     */
    private static function Print_row($maxLens,$row){
        $str ='';
        $i=0;
        foreach ($row as $value){
            $field =  (string) $value;
            $str .="| ". $field;
            //拼接空格
            $str .= self::dump_number($maxLens[$i] +1 - self::getStrByteNumber($field)," ") ;
            $i++;
        }
        return $str." |";
    }

    /**
     * 打印数组
     * @param $arr
     * @param string $str
     * @return string
     */
    public static function Print_table($arr,$str = "\n"){
        //每一列的字符最大字符串长度
        $maxLens = self::columnMaxStrLen($arr);
        //分割线
        $intervalStr = self::intervalStr($maxLens);
        //打印字段
        $fieldStr = self::Print_row($maxLens,array_keys($arr[0]));
        $res = $intervalStr.$str;
        $res .=$fieldStr;
        foreach ($arr as $item){
            $res .= $str.$intervalStr.$str.self::Print_row($maxLens,$item);
        }
        return  $res.$str.$intervalStr.$str;
    }
}
Posted in php | Leave a comment

php QrReader解析二维码数据

在客户端不方便解析二维码图片时,通常是将图片进行base64编码,然后发送给后台服务器进行及解析

安装

#!/usr/bin/env php
composer require khanamiryan/qrcode-detector-decoder

使用

<?php
use Zxing\QrReader;
//使用
if(isset($_POST) and isset($_POST['url_base64'])){
    echo  base64_text($_POST['url_base64']);
}
//定义方法
function base64_text($str){
        $base_img = str_replace('data:image/jpg;base64,', '',$str);
       // 临时文件目录
       $path =dirname(dirname(dirname(__DIR__))).'/runtime/file/'
        //临时文件前缀
        $prefix = "img_";
        //临时文件名称
        $output_file = $prefix.time().rand(100,999).'.jpg';
        $path .=$output_file;
        if( file_put_contents($path, base64_decode($base_img))){
            $qrcode = new QrReader($path);
            $text = $qrcode->text();
            unset($qrcode);
            unlink( $path);
            return $text;
        }
         return false;
    }
>
Posted in php | Leave a comment

wordpress中mac风格代码高亮显示

依赖highlight.jsjQuery

1.将文件上传至wordpress/wp-content/themes并解压

2.编辑主题文件header.php,引入css和js

<!DOCTYPE html>
<html>
    <head>
        <!-- 引入样式文件,根据自己需求修改 -->
        <link rel="stylesheet" 
            href="/wp-content/themes/highlight/styles/monokai_sublime.css"
            type="text/css" >
        <!-- 引入js文件 -->
        <script src="/wp-content/themes/highlight/highlight.pack.js" 
            type="text/javascript" ></script>
        <!-- 引入jQuery -->
        <script src="/wp-content/themes/jquery/dist/jquery.js" 
            type="text/javascript" ></script>
        <!-- mac风格头部 -->
        <style>
            .hljs .tools{
                float: left;
                margin: 5px 5px 6px 5px ;
                width: 10px;height: 10px;
                border-radius: 5px;
                text-align: center;
                line-height: 10px;
            }
        </style>
        <!-- 运行highlight.js -->
        <script>hljs.initHighlightingOnLoad();</script>
    </head>
<body>
</body>
</html>

3. 使用jQuery改变<pre><code></code></pre>样式,编辑footer.php

<script type="text/javascript">
//手字母大写
function titleCase(str) {
    let strArr = str.split(' ');
    for(let i=0;i<strArr.length;i++){
        strArr[i] = strArr[i].substring(0,1).toUpperCase()
          + strArr[i].toLowerCase().substring(1)
    } 
    return strArr.join(' ');
} 
jQuery(function ($) {
    $("pre code").each(function(){
        var lines = $(this).text().split('\n').length ;
	var codename =titleCase($(this).attr("class").split(" ")[2]);
	var str ="<div class='hljs' style='border-top-left-radius: 
            5px;border-top-right-radius: 8px;padding: 3px'>" +
            "<div class='tools' style='background-color: red'></div>" +
            "<div class='tools' style='background-color: yellow'></div>" +
            "<div class='tools' style='background-color:green'></div>" +
	    codename + "</div>";
	console.log(str);
	$(this).parent().prepend(str);
	$(this).css('padding-top','0');
	$(this).css('opacity','0.95');
    });
});
</script>
Posted in wordpress | Leave a comment

原生js首字母大写

function titleCase(str){
    let strArr = str.split(' ');
    for(let i=0;i<strArr.length;i++){
        strArr[i] = strArr[i].substring(0,1).toUpperCase()
            + strArr[i].toLowerCase().substring(1);
    } 
    return strArr.join(' ');
} 

titleCase("ni hao shi guang xiao tou");
// Ni Hao Shi Guang Xiao Tou
Posted in js | Leave a comment

python win32con 剪切板操作

import win32con

# 获取剪切板内容
def get_text():
    w.OpenClipboard()
    d = w.GetClipboardData(win32con.CF_TEXT)
    w.CloseClipboard()
    return d.decode('GBK')

# 设置剪切板内容
def set_text(aString):
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(win32con.CF_TEXT, aString)
    w.CloseClipboard()

# 清空剪切板
def cleat_text():
    w.EmptyClipboard()
Posted in python | Leave a comment