Compare commits

..

No commits in common. "main" and "v1.0.2" have entirely different histories.
main ... v1.0.2

14 changed files with 1011 additions and 487 deletions

View File

@ -5,48 +5,35 @@
执行
```bash
composer config repositories.php-auth-client vcs git@git.int.haowumc.com:arch/php-auth-client.git
composer require arch/php-auth-client
```
### 代码中启用
### 配置步骤
* 注册中间件
1. 找侯小贝配置登录auth信息 ***AppId*** ***AppSecret*** ***guard***
2. 执行
```bash
composer config repositories.php-auth-client vcs git@git.int.haowumc.com:composer/php-auth-client.git
composer require paidian/auth-client
```
### 服务端代码使用
```php
$app->routeMiddleware([
'auth' => PdAuth\Middleware\Authenticate::class,
]);
```
1. 删除路由验证用户登录信息中间件,如无请忽略。
2. 删除代码中验证权限代码 `$this->middleware(CheckRole::class);` 如无请忽略。
3. 获取登录者信息由 `$this->user = app('request')->user('auth');` 变更为 `$this->user`
4. 给前端提供获取当前登录者信息接口, 如有请忽略
5. 在需要验证登录信息的控制器中配置如下代码ERP项目为例
```php
use \PdAuth\Controller;
public function __construct()
{
//这里配置的是ERP对应的guard
$guard = "erp";
$this->auth($guard);
}
```
####获取当前登录用户信息
```php
$this->user
```
#####上线需配置ENV 上线操作者配置
```env
RPC_AUTH_URI=http://auth.in.haowumc.com
AUTH_ERP_SECRET=123456
```
###前端代码使用
1. 获取登录者信息 未登录 http code 返回 401和登录地址 ___客户端需重新定义redirect地址___
2. 用户扫码返回 ***pd_code*** ***app_id***
3. 获取token地址 `api/auth/token.json` 请求方式:get 参数: ***pd_code*** ***app_id***
4. 获取退出登录地址 `/api/auth/logout` 请求方式:get 参数:无
* 注册服务
```php
$app->register(PdAuth\PdAuthServiceProvider::class);
```
### 配置
在项目 .env 文件中增加如下配置
```
PDAUTH_APP_ID=appid
PDAUTH_SECRET=123456
PDAUTH_HOST=http://auth.dev.haowumc.com
```

View File

@ -1,18 +1,18 @@
{
"name": "paidian/auth-client",
"name": "arch/php-auth-client",
"authors": [
{
"name": "候学杰",
"email": "houxuejie@hawumc.com"
"email": "houxuejie@xpai.tv"
}
],
"autoload": {
"psr-4": {
"PdAuth\\": "src/"
"PdAuth\\": "src/PdAuth"
}
},
"require": {
"illuminate/support": "^5.5",
"paidian/json-rpc": "~1.1"
"guzzlehttp/guzzle": "^6.3"
}
}

694
composer.lock generated Normal file
View File

