SiteController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-08-30 18:10
  7. */
  8. namespace api\controllers;
  9. use Yii;
  10. use api\models\form\SignupForm;
  11. use common\models\User;
  12. use api\models\form\LoginForm;
  13. use yii\web\IdentityInterface;
  14. use yii\web\Response;
  15. class SiteController extends \yii\rest\ActiveController
  16. {
  17. public $modelClass = "common\models\Article";
  18. public function behaviors()
  19. {
  20. $behaviors = parent::behaviors();
  21. $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;//默认浏览器打开返回json
  22. return $behaviors;
  23. }
  24. public function actions()
  25. {
  26. return [];
  27. }
  28. public function verbs()
  29. {
  30. return [
  31. 'index' => ['GET', 'HEAD'],
  32. 'login' => ['POST'],
  33. 'register' => ['POST'],
  34. ];
  35. }
  36. public function actionIndex()
  37. {
  38. return [
  39. "feehi api service"
  40. ];
  41. }
  42. /**
  43. * 登录
  44. *
  45. * POST /login
  46. * {"username":"xxx", "password":"xxxxxx"}
  47. *
  48. * @return array
  49. */
  50. public function actionLogin()
  51. {
  52. $loginForm = new LoginForm();
  53. $loginForm->setAttributes( Yii::$app->getRequest()->post() );
  54. if ($user = $loginForm->login()) {
  55. if ($user instanceof IdentityInterface) {
  56. return [
  57. 'accessToken' => $user->access_token,
  58. 'expiredAt' => Yii::$app->params['user.apiTokenExpire'] + time()
  59. ];
  60. } else {
  61. return $user->errors;
  62. }
  63. } else {
  64. return $loginForm->errors;
  65. }
  66. }
  67. /**
  68. * 注册
  69. *
  70. * POST /register
  71. * {"username":"xxx", "password":"xxxxxxx", "email":"x@x.com"}
  72. *
  73. * @return array
  74. */
  75. public function actionRegister()
  76. {
  77. $signupForm = new SignupForm();
  78. $signupForm->setAttributes( Yii::$app->getRequest()->post() );
  79. if( ($user = $signupForm->signup()) instanceof User){
  80. return [
  81. "success" => true,
  82. "username" => $user->username,
  83. "email" => $user->email
  84. ];
  85. }else{
  86. return [
  87. "success" => false,
  88. "error" => $signupForm->getErrors()
  89. ];
  90. }
  91. }
  92. }