我正在开发yii2 api并希望创建用户登录和用户注册/注册,但我不知道如何在API中创建登录和注册
我可以从用户获取值,但是当yii2与iOS应用程序一起使用时登录和注册将如何工作?
这是我的用户控制器代码,
namespace api\modules\v1\controllers;
use Yii;
use yii\data\ActiveDataProvider;
use yii\rest\ActiveController;
use api\modules\v1\models\User;
use yii\web\Response;
use yii\web\JsonResponseFormatter;
/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends ActiveController
{
public function behaviors(){
$behaviors = parent::behaviors();
$behaviors['bootstrap'] = [
'class' => \yii\filters\ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
return $behaviors;
}
public $modelClass = 'api\modules\v1\models\User';
public function actionUserapi()
{
Yii::$app->response->format = Response::FORMAT_JSON;
return new ActiveDataProvider([
'query' => User::find()->asArray()
]);
}
}
答案 0 :(得分:2)
<强>注册强>
/**
* Signs user up.
*
* @return mixed
*/
public function actionCreate()
{
$model = new SignupForm();
$params = Yii::$app->request->post();
$model->username = $params['username'];
$model->password=$params['password'];
$model->email=$params['email'];
if ($model->signup()) {
$response['isSuccess'] = 201;
$response['message'] = 'You are now a member!';
$response['user'] =\common\models\User::findByUsername($model->username);
return $response;
}
else {
//$model->validate();
$model->getErrors();
$response['hasErrors'] = $model->hasErrors();
$response['errors'] = $model->getErrors();
//return = $model;
return $response;
}
}
登录
/**
* User login.
*
* @return mixed
*/
public function actionLogin(){
$model = new LoginForm();
$params = Yii::$app->request->post();
$model->username = $params['username'];
$model->password = $params['password'];
if ($model->login()) {
$response['message'] = 'You are now logged in!';
$response['user'] = \common\models\User::findByUsername($model->username);
//return [$response,$model];
return $response;
}
else {
$model->validate();
$response['errors'] = $model->getErrors();
return $response;
}
}