| Current Path : /var/www/html/mygovuc/backend/controllers/ |
| Current File : /var/www/html/mygovuc/backend/controllers/AuthController.php |
<?php
namespace backend\controllers;
use common\models\LoginForm;
use Yii;
use yii\web\Controller;
use OneLogin\Saml2\Auth;
use yii\filters\VerbFilter;
use common\models\User;
class AuthController extends Controller {
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'google' => ['POST'],
],
],
];
}
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if ($action->id == 'google') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
public function actionGoogle() {
try {
/** disable csrf **/
$this->enableCsrfValidation = false;
/** checking response payload **/
$response = Yii::$app->request->post('SAMLResponse');
if(!$response) {
throw new \Exception('No payload found.');
}
/** saml **/
$auth = new Auth(Yii::$app->params['saml']);
$auth->processResponse();
$samlAttributes = $auth->getAttributes();
if(empty($samlAttributes)) {
throw new \Exception('No attribute found');
}
/** check if user exist **/
var_dump($samlAttributes);
// echo '<pre>' . $_POST['SAMLResponse'] . '</pre>';die;
list($email) = $samlAttributes['email'];
list($first) = $samlAttributes['firstname'];
list($last) = $samlAttributes['lastname'];
$user = $this->checkUserExist($email);
if(!$user) {
$user = $this->createUser($email, $first, $last);
$this->insertRole($user->id);
}
Yii::$app->user->login($user, 3600 * 24 * 1);
$this->goHome();
} catch(\Throwable $t) {
die($t->getMessage());
die('[Failed to signin, error occured]. Click here to go homepage <a href="/">Home.</a>');
}
}
private function checkUserExist($email): mixed {
$user = User::find()->where(['email' => $email])->one();
return $user ?? false;
}
private function createUser($email, $first, $last) : \common\models\User {
$user = new User();
$user->scenario = 'passwordlessLogin';
$user->username = $email;
$user->fullname = $first . $last;
$user->email = $email;
$user->status = 10; //active`
$user->auth_key = Yii::$app->security->generateRandomString();
$user->password_hash = 'null';
$user->last_login = time();
if(!$user->save()) {
throw new \Exception("Failed to save user" . "| error : " . json_encode($user->errors));
}
return $user;
}
/***
* Get User Role
*
**/
public function insertRole($user_id) {
$role = new \backend\modules\mimin\models\AuthAssignment();
$role->item_name = 'firsttime';
$role->user_id = $user_id;
$role->created_at = time();
if(!$role->save()) {
throw new \Exception("Failed to save user");
}
}
}