Closed polinwei closed 6 years ago
Hi! Well, for starters, you pass parameters by the method of Get and try to get from POST
Url http://mysite.com/api/user/login?email=user@gmail.com&password=123
$model->email = $_POST['email']; $model->password = $_POST['password'];
My version:
public function bootstrap($app)
{
$app->getUrlManager()->addRules(
[
// Rules for RESTful
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'users/default',
],
'pluralize' => false,
],
'GET user/login' => 'users/default/login',
// @see http://www.yiiframework.com/doc-2.0/guide-rest-routing.html
//'PUT,PATCH user/<id>' => 'users/default/update',
//'DELETE user/<id>' => 'users/default/delete',
'GET,HEAD user/<id>' => 'users/default/view',
//'POST user' => 'users/default/create',
'GET,HEAD users' => 'users/default/index',
//'user/<id>' => 'users/default/options',
//'users' => 'users/default/options',
]
);
parent::bootstrap($app);
}
//...
/**
* @return LoginForm
*/
public function actionLogin()
{
$model = new LoginForm();
if($model->load(Yii::$app->request->get(), '') && $model->login()) {
$modelClass = $this->modelClass;
$user = $modelClass::findOne(Yii::$app->user->identity->getId());
$user->generateAuthKey();
if($user->save())
return 'auth_key: '. $user->auth_key;
}
$model->validate();
return $model;
}
//...
We check:
http://mysite.com/api/users/login?email=user@gmail.com&password=123
return new auth key: "t19TwQouZWLtNW232tqd-J3L7iHz6K6D"
See how the AngularJS and Yii2 bunch works: http://blog.neattutorials.com/angularjs-and-yii2-part-2-authentication/
It works now . I should to study more. thanks
I tried the rule also can work as below.
$app->getUrlManager()->addRules(
[
// Rules for RESTful
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'users/default'
],
'pluralize' => false,
'extraPatterns' => [
'GET login' => 'login',
],
],
// @see http://www.yiiframework.com/doc-2.0/guide-rest-routing.html
//'PUT,PATCH user/<id>' => 'users/default/update',
//'DELETE user/<id>' => 'users/default/delete',
'GET,HEAD user/<id>' => 'users/default/view',
//'POST user' => 'users/default/create',
'GET,HEAD users' => 'users/default/index',
//'user/<id>' => 'users/default/options',
//'users' => 'users/default/options',
]
);
If it works, then it can) http://www.yiiframework.com/doc-2.0/guide-rest-routing.html
Hi Sir:
I plan to write a user login service in RESTful . The procedure is after user login , then system generate a new auth_key and return to user. My code is below, but not work . Could you help me to point where is wrong? thanks!!
modules\users\controllers\api\DefaultController
http://mysite.com/api/user/login?email=user@gmail.com&password=123