BaseController.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. * 系统基类控制器文件
  4. *
  5. * 主要用于基础验证,初始化数据等
  6. * @author Andy<370791225@qq.com>
  7. * @date 2019-06-20 10:00:00
  8. */
  9. namespace app\controllers;
  10. use app\models\Admin;
  11. use Yii;
  12. use yii\web\Controller;
  13. class BaseController extends CController
  14. {
  15. // 无需登录验证白名单
  16. static $guestAcl = [
  17. 'login/index',
  18. 'login/captcha',
  19. 'login/password',
  20. 'api/login'
  21. ];
  22. public function beforeAction($action)
  23. {
  24. $presentRequestUrl = Yii::$app->request->getPathInfo();
  25. if (Yii::$app->user->isGuest) {// 用户未登录操作
  26. if (in_array($presentRequestUrl, self::$guestAcl)) {
  27. return true;
  28. }
  29. if(isset(Yii::$app->session['user'])){
  30. return true;
  31. }
  32. //判断token
  33. $token='';
  34. $getUserId=0;
  35. if(Yii::$app->request->get('sig')){
  36. $token=Yii::$app->request->get('sig');
  37. $getUserId=Yii::$app->request->get('user_id');
  38. }elseif(Yii::$app->request->post('sig')){
  39. $token=Yii::$app->request->post('sig');
  40. $getUserId=Yii::$app->request->post('user_id');
  41. }
  42. if($token && $getUserId){
  43. $user=Admin::find()->where('token=:token',[':token'=>$token])->asArray()->one();
  44. if(!$user){
  45. echo 'error';
  46. return false;
  47. }else{
  48. if($user['user_id']!=$getUserId){
  49. echo 'error';
  50. return false;
  51. }
  52. $data=[
  53. 'user_id' => $user['user_id'],
  54. 'username' => $user['user_name'],
  55. 'real_name' => $user['real_name'],
  56. 'role'=>$user['role'],
  57. ];
  58. Yii::$app->session['user'] = $data;
  59. return true;
  60. }
  61. }
  62. if (Yii::$app->request->isAjax) {
  63. echo 'error';
  64. return false;
  65. } else {
  66. return $this->redirect(['login/index'])->send();
  67. }
  68. } else {
  69. return true;
  70. }
  71. }
  72. //提示信息并跳转
  73. protected function alert($status,$msg){
  74. $url=Yii::$app->request->getReferrer();
  75. return $this->renderPartial('../error/error',['message'=>$msg,'status'=>$status,'gotoUrl'=>$url]);
  76. }
  77. /**
  78. * 初始化接收参数
  79. * @return array
  80. */
  81. protected static function getRequest()
  82. {
  83. $requestData = [];
  84. $request = Yii::$app->request;
  85. if ($request->isGet && $request->get()) {
  86. $requestData = $request->get();
  87. } elseif ($request->isPost && $request->post()) {
  88. $requestData = $request->post();
  89. } elseif (file_get_contents('php://input')) {
  90. $requestData = json_decode(file_get_contents('php://input'), true);
  91. }
  92. return $requestData;
  93. }
  94. }