@ -0,0 +1,694 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"content-hash": "ca4171a23bcb5fdd4cee12f9002972f7",
"packages": [
{
"name": "doctrine/inflector",
"version": "v1.2.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/inflector.git",
"reference": "e11d84c6e018beedd929cff5220969a3c6d1d462"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/doctrine/inflector/e11d84c6e018beedd929cff5220969a3c6d1d462.zip",
"reference": "e11d84c6e018beedd929cff5220969a3c6d1d462",
"shasum": ""
},
"require": {
"php": "^7.0"
},
"require-dev": {
"phpunit/phpunit": "^6.2"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.2.x-dev"
}
},
"autoload": {
"psr-4": {
"Doctrine\\Common\\Inflector\\": "lib/Doctrine/Common/Inflector"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
}
],
"description": "Common String Manipulations with regard to casing and singular/plural rules.",
"homepage": "http://www.doctrine-project.org",
"keywords": [
"inflection",
"pluralize",
"singularize",
"string"
],
"time": "2017-07-22T12:18:28+00:00"
},
{
"name": "guzzlehttp/guzzle",
"version": "6.3.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/guzzle/guzzle/f4db5a78a5ea468d4831de7f0bf9d9415e348699.zip",
"reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699",
"shasum": ""
},
"require": {
"guzzlehttp/promises": "^1.0",
"guzzlehttp/psr7": "^1.4",
"php": ">=5.5"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.0 || ^5.0",
"psr/log": "^1.0"
},
"suggest": {
"psr/log": "Required for using the Log middleware"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "6.2-dev"
}
},
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle is a PHP HTTP client library",
"homepage": "http://guzzlephp.org/",
"keywords": [
"client",
"curl",
"framework",
"http",
"http client",
"rest",
"web service"
],
"time": "2017-06-22T18:50:49+00:00"
},
{
"name": "guzzlehttp/promises",
"version": "v1.3.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/guzzle/promises/a59da6cf61d80060647ff4d3eb2c03a2bc694646.zip",
"reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646",
"shasum": ""
},
"require": {
"php": ">=5.5.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.4-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle promises library",
"keywords": [
"promise"
],
"time": "2016-12-20T10:07:11+00:00"
},
{
"name": "guzzlehttp/psr7",
"version": "1.4.2",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/guzzle/psr7/f5b8a8512e2b58b0071a7280e39f14f72e05d87c.zip",
"reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c",
"shasum": ""
},
"require": {
"php": ">=5.4.0",
"psr/http-message": "~1.0"
},
"provide": {
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.4-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Tobias Schultze",
"homepage": "https://github.com/Tobion"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"request",
"response",
"stream",
"uri",
"url"
],
"time": "2017-03-20T17:10:46+00:00"
},
{
"name": "illuminate/contracts",
"version": "v5.5.28",
"source": {
"type": "git",
"url": "https://github.com/illuminate/contracts.git",
"reference": "03e9014d2091a30b025c895aa6d39c2755576ea5"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/illuminate/contracts/03e9014d2091a30b025c895aa6d39c2755576ea5.zip",
"reference": "03e9014d2091a30b025c895aa6d39c2755576ea5",
"shasum": ""
},
"require": {
"php": ">=7.0",
"psr/container": "~1.0",
"psr/simple-cache": "~1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.5-dev"
}
},
"autoload": {
"psr-4": {
"Illuminate\\Contracts\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "The Illuminate Contracts package.",
"homepage": "https://laravel.com",
"time": "2017-11-22T19:01:14+00:00"
},
{
"name": "illuminate/support",
"version": "v5.5.28",
"source": {
"type": "git",
"url": "https://github.com/illuminate/support.git",
"reference": "4db3cc82b483172b1b25d9dfcec684927f5c8cf9"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/illuminate/support/4db3cc82b483172b1b25d9dfcec684927f5c8cf9.zip",
"reference": "4db3cc82b483172b1b25d9dfcec684927f5c8cf9",
"shasum": ""
},
"require": {
"doctrine/inflector": "~1.1",
"ext-mbstring": "*",
"illuminate/contracts": "5.5.*",
"nesbot/carbon": "^1.20",
"php": ">=7.0"
},
"replace": {
"tightenco/collect": "self.version"
},
"suggest": {
"illuminate/filesystem": "Required to use the composer class (5.2.*).",
"symfony/process": "Required to use the composer class (~3.3).",
"symfony/var-dumper": "Required to use the dd function (~3.3)."
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.5-dev"
}
},
"autoload": {
"psr-4": {
"Illuminate\\Support\\": ""
},
"files": [
"helpers.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "The Illuminate Support package.",
"homepage": "https://laravel.com",
"time": "2017-12-24T20:02:59+00:00"
},
{
"name": "nesbot/carbon",
"version": "1.22.1",
"source": {
"type": "git",
"url": "https://github.com/briannesbitt/Carbon.git",
"reference": "7cdf42c0b1cc763ab7e4c33c47a24e27c66bfccc"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/briannesbitt/Carbon/7cdf42c0b1cc763ab7e4c33c47a24e27c66bfccc.zip",
"reference": "7cdf42c0b1cc763ab7e4c33c47a24e27c66bfccc",
"shasum": ""
},
"require": {
"php": ">=5.3.0",
"symfony/translation": "~2.6 || ~3.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "~2",
"phpunit/phpunit": "~4.0 || ~5.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.23-dev"
}
},
"autoload": {
"psr-4": {
"Carbon\\": "src/Carbon/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Brian Nesbitt",
"email": "brian@nesbot.com",
"homepage": "http://nesbot.com"
}
],
"description": "A simple API extension for DateTime.",
"homepage": "http://carbon.nesbot.com",
"keywords": [
"date",
"datetime",
"time"
],
"time": "2017-01-16T07:55:07+00:00"
},
{
"name": "psr/container",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/container.git",
"reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/php-fig/container/b7ce3b176482dbbc1245ebf52b181af44c2cf55f.zip",
"reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Container\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common Container Interface (PHP FIG PSR-11)",
"homepage": "https://github.com/php-fig/container",
"keywords": [
"PSR-11",
"container",
"container-interface",
"container-interop",
"psr"
],
"time": "2017-02-14T16:28:37+00:00"
},
{
"name": "psr/http-message",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/php-fig/http-message/f6561bf28d520154e4b0ec72be95418abe6d9363.zip",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"time": "2016-08-06T14:39:51+00:00"
},
{
"name": "psr/simple-cache",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/simple-cache.git",
"reference": "753fa598e8f3b9966c886fe13f370baa45ef0e24"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/php-fig/simple-cache/753fa598e8f3b9966c886fe13f370baa45ef0e24.zip",
"reference": "753fa598e8f3b9966c886fe13f370baa45ef0e24",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\SimpleCache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interfaces for simple caching",
"keywords": [
"cache",
"caching",
"psr",
"psr-16",
"simple-cache"
],
"time": "2017-01-02T13:31:39+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.6.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "2ec8b39c38cb16674bbf3fea2b6ce5bf117e1296"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/symfony/polyfill-mbstring/2ec8b39c38cb16674bbf3fea2b6ce5bf117e1296.zip",
"reference": "2ec8b39c38cb16674bbf3fea2b6ce5bf117e1296",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.6-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"time": "2017-10-11T12:05:26+00:00"
},
{
"name": "symfony/translation",
"version": "v3.4.2",
"source": {
"type": "git",
"url": "https://github.com/symfony/translation.git",
"reference": "4c5d5582baf2829751a5207659329c1f52eedeb6"
},
"dist": {
"type": "zip",
"url": "https://files.phpcomposer.com/files/symfony/translation/4c5d5582baf2829751a5207659329c1f52eedeb6.zip",
"reference": "4c5d5582baf2829751a5207659329c1f52eedeb6",
"shasum": ""
},
"require": {
"php": "^5.5.9|>=7.0.8",
"symfony/polyfill-mbstring": "~1.0"
},
"conflict": {
"symfony/config": "<2.8",
"symfony/dependency-injection": "<3.4",
"symfony/yaml": "<3.4"
},
"require-dev": {
"psr/log": "~1.0",
"symfony/config": "~2.8|~3.0|~4.0",
"symfony/dependency-injection": "~3.4|~4.0",
"symfony/finder": "~2.8|~3.0|~4.0",
"symfony/intl": "^2.8.18|^3.2.5|~4.0",
"symfony/yaml": "~3.4|~4.0"
},
"suggest": {
"psr/log": "To use logging capability in translator",
"symfony/config": "",
"symfony/yaml": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.4-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Component\\Translation\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony Translation Component",
"homepage": "https://symfony.com",
"time": "2017-12-12T08:27:14+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": []
}

View File

@ -1,42 +0,0 @@
<?php
return [
'code' => [
'unauthorized' => 400401,
],
/**
* 支持的应用配置
*/
'apps' => [
'op' => [
'id' => '100006',
'secret' => env('AUTH_OP_SECRET','123456'),
],
'erp' => [
'id' => '100009',
'secret' => env('AUTH_ERP_SECRET','123456'),
],
'crm' => [
'id' => '100010',
'secret' => env('AUTH_CRM_SECRET','123456'),
],
'ds' => [
'id' => '100011',
'secret' => env('AUTH_DS_SECRET','123456'),
],
'payment' => [
'id' => '100007',
'secret' => env('AUTH_PAYMENT_SECRET','123456'),
],
'xiaoke' => [
'id' => '100005',
'secret' => env('AUTH_XIAOKE_SECRET','123456'),
],
'finance' => [
'id' => '100003',
'secret' => env('AUTH_FINANCE_SECRET','123456'),
],
],
];

View File

@ -1,201 +0,0 @@
<?php
namespace PdAuth;
use JsonRpc\Client;
use PdAuth\Middleware\Authenticate;
class Auth
{
protected $config;
protected $host;
protected $id;
protected $secret;
/**
* @var Client
*/
protected $rpc;
public function __construct($config)
{
$this->config = $config;
$this->configure();
}
/**
* @throws \Exception
*/
protected function configure()
{
switch (env('APP_ENV')) {
case 'local':
case 'develop':
$this->host = 'http://auth.dev.haowumc.com';
break;
case 'production':
$this->host = 'https://auth.int.haowumc.com';
break;
default:
throw new \Exception('"APP_ENV" is not defined or not allow');
}
//为了公司内部调用的统一,更换协议为 JSON RPC
if (function_exists('app')) {
$this->rpc = app('rpc.auth');
} else {
$this->rpc = new Client([
'client' => [
'auth' => [
'local' => true,
'base_uri' => env('RPC_AUTH_URI'),
],
],
]);
}
}
protected function matchConfigById($id)
{
foreach ($this->config['apps'] as $name => $app) {
if ($app['id'] == $id) {
return $name;
}
}
return null;
}
public function choose($name = null, $id = null)
{
if ($id) {
$name = $this->matchConfigByid($id);
$this->choose($name);
}
if (!$name) {
$name = env('APP_NAME');
}
switch ($name) {
case 'erp':
case 'erp-api':
$this->id = $this->config['apps']['erp']['id'];
$this->secret = $this->config['apps']['erp']['secret'];
break;
case 'ds':
case 'ds-api':
$this->id = $this->config['apps']['ds']['id'];
$this->secret = $this->config['apps']['ds']['secret'];
break;
case 'crm':
case 'crm-api':
$this->id = $this->config['apps']['crm']['id'];
$this->secret = $this->config['apps']['crm']['secret'];
break;
case 'op':
case 'op-api':
$this->id = $this->config['apps']['op']['id'];
$this->secret = $this->config['apps']['op']['secret'];
break;
case 'payment':
case 'paymeny_api':
$this->id = $this->config['apps']['payment']['id'];
$this->secret = $this->config['apps']['payment']['secret'];
break;
case 'xiaoke':
case 'xiaoke_api':
$this->id = $this->config['apps']['xiaoke']['id'];
$this->secret = $this->config['apps']['xiaoke']['secret'];
break;
case 'finance':
$this->id = $this->config['apps']['finance']['id'];
$this->secret = $this->config['apps']['finance']['secret'];
break;
}
return $this;
}
/**
* 生成web授权的链接
* @param $redirect
* @return string
*/
public function connect($redirect)
{
$id = $this->id;
$redirect = urlencode($redirect);
return "{$this->host}/connect?appid={$id}&redirect=$redirect";
}
/**
* @param $code
* @return array
* @throws \JsonRpc\Exception\RpcServerException
*/
public function getAccessToken($code)
{
$token = $this->rpc->call('oauth.access_token', [$this->id, $this->secret, $code]);
return $token;
}
/**
* 根据用户token获取用户信息
* @param $token
* @return array|null
* @throws \JsonRpc\Exception\RpcServerException
*/
public function getUserInfo($token)
{
$info = $this->rpc->call('oauth.user_info', [$this->id, $this->secret, $token]);
return $info;
}
/**
* 退出登录
* @param $token
* @return array
* @throws \JsonRpc\Exception\RpcServerException
*/
public function logout($token){
return $info = $this->rpc->call('oauth.logout', [$this->id, $this->secret, $token]);
}
/**
* 获取用户组
* @param null $token
* @return null
*/
public function getGroupUsers($token = null)
{
if ($token == null) {
$token = $_COOKIE[Authenticate::CookieName];
}
$token = urlencode($token);
$resp = $this->get("$this->host/api/group/users?access_token=$token");
if ($resp['code'] == 0) {
return $resp['data'];
}
return null;
}
/**
* @绑定好物平台用户
*
* @param int $user_id
* @param int $hwuser_id
* @return null
*/
public function bindHwUser(int $user_id, int $hwuser_id)
{
if ($user_id <= 0 || $hwuser_id <= 0) {
return null;
}
$resp = $this->post("$this->host/api/bind/hwuser", [
'id' => $user_id,
'hwmc_id' => $hwuser_id,
]);
return $resp;
}
}

View File

@ -1,25 +0,0 @@
<?php
namespace PdAuth;
use PdAuth\Middleware\Authenticate;
use PdAuth\Middleware\CheckRole;
trait Controller
{
protected $user;
protected $guard;
public function auth($guard)
{
$this->guard = $guard;
app('auth')->shouldUse($guard);
app('pd.auth')->choose($guard);
$this->middleware(Authenticate::class);
$this->middleware(CheckRole::class);
$this->user = app('request')->user($guard);
}
}

View File

@ -1,66 +0,0 @@
<?php
namespace PdAuth\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Support\Str;
class Authenticate
{
const CookieName = 'token';
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
//登录状态检测
if ($this->auth->guard($guard)->guest()) {
$redirect = $request->input('redirect');
if ($request->isXmlHttpRequest()) {
if( $redirect == null ){
$redirect = $request->header('referer');
}
return response()->json([
'code' => config('pdauth.code.unauthorized', 401),
'msg' => 'Unauthorized',
'data' => [
'url' => app('pd.auth')->connect($redirect),
],
],401);
} else {
if( $redirect == null ){
$redirect = $request->getSchemeAndHttpHost()."/api/auth/token.html";
}
return redirect(app('pd.auth')->connect($redirect));
}
}
return $next($request);
}
}

View File

@ -0,0 +1,116 @@
<?php
namespace PdAuth\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Support\Str;
class Authenticate
{
const CookieName = 'token';
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
//oauth 回调
$code = $request->input('pd_code');
if ($code) {
$token = app('pd.auth')->getAccessToken($code);
if (isset($token['access_token'])) {
setcookie(self::CookieName, $token['access_token'], strtotime($token['expired_at']), '/');
$qs = $request->getQueryString();
$params = explode('&', $qs);
$qs = '?';
foreach ($params as $k => $v) {
if (Str::startsWith($v, 'pd_code=')) {
continue;
}
$qs .= $v . '&';
}
if (!$request->isXmlHttpRequest()) {
abort(302, '', [
'Location' => $request->getSchemeAndHttpHost() . $request->getBaseUrl() . $request->getPathInfo() . $qs,
]);
}
}
}
//登录状态检测
if ($this->auth->guard($guard)->guest()) {
$redirect = $request->input('redirect', $request->getUri());
if ($request->isXmlHttpRequest()) {
return response()->json([
'code' => 401,
'msg' => 'need login',
'data' => [
'url' => app('pd.auth')->connect($redirect),
],
]);
} else {
return redirect(app('pd.auth')->connect($redirect));
}
}
//权限检测
// $path = $request->path();
// $privileges = config('pdauth.roles_privileges');
// $user = $request->user();
// $match = [];
// foreach ($user['roles'] as $role) {
// if (array_key_exists($role, $privileges)) {
// //如果设置了 * ,则跳过权限检测
// if (is_string($privileges[$role]) && $privileges[$role] == '*') {
// return $next($request);
// }
// if (!is_array($privileges[$role])) {
// throw new \Exception('pdauth 配置错误!');
// }
// $match = array_merge($match, $privileges[$role]);
// }
// }
// if (in_array($path, $match)) {
// return $next($request);
// }
// if ($request->isXmlHttpRequest()) {
// return response()->json([
// 'code' => 403,
// 'msg' => '无权访问,请联系管理员授权',
// 'data' => null,
// ]);
// }
// api_abort(403, '无权访问,请联系管理员授权');
return $next($request);
}
}

