I am using CakePHP 2.9 version. $this->Auth-login() function in Userscontroller doesnt get username. even though my database(user) have 'username' and 'password' field. It is redirecting to else statement.
UsersController:
public $components = array('Paginator','Auth','Session','Flash');
public function beforeFilter() {
$this->Auth->allow('login','logout');
}
public function login(){
if($this->request->is('post')){
$this->set('user1',$this->Auth->request);
if($this->Auth->login()){
return $this->redirect($this->Auth->redirect(['controller'=>'accessors','action'=>'index']));
}
else{
$this->Flash->set('Please check with username and password.');
} }}
login.ctp
echo $this->Form->create('User');
echo $this->Form->input('username',$options=array('div'=>array('class'=>'input text required'),'type'=>'text','autocomplete'=>'off'));
echo $this->Form->input('password',$options=array('div'=>'input password required'));
echo $this->Form->button('Submit', $options=array('type'=>'submit'));
echo $this->Form->button('Reset', $options=array('type'=>'reset')).'</br>';
Here is the screenshot of variables with assigned values captured through DebugKit
Can someone tell me where did i make mistake ?
Related
I am new to developing, and I want to do a simple validation in Codeigniter. I don't know where I am going wrong.
This is my form to be validated
And my controller is this
public function __construct()
{
parent::__construct();
$this->load->model('M_menu');
$this->load->model('master/M_user_type');
$this->load->helper(array('form'));
$this->load->library('form_validation');
}
public function index()
{
$data['menus']=$this->M_menu->getSideBarMenu_m();$data['error_message'] = '';
$this->load->view('master/V_user_type',$data);
}
function saveUserType_c()
{
$data['error_message'] = '';
$this->form_validation->set_rules('userType', 'UserTypeName', 'required');
echo var_dump($this->form_validation->run());
if (!$this->form_validation->run() )
{$data['menus']=$this->M_menu->getSideBarMenu_m();
$data['error_message'] .= validation_errors();
$this->load->view('master/V_user_type',$data);
}
else
{
$insert=$this->M_user_type->saveUserType_m();
if($insert){
$response=array("insert"=>true);
}else{
$response=array("insert"=>false);
}
echo json_encode($response);
}
}
With this I get the network error, and data is being saved to db. But no action in form(form not loading). Please guide me, where I go wrong. Also, if I need to give any more details
Please check your usertype view page, you can also load usertype view page before validation, so that you will be confirmed that usertype view page exist, I hope you understand my point.
You have to load a model before you call its methods. Use this:
$this->load->model('M_user_type');
$insert=$this->M_user_type->saveUserType_m();
I'm having trouble displaying the validation errors of a form using a custom validator.
The errors does exist as the debug method shows, it just won't be displayed in the form.
I'd like to be able to show the error message under (or above, or anywhere) the field.
What I've tried
Well, the documentation does state:
When using View\Helper\FormHelper::control(), errors are rendered by
default, so you don’t need to use isFieldError() or call error()
manually.
Nevertheless, I added the following in the form (just below the email control), which didn't do anything more. No message displayed.
if ($this->Form->isFieldError('email')) {
echo $this->Form->error('email', 'Yes, it fails!');
}
I've also found several questions and answers about this issue on SO, but they look outdated (from '09 to '13) and do not seem to correspond to today's CakePHP syntax.
What I've done
Users/forgot_password.ctp
<?= $this->Form->create() ?>
<?= $this->Form->control('email', ['type' => 'email']) ?>
<?= $this->Form->button(__('Reset my password')) ?>
<?= $this->Form->end() ?>
UsersController.php
(notice the specific validation set, as explained in documentation)
public function forgotPassword()
{
if ($this->request->is('post')) {
$user = $this->Users->newEntity($this->request->getData(), ['validate' => 'email']);
if ($user->errors()) {
debug($user->errors()); // <- shows the validation error
$this->Flash->error(__('An error occurred.'));
} else {
// ... procedure to reset password (which works fine!) and redirect to login...
return $this->redirect(['action' => 'login']);
}
}
}
UsersTable.php
public function validationEmail(Validator $validator)
{
$validator
->email('email')
->notEmpty('email', __('An email address is required.'));
return $validator;
}
What it looks like
Update
Thanks to #ndm comment, here is the correct way to display the error.
In UsersController.php:
public function forgotPassword()
{
// user context for the form
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity(§user, $this->request->getData(), ['validate' => 'email']); <- validation done on patchEntity
if ($user->errors()) {
$this->Flash->error(__('An error occurred.'));
} else {
// ... procedure to reset password and redirect to login...
return $this->redirect(['action' => 'login']);
}
}
// pass context to view
$this->set(compact('user'));
}
And in the view forgotPassword.ctp:
<?= $this->Form->create($user) ?>
//modify your function as below
public function forgotPassword()
{
if ($this->request->is('post')) {
$user = $this->Users->newEntity($this->request->getData(), ['validate' => 'email']);
if ($user->getErrors()) {
debug($user->getError('email')); // <- shows the validation error
$this->Flash->error(__($user->getError('email')['_empty']));
} else {
// ... procedure to reset password (which works fine!) and redirect to login...
return $this->redirect(['action' => 'login']);
}
}
}
I am having a form and in submission page. When I refresh the page it asks for resend data. To avoid that I found that I have to implement PRG pattern. Can anyone please help me to implement the same in CodeIgniter?
In order to pass data from the processing function back to the viewing function you will have to use sessions. The example assumes Codeigniter v3.0.0 or greater. If you are using some earlier version you will have to modify the setting, getting and resetting of the session data.
Here's a very simple controller
class TestPRG extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->library('session');
}
public function index()
{
$data['name'] = $this->session->name;
$data['pw'] = $this->session->pw;
$this->load->view('test_form_v', $data);
unset($_SESSION['name'], $_SESSION['pw']);
}
public function process_form()
{
$_SESSION['name'] = $this->input->post('username');
$_SESSION['pw'] = $this->input->post('password');
redirect('testprg', 'location', 303);
}
}
The view file
<?php
echo form_open('testprg/process_form');
echo form_input('username', isset($name) ? $name : NULL);
echo form_password('password', "");
echo form_submit('Submit', 'Submit');
echo form_close();
echo isset($pw) ? $pw : "";
This will echo the last entered password if it exists. It won't exist on a page refresh or go back from the browser.
Working with Laravel 5 I'm facing an issue to where it routes to auth/login by default. When you login, it redirects to login causing an error. When I'm able to actually use http://localhost/login it actually routes to home like it should. Anything new that would be causing it behave like this?
HomeController shown below:
<?php namespace app\Http\Controllers;
class HomeController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard to the user.
*
* #return Response
*/
public function index()
{
return view('home');
}
public function showLogin()
{
// show the form
return view('login');
}
public function doLogin()
{
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
echo 'SUCCESS!';
} else {
// validation not successful, send back to form
return Redirect::to('login');
}
}
}
public function doLogout()
{
Auth::logout(); // log the user out of our application
return Redirect::to('login'); // redirect the user to the login screen
}
}
I figured it out to be that constructor.
public function __construct()
{
$this->middleware('auth');
}
I removed that and changed the view to 'auth/login' and it works like a charm.
I'm trying to create a simply login page. I want validation on that page so that when a user clicks login the site checks that in the users database activated is set to 1, if not they can't login. I'm still very new to cakephp and am trying to pick up quickly so I'm sorry if this is a simple beginner question.
here is the validation in my User model
public $checkActive = array(
'activated'=>array(
'rule'=>array('equalTo', '0'),
'message'=>'The account must be activated, please check your email.'
));
here is the login function in my usersController
public function login() {
$this->set('title_for_layout', 'Individual Registration');
$this->set('stylesheet_used', 'style');
$this->set('image_used', 'eBOXLogo.jpg');
if ($this->request->is('post')){
if ($this->request->data['User']['password'] == 'qazwsx'){
if ($this->Auth->login()){
if (0 === $this->User->find('count',array('conditions'=>array('enabled'=>1,'login'=> $username)))) {
$this->Session->setFlash('Sorry, your account is not validated yet.');
}
$this->Auth->user('id');
$this->redirect($this->Auth->redirect('eboxs/home'));
}
}
else {
$this->Session->setFlash('Username or password is incorrect');
}
}else{
$this->Session->setFlash('Welcome, please login');
}
}
here is my beforeLogin function in the usersController
public function beforeLogin(){
if(isset($this->data['User']['password'])){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
app controller
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'users', 'action'=>'login'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"You can't access this page",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user){
return true;
}
public function beforeFilter(){
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user',$this->Auth->user());
}
I realize that there is no call in my controller to the validation but with my other validation such as username is unique, I haven't had to call it.
in short at the moment anyone can log into my page, I'm trying to make it so only those who have 1 in the activated field in the users table can login.
One option would be to check account validation right after login like this :
<?php
if ($this->request->is('post')){
if ($this->request->data['User']['password'] == 'qazwsx'){
if ($this->Auth->login()) {
// login ok, but check if activated
$username = $this->request->data['User']['username'];
if (0 === $this->User->find('count',array('conditions'=>array('activated'=>1,'username'=> $username)))) {
$this->Session->setFlash('Sorry, your account is not validated yet.');
$this->redirec($this->referer());
}
$this->Auth->user('id');
$this->redirect($this->Auth->redirect('eboxs/home'));
}
}
Add a scope option to your auth setup:
'Auth'=>array(
'loginRedirect'=>array('controller'=>'users', 'action'=>'login'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"You can't access this page",
'authorize'=>array('Controller'),
'scope' => array('User.activated' => 1)
)
This will prevent the user from logging in if they do not have User.activated = 1.
Also, look into your auth setup and re-read the manual page for CakePHP 2.0, you config looks like 1.3. There should be no need to check the password yourself, and you definitely don't need a beforeLogin method for such a simple setup.