<?php
/**
 * 用户 Token 及 refreshToken
 * @作者 苏相锟 <admin@phpok.com>
 * @主页 https://www.phpok.com
 * @版本 5.x
 * @授权 GNU Lesser General Public License https://www.phpok.com/lgpl.html 
 * @时间 2022年1月7日
**/

/**
 * 安全限制，防止直接访问
**/
if(!defined("PHPOK_SET")){
	exit("<h1>Access Denied</h1>");
}

class token_control extends phpok_control
{
	public function __construct()
	{
		parent::control();
	}

	public function index_f()
	{
		$this->refresh_f();
	}

	/**
	 * 通过 refresh 获取新的 Token
	**/
	public function refresh_f()
	{
		$token_id = ($this->config['token'] && $this->config['token']['refresh_id']) ? $this->config['token']['refresh_id'] : 'refreshToken';
		$day = ($this->config['token'] && $this->config['token']['refresh_day']) ? $this->config['token']['refresh_day'] : 30;
		$token = $this->get($token_id,'html');
		if(!$token){
			$this->error(P_Lang('未指定 refreshToken 信息'));
		}
		$config = $this->model('config')->get_all();
		if(!$config || !$config['private_key'] || !$config['public_key']){
			$this->error(P_Lang('系统配置不全，请系统管理员到后台配置好公钥，密钥及API验证串'));
		}
		//对 token 数据进行解密
		$this->lib("token")->etype("public_key");
		$this->lib('token')->public_key($config['public_key']);
		$this->lib('token')->private_key($config['private_key']);
		$this->lib('token')->expiry($day*24*60*60);
		$data = $this->lib('token')->decode($token);
		if(!$data || !$data['id'] || !$data['time'] || !$data['chk']){
			$this->error(P_Lang('参数不完整'));
		}
		if(!$this->model('token')->check($data['id'],$data['time'],$data['chk'])){
			$this->error(P_Lang('refreshToken 验证不通过'));
		}
		$data = $this->model('token')->create($data['id']);
		$this->success($data);
	}

	public function demo_f()
	{
		$config = $this->model('config')->get_all();
		if(!$config || !$config['private_key'] || !$config['public_key']){
			$this->error(P_Lang('系统配置不全，请系统管理员到后台配置好公钥，密钥及API验证串'));
		}
		$this->lib("token")->etype("public_key");
		$this->lib('token')->public_key($config['public_key']);
		$this->lib('token')->private_key($config['private_key']);
		$this->lib('token')->expiry(24*60*60);
		$tmp = $this->lib('token')->encode($data);
		$this->lib("token")->etype("public_key");
		$list = $this->lib('token')->decode($tmp);
		$this->success('测试非对称加密');
	}
}
