My password and username are correct, but I can't login to admin. Is there anything wrong with my controller?
This is my model:
class login_model extends CI_Model{
function cek($username, $password){
$this->db->where("username", $username);
$this->db->where("password", $password);
return $this->db->get("user_admin");
}
function getLoginData($usr, $psw){
$u = $usr;
$p = md5($psw);
$q_cek_login = $this->db->get_where('user_admin', array('username' => $u, 'password' => $p));
if(count($q_cek_login->result()) > 0){
foreach($q_cek_login->result() as $qck){
foreach($q_cek_login->result() as $qad){
$sess_data['logged_in'] = TRUE;
$sess_data['id'] = $qad->id;
$sess_data['username'] = $qad->username;
$sess_data['password'] = $qad->password;
$sess_data['email'] = $qad->email;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
redirect('welcome_message');
}
}else{
$this->session->set_flashdata('result_login'. 'username dan password salah');
header('location: '. base_url(). 'login');
}
}
}
This is my controller:
class login extends CI_Controller {
function _construct(){
parent::_construct();
if($this->session->userdata('username')){
redirect(base_url('welcome_message'));
}
$this->load->model(array('login_model'));
}
function index(){
$this->load->view('login');
}
function proses(){
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if($this->form_validation->run() == FALSE){
$this->load->view('login');
}else{
$usr = $this->input->post('username');
$psw = $this->input->post('password');
$u = $usr;
$p = md5($psw);
$cek = $this->login_model->cek($u, $p);
if($cek->num_rows() > 0 ){
foreach($cek->result() as $qad){
$sess_data['id'] = $qad->id;
$sess_data['email'] = $qad->email;
$sess_data['username'] = $qad->username;
$sess_data['level']=$qad->level;
$this->session->set_userdata($sess_data);
}
$this->session->set_flashdata('success', 'login berhasil');
redirect(base_url('/'));
}else{
$this->session->set_flashdata('result_login', 'username dan password yang anda masukkan salah');
redirect(base_url('login'));
}
}
}
My view:
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="<?php echo base_url('login/proses'); ?>" method="post">
<?php if (validation_errors() || $this->session->flashdata('result_login')) { ?>
<div class="alert alert-danger animated fadeInDown" role="alert">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Peringatan!</strong>
<?php echo validation_errors(); ?>
<?php echo $this->session->flashdata('result_login'); ?>
</div>
<?php } ?>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Username" id="username" name="username">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
Register a new admin
</div>
When I try to log in, I always get this error:
I don't see anything strikingly wrong with your code.
Well you are obviously hitting your last nested else which means for some reason this statement $cek->num_rows() > 0 is evaluating to false.
I assume that you are entering a proper and existing username + password combination. But to troubleshoot you can after $p = md5($psw); do:
echo 'hashed password: ' . $p . '<br>username: ' . $u; exit;
and see if the username and hashed password match something in the database, if not, you have your answer. My best guess is that you perhaps didn't store a hashed password and only plain-text one.
As a side note you should move all of your redirects and flashdata out of your model. Models should only return or throw Exceptions.
Related
Controller
public function index()
{
//load session library
$this->load->library('session');
if($this->session->userdata('user')){
// redirect('home');
$this->load->view('heropage');
}
else{
$this->load->view('login_page');
}
}
public function login(){
$email = $_POST['email'];
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if($data)
{
$id=$data[0]->id;
$first_name=$data[0]->firstname;
$last_name=$data[0]->lastname;
$grade=$data[0]->grade;
$points=$data[0]->points;
$this->session->set_userdata('user_id',$id);
$this->session->set_userdata('lname',$last_name);
$this->session->set_userdata('user', $email);
$this->session->set_userdata('fname',$first_name);
$this->session->set_userdata('grade',$grade);
$this->session->set_userdata('pts',$points);
$this->getImg();
redirect('home');
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found'); }
}
View
<?php if(isset($_SESSION['success'])) :?>
<div class="alert alert-success"><?=$_SESSION['success'];?></div>
<?php endif; if(isset($_SESSION['error'])) :?>
<div class="alert alert-warning"><?=$_SESSION['error'];?></div>
<?php endif;?>
<!-- End alerts -->
<form action="<?php echo base_url();?>index.php/User/login" method="post" accept-charset="utf-8">
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" placeholder="Email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control"name="password" placeholder="Password">
<?php echo form_error('password'); ?>
</div>
<div class="form-group">
<button class="btn btn-sm btn-success" type="submit" align="center" name="login" class="submit">Log in</button>
</div>
</div>
</form>
model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email'=>$email));
if($query->num_rows() == 1 )
{
return $query->result();
}
}
Upon trying to log in, I got the error page cant be found. I want it to go to the home page if the session is correct. here is the error message:
404 Page Not Found
The page you requested was not found.
How can I solve the error because I have also set as needed in the routes
I think your form action should be <?php echo base_url(); ?>user/login
Also in your model you're not checking for password anywhere.
You're also not returning anything if the email is not found or more than 1 results are found -
($query->num_rows() == 1)
Model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email' => $email, 'password' => $password))->result(); // you should use row() here to return only 1 row.
return $query; // you should check the uniqueness of email on registration, not here -- not allow duplicate email on registration
}
Controller
public function login(){
$email = $_POST['email']; // $this->input->post('email');
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if( !empty($data) ) // if no result found it'll be empty
{
// your code
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found');
}
}
See, if this helps you.
In Magento 2, I have a custom login form in Header.
If a customer is on the product page for eg :
http://www.testwebsite.com/catalog/product/view/id/10
and login from header form then customer should redirect to the same product page instead of Customer Dashboard.
I have tried plugin code from this link.
Below is my custom header form code -
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath('/'); // Change this to what you want
return $result;
}
}
I want to redirect the customer to $currenturl. Link tutorial can be able to redirect to the home page. Please suggest what needs to be done to achieve to redirect the customer to the current page.
Try the below:
Header Login Form :-
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<input type="hidden" name='referer' value="<?php echo $currenturl ?>">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code : -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
protected $request;
public function __construct(
\Magento\Framework\App\RequestInterface $request
) {
$this->request = $request;
}
public function getPostReferer()
{
return $this->request->getPostValue('referer');
}
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath($this->getPostReferer());
return $result;
}
}
Please try with the following code I have set the current url to the instant of $resultRedirect like this : $resultRedirect->setUrl($currenturl);
<?php
namespace Vendor\Module\Controller\Account;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Catalog\Api\ProductRepositoryInterface;
class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {
public function execute() {
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$sku = '24-MB01'; //Edit as per your product sku
$_product = $this->productRepository->get($sku);
$currenturl = $_product->getProductUrl();
if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
/** #var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
$this->session->setCustomerDataAsLoggedIn($customer);
$this->session->regenerateId();
} catch (EmailNotConfirmedException $e) {
$value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
$message = __(
'This account is not confirmed.' .
' Click here to resend confirmation email.', $value
);
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (AuthenticationException $e) {
$message = __('Invalid login or password.');
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (\Exception $e) {
$this->messageManager->addError(__('Invalid login or password.'));
}
} else {
$this->messageManager->addError(__('A login and a password are required.'));
}
}
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
}
If you have a plugin that receives the Magento\Customer\Controller\Account\LoginPost object you could get the referer URL like : $subject->_redirect->getRefererUrl(). Then return this URL
$productURL = $subject->_url->getUrl($subject->_redirect->getRefererUrl());
return $subject->_redirect($productURL);
I'm not 100% sure if this URL will actually be the URL you want but worth a try.
Dear Expert need Help first see my view code in codeigniter :
<div class="form-group">
<label for="tglawal" class="col-sm-2 control-label">Periode</label>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglawal" id="tglawal">
</div>
</div>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglakhir" id="tglawal1">
</div>
</div>
</div>
and this my model code :
private function _get_datatables_query()
{
//add custom filter here
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal', $this->input->post('tglawal'));
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir', $this->input->post('tglakhir'));
}
}
public function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
and my controller if i get the important code is:
public function index()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->view('infokunjungan_view', $data);
}
else redirect(base_url());
}
public function ajax_list()
{
$list = $this->Infokunjungan->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $infokunjungan) {
$no++;
$row = array();
$row[] = "<td style='vertical-align:middle'><center>{$no}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglawal}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglakhir}<center></td>";
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Infokunjungan->count_all(),
"recordsFiltered" => $this->Infokunjungan->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
the problem is if searching between two date tglawal and tglakhir
im using between 2016-12-04 and 2016-12-04 output display will empty
but if using between 2016-12-04 and 2016-12-06 output success where is my problem or maybe im using where or i have to use like?
You need to use the >= and <= operator.
In your model try the below.
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal >=', $this->input->post('tglawal')); //assuming this is your begining (from) date
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir <=', $this->input->post('tglakhir')); //assuming this is your end(to) date
}
The above will search for the between dates including the dates selected.
Use the operator depending on the beginning and ending variable.
My code is to fetch questions of users saved in the database by a foreach loop and let the admin answer each question and save the answer of each question after checking of validation rules in the database , Here we go :
Model is :
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result();
}
My view is:
foreach ($questions as $id => $row) :
?>
<?php
echo "<h5>".$row->question;
echo "<br>";
echo "from : ".$row->user_name."</h5>";
echo date('Y-m-d H:i');
echo "<br>";
$q_no='save'.$row->id;
$ans_no='answer'.$row->id;
echo "<h4> Answer:</h4>";
echo form_open('control_panel');
?>
<textarea name='<?php echo 'answer'.$row->id; ?>' value="set_value('<?php echo 'answer'.$row->id; ?>')" class='form-control' rows='3'> </textarea>
<input type='hidden' name='<?php echo $q_no ; ?>' value='<?php echo $q_no; ?>' />
<input type='hidden' name='<?php echo $ans_no ; ?>' value='<?php echo $ans_no ; ?>' />
<?php
echo form_error($ans_no);
echo "
<div class='form-group'>
<div >
<label class='checkbox-inline'>
<input type='checkbox' name='add_faq' value='yes' />
Adding to FAQ page .
</label>
</div>
</div>
<p>";
?>
<input type='submit' name='<?php echo 'save'.$row->id; ?>' value='<?php echo 'save'.$row->id; ?>' class='btn btn-success btn-md'/>
<?php
echo 'answer'.$row->id;
?>
<hr>
<?php endforeach; ?>
and my controller is :
$this->load->model('control_panel');
$data['questions']=$this->control_panel->get_questions();
$data['no_of_questions']=count($data['questions']);
if($this->input->post($q_no))
{
$this->form_validation->set_rules($ans_no,'Answer','required|xss_clean');
if($this->form_validation->run())
{
/* code to insert answer in database */
}
}
of course it did not work with me :
i get errors :
Severity: Notice
Message: Undefined variable: q_no
i do not know how to fix it
I am using codeigniter as i said in the headline.
In your controller on your post() you have a variable called q_no you need to set variable that's why not picking it up.
I do not think name="" in input can have php code I think it has to be text only.
Also would be best to add for each in controller and the call it into view.
Please make sure on controller you do some thing like
$q_no = $this->input->post('q_no');
$ans_no = $this->input->post('ans_no');
Below is how I most likely would do lay out
For each Example On Controller
$this->load->model('control_panel');
$data['no_of_questions'] = $this->db->count_all('my_table');
$data['questions'] = array();
$results = $this->control_panel->get_questions();
foreach ($results as $result) {
$data['questions'][] = array(
'question_id' => $result['question_id'],
'q_no' => $result['q_no'],
'ans_no' => $result['ans_no']
);
}
//Then validation
$this->load->library('form_validation');
$this->form_validation->set_rules('q_no', '', 'required');
$this->form_validation->set_rules('ans_no', '', 'required');
if ($this->input->post('q_no')) { // Would Not Do It This Way
if ($this->form_validation->run() == TRUE) {
// Run Database Insert / Update
// Redirect or load same view
} else {
// Run False
$this->load->view('your view', $data);
}
}
Example On View
<?php foreach ($questions as $question) {?>
<input type="text" name="id" value="<?php echo $question['question_id'];?>"/>
<input type="text" name="q_no" value"<?php echo $question['q_no'];?>"/>
<input type="text"name="a_no" value="<?php echo $question['a_no'];?>"/>
<?php }?>
Model
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result_array();
}
I'm trying to get a login form to 'remember' the user logging in and I just can't work out how to do it.
Here's my controller
public function getLogin()
{
// Return the view with the data
return View::make('users.login');
}
public function postLogin()
{
// Gather Sanitized Input
$input = array(
'email' => Binput::get('email'),
'password' => Binput::get('password'),
'rememberMe' => Binput::get('rememberMe')
);
// Set Validation Rules
$rules = array (
'email' => 'required|min:4|max:64|email',
'password' => 'required|min:6'
);
//Run input validation
$v = Validator::make($input, $rules);
if ($v->fails())
{
// Validation has failed
return Redirect::to('users/login')->withErrors($v)->withInput();
}
else
{
try
{
//Check for suspension or banned status
$user = Sentry::getUserProvider()->findByLogin($input['email']);
$throttle = Sentry::getThrottleProvider()->findByUserId($user->id);
$throttle->check();
// Set login credentials
$credentials = array(
'email' => $input['email'],
'password' => $input['password']
);
// Try to authenticate the user
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Sentry::loginAndRemember($user);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
// Sometimes a user is found, however hashed credentials do
// not match. Therefore a user technically doesn't exist
// by those credentials. Check the error message returned
// for more information.
Session::flash('error', 'Invalid username or password.' );
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
echo 'User not activated.';
Session::flash('error', 'You have not yet activated this account.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
// The following is only required if throttle is enabled
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$time = $throttle->getSuspensionTime();
Session::flash('error', "Your account has been suspended for $time minutes.");
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
Session::flash('error', 'You have been banned.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
return Redirect::to('/');
}
}
/**
* Logout
*/
public function getLogout()
{
Session::flush();
Sentry::logout();
return Redirect::to('/');
}
And here's my View
#extends('layouts/master')
{{-- Web site Title --}}
#section('title')
#stop
{{-- Content --}}
#section('content')
<div class="tck-well span6 offset3">
<h1>Login</h1>
<form class="" action="{{ URL::to('users/login') }}" method="post">
{{ Form::token(); }}
<div class="control-group {{ ($errors->has('email')) ? 'error' : '' }}" for="email">
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input name="email" id="email" value="{{ Request::old('email') }}" type="text" class="input-xlarge" placeholder="E-mail">
{{ ($errors->has('email') ? $errors->first('email') : '') }}
</div>
</div>
<div class="control-group {{ $errors->has('password') ? 'error' : '' }}" for="password">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input name="password" value="" type="password" class="input-xlarge" placeholder="New Password">
{{ ($errors->has('password') ? $errors->first('password') : '') }}
</div>
</div>
<div class="control-group" for"rememberme">
<div class="controls">
<label class="checkbox inline">
<input type="checkbox" name="rememberMe" value="1"> Remember Me
</label>
</div>
</div>
<div class="form-actions">
<input class="button button-large button-secondary" type="submit" value="Log In">
Forgot Password?
</div>
</form>
</div>
#stop
Can someone help point me in the right direction please?
You could also use the helper method:
if( Input::get('rememberMe') ) {
$user = Sentry::authenticateAndRemember($credentials)
} else {
$user = Sentry::authenticate($credentials, false);
}
Similar to Devo's
// Try to log the user in
Sentry::authenticate(Input::only('email', 'password'), Input::get('remember-me', 0));
// For the view page
<input type="checkbox" name="remember-me" id="remember-me" value="1" /> Remember me;
Instead of,
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Use,
if(!empty($input['rememberMe'])) {
$user = Sentry::authenticate($credentials, true);
} else {
$user = Sentry::authenticate($credentials, false);
}
And make sure you are getting some value in $input['rememberMe'].
From GitHub it seems setting gc_maxlifetime in php.ini (or .htaccess) is sometimes necessary as well..
session.gc_maxlifetime = 2592000
In app/config/session.php add this lines:
'lifetime' => 999999,
'expire_on_close' => false,