91
src/PdAuth/OAuth.php Normal file
View File

@ -0,0 +1,91 @@
<?php
namespace PdAuth;
use PdAuth\Middleware\Authenticate;
class OAuth
{
protected $host;
protected $id;
protected $secret;
public function __construct($config)
{
$this->host = $config['host'];
$this->id = $config['appid'];
$this->secret = $config['secret'];
}
/**
* 生成授权的链接
* @param $redirect
* @return string
*/
public function connect($redirect)
{
$redirect = urlencode($redirect);
return $this->host . "/connect?appid={$this->id}&redirect=$redirect";
}
public function getAccessToken($code)
{
$resp = $this->get("$this->host/api/access_token?id={$this->id}&secret={$this->secret}&code={$code}");
if ($resp['code'] == 0) {
return $resp['data'];
}
return null;
}
/**
* 根据用户token获取用户信息
* @param $token
* @return null
*/
public function getUserInfo($token)
{
$token = urlencode($token);
$resp = $this->get("$this->host/api/user/info?access_token=$token");
if ($resp['code'] == 0) {
return $resp['data'];
}
return null;
}
/**
* 获取用户组
* @param null $token
* @return null
*/
public function getGroupUsers($token = null)
{
if ($token == null) {
$token = $_COOKIE[Authenticate::CookieName];
}
$token = urlencode($token);
$resp = $this->get("$this->host/api/group/users?access_token=$token");
if ($resp['code'] == 0) {
return $resp['data'];
}
return null;
}
/**
* pd auth 系统发起请求
* @param $url
* @return mixed|null
*/
protected function get($url)
{
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', $url);
if ($res->getStatusCode() == 200) {
return \GuzzleHttp\json_decode($res->getBody(), true);
} else {
return null;
}
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace PdAuth;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use PdAuth\Middleware\Authenticate;
class PdAuthServiceProvider extends ServiceProvider
{
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('auth', function (Request $request) {
$token = $request->header('Authorization', $request->cookie(Authenticate::CookieName));
if ($token) {
try {
$user = app('pd.auth')->getUserInfo($token);
if ($user) {
return $user;
}
} catch (DecryptException $ex) {
return null;
}
}
return null;
});
//
$config = $this->app['config']['auth'];
if (!isset($config['guards']['auth'])) {
config(['auth.guards.auth' => ['driver' => 'auth']]);
$this->app['auth']->shouldUse('auth');
}
}
protected function setupConfig()
{
$source = realpath(__DIR__ . '/../config/pdauth.php');
if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
$this->publishes([$source => config_path('pdauth.php')], 'pdauth');
} elseif ($this->app instanceof LumenApplication) {
$this->app->configure('pdauth');
}
$this->mergeConfigFrom($source, 'pdauth');
}
public function register()
{
$this->setupConfig();
$this->app->singleton('pd.auth', function () {
return new OAuth(config('pdauth'));
});
}
}

