fitness-web/customerapi/controllers/UserController.php
2021-09-27 20:43:59 +02:00

105 lines
2.8 KiB
PHP

<?php
/**
* Created by IntelliJ IDEA.
* User: rocho
* Date: 2018.08.29.
* Time: 21:58
*/
namespace customerapi\controllers;
use common\models\Customer;
use customerapi\models\LoginForm;
use customerapi\models\PasswordChangeForm;
use sizeg\jwt\Jwt;
use sizeg\jwt\JwtHttpBearerAuth;
use Yii;
use yii\web\BadRequestHttpException;
/** @noinspection PhpUnused */
class UserController extends RestController
{
/**
* hash for password test is:
* $2y$13$D2BauYE2nhCdVDNatT9BMeWGxOvi5t5V6W2OUjr6sj2FRpb317Cpq
*
*/
/** @noinspection PhpUnused */
public function actionLogin()
{
// $customer = new Customer();
// $customer->setPassword("test");
$form = new LoginForm();
$form->load(\Yii::$app->request->post(), '');
if ($form->validate()) {
/** @var Jwt $jwt */
$jwt = Yii::$app->jwt;
$signer = $jwt->getSigner('HS256');
$key = $jwt->getKey();
$time = time();
// Adoption for lcobucci/jwt ^4.0 version
$token = $jwt->getBuilder()
->issuedBy('customerapi')// Configures the issuer (iss claim)
->permittedFor('customer')// Configures the audience (aud claim)
->identifiedBy('A989C57D19E2AF756BA9585AC4CFAF7974AE3D2BCA7CCA7307B39AB28CC7C2C8', true)// Configures the id (jti claim), replicating as a header item
->issuedAt($time)// Configures the time that the token was issue (iat claim)
->expiresAt($time + 3600)// Configures the expiration time of the token (exp claim)
->withClaim('uid', $form->getCustomer()->getId())// Configures a new claim, called "uid"
->getToken($signer, $key); // Retrieves the generated token
return $this->asJson([
'token' => (string)$token,
]);
} else {
return $this->asJson(
[
'errors' => $form->getErrors()
]
);
}
}
/**
* @throws \yii\base\InvalidConfigException
* @throws \yii\base\Exception
* @throws BadRequestHttpException
*/
public function actionPasswordChange()
{
$form = new PasswordChangeForm();
$form->scenario = "default";
$form->load(\Yii::$app->request->post(), '');
if (!$form->validate()) {
throw new BadRequestHttpException( $form->getErrorSummary(false)[0]);
}
$customer = Customer::findOne(\Yii::$app->user->id);
if (!$customer->validatePassword($form->passwordOld)) {
throw new BadRequestHttpException("Jelenlegi jelszó nem egyezik", "2");
}
$customer->setPassword($form->password);
$customer->save();
}
protected function getOptionalActions()
{
return ['login'];
}
}