Commit b556303d authored by shajiaiming's avatar shajiaiming

user auth

parent 9f0382bd
<?php
namespace api\base;
class BaseConstant
{
const ERROR = 'error';
const MSG = 'msg';
const MESSAGE = 'message';
const CODE = 'code';
const VAL = 'val';
const DATA = 'data';
const OK = 'ok';
const FINALTAG = 'finaltag';
}
...@@ -37,7 +37,7 @@ class BaseResponse extends Response ...@@ -37,7 +37,7 @@ class BaseResponse extends Response
$return = $data; $return = $data;
} }
if (YII_ENV_DEV) { if (YII_ENV_DEV) {
$return['time'] = \Yii::$app->controller->end - \Yii::$app->controller->start; #$return['time'] = \Yii::$app->controller->end - \Yii::$app->controller->start;
} }
\Yii::$app->response->data = $return; \Yii::$app->response->data = $return;
parent::send(); parent::send();
......
<?php
namespace api\base;
use yii\helpers\Html;
use yii\web\Response;
class ResponseMsg
{
public $is_support_jsonp = false;
public $header_list = [];
private static $default_header_list = [];
public function __construct()
{
// if ('cli' !== php_sapi_name()){
// $this->header_list = self::$default_header_list;
// $this->fzmCrossHeader();
// }
}
public function fzmCrossHeader()
{
$allow_list = \Yii::$app->params['allow_options_domain']['common'];
$origin = \Yii::$app->request->headers->get('Origin');
if (!in_array($origin, $allow_list)) {
$origin = implode(',', $allow_list);
}
$this->header('Access-Control-Allow-Origin', $origin);
$this->header('Access-Control-Allow-Methods', 'POST,GET,OPTIONS');
$this->header('Access-Control-Allow-Credentials', 'true');
$this->header('Access-Control-Allow-Headers', 'Authorization,FZM-REQUEST-OS,FZM-USER-IP,FZM-REQUEST-UUID,Content-Type,Content-Length');
}
public static function setDefaultHeader($default_header_list)
{
foreach ($default_header_list as $key => $header) {
self::$default_header_list[$key] = $header;
}
}
public static function getDefaultHeader()
{
return self::$default_header_list;
}
public function arrSuccess($data = BaseConstant::OK, $code = 200)
{
return [BaseConstant::ERROR => false, BaseConstant::MESSAGE => $data, BaseConstant::CODE => $code];
}
public function arrFail($data, $code = -1)
{
return [BaseConstant::ERROR => true, BaseConstant::MESSAGE => $data, BaseConstant::CODE => $code];
}
/**
* 失败返回接口
* @param string $msg
* @param int $code
* @return string
*/
public function jsonError($msg = '', $code = -1)
{
if (empty($msg)) {
$msg = 'unknown error';
}
$view = [
BaseConstant::CODE => $code,
BaseConstant::MESSAGE => $msg,
];
$json = json_encode($view);
return $this->dumpJsonData($json);
}
/**
* 成功返回接口
* @param string $msg
* @param int $code
* @return string
*/
public function jsonSuccess($data = '', $code = 200)
{
$view = [
BaseConstant::CODE => $code,
BaseConstant::MESSAGE => BaseConstant::OK,
BaseConstant::DATA => $data
];
$json = json_encode($view);
return $this->dumpJsonData($json);
}
/**
* 直接处理接口数据
* @param $ret
*/
public function dealRet($ret)
{
if (true === $ret[BaseConstant::ERROR]) {
$this->jsonError($ret[BaseConstant::MESSAGE] ? : 'unknown error');
} else {
$this->jsonSuccess($ret[BaseConstant::MESSAGE] ? : BaseConstant::OK);
}
}
/**
* 根据是否为JSONP做特殊处理输出
* @param $json
* @return string
*/
public function dumpJsonData($json)
{
$callback = '';
if (true === $this->is_support_jsonp) {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
$callback_key = 'jsonpcallback';
$callback = $_GET[$callback_key];
if ($callback) {
$callback = Html::encode($callback_key);
$json = $callback . '(' . $json . ')';
}
}
if (!$callback && !$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return $json;
}
/**
* @param $json_str
* @param string $callback_key
* @return string
*/
public function printByJson($json_str, $callback_key = '')
{
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . $json_str . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return $json_str;
}
}
/**
* @param $arr
* @param string $callback_key
* @return string
*/
public function printByArr($arr, $callback_key = '')
{
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
public function printOldFail($code, $code_msg, $detail_code, $detail_msg, $callback_key = '')
{
$this->fzmCrossHeader();
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
$arr = ['code' => $code, 'error' => $code_msg, 'ecode' => $detail_code, 'message' => $detail_msg, 'data' => []];
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
/**
* @param $success_data
* @param string $callback_key
* @return string
*/
public function printOldSuccess($success_data, $callback_key = '')
{
$this->fzmCrossHeader();
$callback = '';
if ($callback_key) {
$callback = $_GET[$callback_key] ?? '';
}
$arr = ['code' => 200, 'ecode' => 200, 'error' => 'OK', 'message' => 'OK', 'data' => $success_data];
if ($callback) {
$callback = Html::encode($callback_key);
if (!$this->isDebug()) {
$this->header('Content-type', 'application/javascript');
}
return $callback . '(' . json_encode($arr) . ')';
} else {
if (!$this->isDebug()) {
$this->header('Content-type', 'application/json');
}
return json_encode($arr);
}
}
/**
* 解决xdebug cookie设置不了的问题
*/
private function isDebug()
{
if (defined('SERVICE_ENV') && (SERVICE_ENV === 'test' || SERVICE_ENV === 'local') && isset($_GET['debug'])) {
return true;
}
return false;
}
public function header($key, $value)
{
$this->header_list[$key] = $value;
}
public function getHeaders()
{
return $this->header_list;
}
public function withHeaders($header_arr)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
foreach ($header_arr as $key => $val) {
\Yii::$app->response->headers->add($key, $val);
}
return $this;
}
public function withContent($content)
{
return $content;
}
}
...@@ -2,13 +2,50 @@ ...@@ -2,13 +2,50 @@
namespace api\controllers; namespace api\controllers;
use common\models\Admin;
use Yii; use Yii;
use common\models\Admin;
use common\models\LoginForm;
use api\base\BaseController; use api\base\BaseController;
class UserController extends BaseController class UserController extends BaseController
{ {
/** /**
* landing
* @return array
* @throws \yii\base\Exception
* @throws \yii\base\InvalidConfigException
*/
public function actionLogin()
{
$model = new LoginForm();
$model->setScenario(LoginForm::SCENARIOS_LOGIN);
$model->load(Yii::$app->request->post());
if ($model->login()) {
$response = [
'success' => true,
'msg' => 'Login Successful'
];
} else {
$error = implode(", ", \yii\helpers\ArrayHelper::getColumn($model->errors, 0, false)); // Model's Errors string
$response = [
'success' => false,
'msg' => $error
];
}
return $response;
/* if ($model->login()) {
var_dump([]);exit;
return [
'access_token' => $model->login(),
];
} else {
var_dump($model->getFirstErrors(),[]);exit;
return $model->getFirstErrors();
}*/
}
/**
* 用户同步 * 用户同步
*/ */
public function actionUserSync() public function actionUserSync()
......
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
namespace common\behaviors; namespace common\behaviors;
use api\base\ResponseMsg;
use common\components\Response;
use yii\base\ActionFilter; use yii\base\ActionFilter;
use Yii; use Yii;
...@@ -15,53 +17,23 @@ class LoginStatusAuthInterceptor extends ActionFilter ...@@ -15,53 +17,23 @@ class LoginStatusAuthInterceptor extends ActionFilter
{ {
public function beforeAction($action) public function beforeAction($action)
{ {
return true;
$auth_string = Yii::$app->request->headers->get('Authorization'); $auth_string = Yii::$app->request->headers->get('Authorization');
if (strstr($auth_string, 'Bearer')) { if (strstr($auth_string, 'Bearer')) {
return $this->frontAuth(); return true;
#return $this->frontAuth();
} }
if (!$auth_string) { if (!$auth_string) {
$message = 'cms auth error'; $message = 'cms auth error';
$code = '40004'; $code = '40004';
goto doEnd; goto doEnd;
} }
$auth_arr = explode('||', $auth_string);
$cookies = [];
foreach ($auth_arr as $auth_item) {
$auth_item_item = explode('=', $auth_item);
$cookies[$auth_item_item[0]] = urlencode($auth_item_item[1]);
}
$curl = new FpfHttpClient();
$url = Yii::$app->fpf->getConfig('cms_auth_user_id', 'api');
$get_data = [];
$options = [
'cookies' => $cookies
];
$result = $curl->get($url, $get_data, $options);
$result = json_decode($result, true);
if (isset($result['code']) && 200 == $result['code']) {
Yii::$app->request->setUserId($result['data']['zhaobi_uid']);
$base_service = new BaseService();
$items = $base_service->getBaseInfoByUserIds([$result['data']['zhaobi_uid']]);
$detail = $items[0];
$platform_code = $detail->plat;
$platform_id_mapping = Yii::$app->fpf->getConfig('platform_id_mapping', 'platform');
$platform_id = $platform_id_mapping[$platform_code] ?? '';
if (!$platform_id) {
$message = 'platform id get error';
$code = '40001';
goto doEnd;
}
Yii::$app->request->setPlatformId($platform_id);
return true;
} else {
$message = 'cms auth error';
$code = '40003';
}
doEnd : doEnd :
// 返回错误 // 返回错误
$response_message = new ResponseMsg(); $response_message = new ResponseMsg();
$content = $response_message->jsonError($message, $code); $content = $response_message->jsonError($message, $code);
$content = response()->withHeaders($response_message->getHeaders())->withContent($content); $content = $response_message->withHeaders($response_message->getHeaders())->withContent($content);
Yii::$app->response->data = $content; Yii::$app->response->data = $content;
Yii::$app->response->send(); Yii::$app->response->send();
return false; return false;
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
namespace common\behaviors; namespace common\behaviors;
use api\base\ResponseMsg;
use yii\base\ActionFilter; use yii\base\ActionFilter;
use Yii; use Yii;
...@@ -15,6 +16,7 @@ class UserAuthInterceptor extends ActionFilter ...@@ -15,6 +16,7 @@ class UserAuthInterceptor extends ActionFilter
{ {
public function beforeAction($action) public function beforeAction($action)
{ {
return true;
if (!parent::beforeAction($action)){ if (!parent::beforeAction($action)){
return false; return false;
} }
...@@ -22,25 +24,24 @@ class UserAuthInterceptor extends ActionFilter ...@@ -22,25 +24,24 @@ class UserAuthInterceptor extends ActionFilter
$request_class = get_class($action->controller); $request_class = get_class($action->controller);
$request_action = $action->id; $request_action = $action->id;
$headers = Yii::$app->request->headers; $user_id = 46;
$Authorization = $headers['Authorization'] ?? null; $platform_id = 17;
$user_id = Yii::$app->request->getUserId(); $user_auth = Yii::$app->params['user_auth']['user_auth'];
$platform_auth = Yii::$app->fpf->getConfig('plat_auth', 'platform_auth'); $user_auth_map = $user_auth[$platform_id] ?? null;
if(empty($user_auth_map)){
$platform_auth_map = $platform_auth[$platform_id] ?? null;
if(empty($platform_auth_map)){
$code = '40001'; $code = '40001';
$message = 'platform auth error'; $message = 'platform auth error';
goto doEnd; goto doEnd;
} }
$user_auth_map = $platform_auth_map[$user_id] ?? null; $user_auth_map = $user_auth_map[$user_id] ?? null;
if(empty($user_auth_map)){ if(empty($user_auth_map)){
$code = '40002'; $code = '40001';
$message = 'user auth error'; $message = 'user auth error';
goto doEnd; goto doEnd;
} }
$auth_type_map = Yii::$app->fpf->getConfig($user_auth_map, 'platform_auth'); $auth_type_map = Yii::$app->params['user_auth'][$user_auth_map];
#$auth_type_map = array_unique($auth_type_map);
#var_dump($auth_type_map);exit;
$switch = false; $switch = false;
foreach ($auth_type_map as $key => $auth_type){ foreach ($auth_type_map as $key => $auth_type){
if($request_class == $auth_type['class']){ if($request_class == $auth_type['class']){
...@@ -69,7 +70,7 @@ class UserAuthInterceptor extends ActionFilter ...@@ -69,7 +70,7 @@ class UserAuthInterceptor extends ActionFilter
// 返回错误 // 返回错误
$response_message = new ResponseMsg(); $response_message = new ResponseMsg();
$content = $response_message->jsonError($message, $code); $content = $response_message->jsonError($message, $code);
$content = response()->withHeaders($response_message->getHeaders())->withContent($content); $content = $response_message->withHeaders($response_message->getHeaders())->withContent($content);
Yii::$app->response->data = $content; Yii::$app->response->data = $content;
Yii::$app->response->send(); Yii::$app->response->send();
return false; return false;
......
...@@ -15,6 +15,8 @@ class LoginForm extends Model ...@@ -15,6 +15,8 @@ class LoginForm extends Model
private $_user; private $_user;
//定义场景
const SCENARIOS_LOGIN = 'login';
/** /**
* @inheritdoc * @inheritdoc
...@@ -31,6 +33,13 @@ class LoginForm extends Model ...@@ -31,6 +33,13 @@ class LoginForm extends Model
]; ];
} }
public function scenarios() {
$scenarios = [
self:: SCENARIOS_LOGIN => ['username', 'password'],
];
return array_merge( parent:: scenarios(), $scenarios);
}
/** /**
* Validates the password. * Validates the password.
* This method serves as the inline validation for password. * This method serves as the inline validation for password.
...@@ -55,6 +64,8 @@ class LoginForm extends Model ...@@ -55,6 +64,8 @@ class LoginForm extends Model
*/ */
public function login() public function login()
{ {
#echo 'aaaaa';exit;
#var_dump($this->validate());exit;
if ($this->validate()) { if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment