I have login form which, where I am implementing 2 Factor Authentication integrating twilio API.
The API is working fine and I can get the verification response for success or failure.
Now I am somehow not able to display the message "OTP verification Failed" on the form.
here is my controller code:
public function actionLogin() {
$this->layout = '#app/themes/backend/login';
$model = new LoginForm(['scenario' => 'login']);
if (Yii::$app->request->isAjax && $model->load($_POST)) {
$authy_id = Yii::$app->session->get('authy_id');
// var_dump($authy_id);exit;
Yii::$app->response->format = 'json';
// var_dump($model);exit;
if(!empty($authy_id)){
$authy_api = new AuthyApi('api-key');
$token_entered_by_user = $model->otp;
$verification = $authy_api->verifyToken($authy_id, $token_entered_by_user);
if ($verification->ok()) {
// correct token
// Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}else{
// Yii::$app->response->format = 'json';
$model->addError('OTP Verification Failed');
print_r('error');
Yii::$app->session->setFlash('error', "OTP verification failed!");
exit;
}
}else{
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
}
if ($model->load(Yii::$app->request->post()) && $model->login()) {
if (Yii::$app->user->identity->user_role == 'admin') {
$path = "../" . Yii::$app->user->identity->user_role;
return $this->redirect($path);
}
elseif(Yii::$app->user->identity->user_role == 'customer') {
$path = "../" . Yii::$app->user->identity->user_role .'/default/index';
return $this->redirect($path);
}
else{
$path = "../" . "site/index";
return $this->redirect($path);
...
}
}
return $this->render('login', [
'model' => $model,
]);
}
and in my view file I have tried like:
<?php pjax::begin(['id'=>'otp-error']); ?>
<?php if(Yii::$app->session->hasFlash('error')):?>
<div class="info" id="otp-error">
<?= Yii::$app->session->getFlash('error') ?>
</div>
<?php endif?>
<?php pjax::end(); ?>
what I am missing here?
Remove the exit; after setting the "OTP verification failed!" message.
You are returning to nowhere just after you set that flash message.
Remember that for the flash message to work, your code must reach your view. If you return before, or return a JSON, it will never get to your client.
Related
I want to ask how to to check the data if we input data if there is the same data that cannot be inserted.
My code:
$obj = new Pengajuan();
// $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
$status = "Tersmpan";
} else {
$status = "Gagal";
}
echo json_encode(array("status" => $status));
Above of the code add a validation like below:
$this->validate([
'id_nasabah' =>'unique:pengajuans'
]) ;
And then rest of your controller code.
try this:
public function store(Request $request)
{
$this->validate($request,[
'id_nasabah'=>'required|exists:your_table_name,id',
'tgl_pengajuan'=>'more_validations',
'besar_pinjaman'=>'more_validations',
]);
//if $this->validate() fails, it will return a response 422 code error
//else it will continue with the creation of your object
//is a good idea to use a try-catch in case of something goes wrong
try
{
$pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));
return response->json([
'pengajuan'=>$pengajuan,
'status'=>'Tersmpan',
],200);//return a http code 200 ok
}
catch(Exception $e)
{
//'message'=>'this will return what is the error and line'
return response()->json([
'message'=>$e->getMessage().'/'.$e->getLine(),
'status'=>'Gagal',
],422);
}
}
I'm getting error when login to my project and then goto the base url. The below is the error which i get
My Login page [ see the url ]
After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error
I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
header("location: http://localhost/capacity_planner/login/login_check");
}
?>
admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
$email = ($this->session->userdata['logged']['email']);
}else{
header("location: http://localhost/capacity_planner/login");
}
?>
controller side
public function login_check(){
$data['base_url'] = base_url();
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run($this) == false) {
$this->index();
} else {
if(isset($this->session->userdata['logged'])) {
$data['login_bg'] = $this->input->post('login_bg');
$this->load->view("admin_db", $data);
}
}
function check_database($password){
$email= $this->input->post('email');
$user = $this->user->loginCheck($email, $password);
if($user[1] == 1){
$result = $this->user->user_details($email);
if($result != false) {
$session_data = array(
'id' => $result[0]->id,
'email' => $result[0]->cp_email,
);
$this->session->set_userdata('logged', $session_data);
return true;
}
} else{
$this->form_validation->set_message('check_database', $user[0]);
return false;
}
}
ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
if(isset($this->session->userdata['logged'])) {
//admin_db display function eg.redirect('admindashboard');
}
else{
//load your index view
this->load->view('your_index_view');
}
}
or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
redirect('index');
}
else{
$this->load->view('dashboard view');
}
}
This is my assumption.Kindly check it.
I am rendering contact us form in another view with the following code.
<?php echo $this->render('contact', [
'model' => $contactModel,
]); ?>
I also included
'enableAjaxValidation' => true,
to the form header.
My controller code is like the following.
$model = new ContactForm();
$data = "";
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
$data = "success";
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
$data = "Error";
}
}else{
$data = false;
}
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $data;
When I am trying to submit the form the validation works perfectly but when all the fields are entered correctly the page reloads with ajax request showing twice in firebug console. I want the page to stay on the form and fetch and display the success or error message from the controller.
I am new in yii2, Right now i am working with custom login, i did all code for login but when i go in home page through index action i didn't get any session there, Here is my code
public function actionIndex()
{
$session = Yii::$app->session;
if ($session->isActive) {
echo 'sdsd'; die;
}
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new User();
//if ($model->load(Yii::$app->request->post()) && $model->login()) {
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$userName = $_POST['User']['UserName'];
$password = $_POST['User']['Password'];
$condition = "UserName = '".$userName."' AND Password = '".md5($password)."' AND Status = '1' AND UserType = '1' ";
$loginData = User::find()->where($condition)->all();
if(count($loginData)>0) {
$username = $loginData[0]->UserName;
$userID = $loginData[0]->UserID;
$session = Yii::$app->session;
$session->set('userName',$username);
$session->set('userID',$userID);
$this->redirect('index');
} else {
Yii::$app->session->setFlash('error', 'Username or password is incorrect');
}
}
return $this->render('login', [
'model' => $model,
]);
}
Even after login it still consider me as guaest user, Yii::$app->user->isGuest what changes i need to do now ?
You don't login the user in Yii App
You don't need set the session you must assign the proper value to this function
return \Yii::$app->getUser()->login($yourUser, $yourRememberMe ? $this->module->rememberFor : 0);
see this doc for user and this for login
I am working on a project. I want to save 2 models in a same form. I've tried like this:
actionCreate in QController.php
public function actionCreate()
{
$model=new Question;
$test=new Answer;
if(isset($_POST['Question']) && ($_POST['Answer']))
{
$model->attributes=$_POST['Question'];
$model->question=CUploadedFile::getInstance($model,'question');
$test->attributes=$_POST['Answer'];
$valid=$model->validate();
$valid=$test->validate() && $valid;
if($valid){
$model->save(false);
$test->save(false);
$model->question->saveAs(Yii::app()->basePath . '/../images/questions/' . $model->question.'');
$this->redirect(array('view','id'=>$model->id_question));
}
}
$this->render('create',array(
'model'=>$model,
'test'=>$test,
));
}
Then, in my Q/_form.php
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'question-form',
'enableAjaxValidation'=>false,
)); ?>
<?php $answerModel = new Answer; ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model, $answerModel); ?>
<?php echo $form->fileFieldRow($model,'question',array('class'=>'span5','maxlength'=>50)); ?>
<?php echo $form->textFieldRow($answerModel,'optionA',array('class'=>'span5','maxlength'=>100)); ?>
//rest of codes
<?php $this->endWidget(); ?>
I've tried this but still not save the data. How can I do to fix it? Thanks for your answer
You should validate first and then save data:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
// use false parameter to disable validation
$model->save(false);
$test->save(false);
// redirect
}
And with transactions:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
$dbTransaction = Yii::app()->db->beginTransaction();
try {
// use false parameter to disable validation
$model->save(false);
$test->save(false);
$dbTransaction->commit();
// redirect here
} catch (Exception $e) {
$dbTransaction->rollBack();
// save/process error
}
}