View File

@ -1,101 +0,0 @@
<?php
namespace PdAuth;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use PdAuth\Middleware\Authenticate;
use Symfony\Component\HttpFoundation\Cookie;
class PdAuthServiceProvider extends ServiceProvider
{
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$config = $this->app['config']['auth'];
foreach ($this->app['config']['pdauth']['apps'] as $key => $app) {
$this->app['auth']->viaRequest($key, function (Request $request) use ($key) {
$token = $request->header('Authorization', $request->cookie(Authenticate::CookieName));
if ($token) {
return app('pd.auth')->choose($key)->getUserInfo($token);
}
return null;
});
if (!isset($config['guards'][$key])) {
config(['auth.guards.' . $key => ['driver' => $key]]);
}
}
$this->setupRouter();
}
protected function setupConfig()
{
$source = realpath(__DIR__ . '/../config/auth.php');
if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
$this->publishes([$source => config_path('pdauth.php')], 'pdauth');
} elseif ($this->app instanceof LumenApplication) {
$this->app->configure('pdauth');
}
$this->mergeConfigFrom($source, 'pdauth');
}
protected function setupRouter()
{
//添加获取token的路由
$this->app['router']->get('api/auth/token.json', function (Request $request) {
$code = $request->input('pd_code');
$id = $request->input('app_id');
$token = app('pd.auth')->choose(null, $id)->getAccessToken($code);
$cookie = new Cookie(Authenticate::CookieName, $token['access_token'], strtotime($token['expired_at']));
return response()->json([
'code' => 0,
'message' => '',
'data' => $token,
])->withCookie($cookie);
});
$this->app['router']->get('api/auth/token.html', function (Request $request) {
$code = $request->input('pd_code');
$id = $request->input('app_id');
$token = app('pd.auth')->choose(null, $id)->getAccessToken($code);
$cookie = new Cookie(Authenticate::CookieName, $token['access_token'], strtotime($token['expired_at']));
return RedirectResponse::create('/')->withCookie($cookie);
});
$this->app['router']->get('api/auth/logout', function (Request $request) {
$cookie = new Cookie(Authenticate::CookieName, '', time());
return response()->json([
'code' => 0,
'message' => '',
'data' => [
'url' => isDev() ? 'http://auth.dev.haowumc.com/logout' : 'https://auth.int.haowumc.com/logout'
],
])->withCookie($cookie);
});
}
public function register()
{
$this->setupConfig();
$this->app->singleton('pd.auth', function () {
return new Auth(config('pdauth'));
});
}
}

7
src/config/pdauth.php Normal file
View File

@ -0,0 +1,7 @@
<?php
return [
'appid' => env('PDAUTH_APP_ID', '100002'),
'secret' => env('PDAUTH_SECRET', '123456'),
'host' => env('PDAUTH_HOST', 'http://auth.dev.haowumc.com'),
];

View File

@ -1,8 +0,0 @@
<?php
require_once '../vendor/autoload.php';
use \PdAuth\Auth;
$auth = new Auth(require '../config/auth.php');
$auth->choose('erp');
exec('open '.$auth->connect('/'));