I am new to CakePHP, and follow the tutorial of CakePHP to try login function, however there is no error message appear after I use the wrong username/password. Please help.
public function login()
{
if ($this->request->is('post')) {
$user=$this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'bookmarks']);
}
$this->Flash->error('Your username or password is incorrect');
}
}
By using FlashComponent's magic method __call() an element is required to exist under src/Template/Element/Flash.
In your case you called error(), therefore it uses src/Template/Element/Flash/error.ctp. Make sure element exists.
Either that or you are not calling $this->Flash->render() in your view (where you want the error message to be shown).
Related
I'm new in laravel
I coded a script that many users may work with
but the problem that I have is this :
when a user like "Helen" signs in she can see her profile
but if next another user like "Maria" logs on , Marias panel will be shown for both of them
I think it means just one session can be active at the same time and the value of session will be for the latest user
and the older users session doesn't expire just the value in the session will be changed , thus she identifies as another user and can see that users profile, and also when a user logs out , because of close of the session , all users will be signed out.
here is my simple code :
public function Login(){
$this->Token();
$pack=Input::all();
try {
$result=DB::table('user')->where('Email','=',$pack['email'])->get();
if (Hash::check($pack['password'], $result[0]->Password)){
session(['there' => $result['0']->Email]);
return redirect('dashboard');
}
return redirect('dashboard')->with('does','wrong password');
}catch(Exception $e){
return redirect('dashboard')->with('does',.$e);
}
}
public function UserType() {
if(!session('there'))
return "Not Logged";
else {
$result = DB::table('user')->where('Email', '=', session('there'))->get();
if($result!=null)
return "User";
}
public function ShowDashboard(){
if($this->UserType()=="Not Logged")
else
return view('pages/dashboard');
}
I am not sure why you are session() to manage user logins... Also, they depend a lot on situations where users are login from the same computer, same browser... cookies... etc etc... and maybe that's why you might be getting 2 different session values at the same time...
In any case.. please try and prefer using Laravel's predefined functions of Auth to handle your login/logout procedures.
public function Login()
{
// What does this do? Check for a CSRF token? If yes, then
// please understand then Laravel automatically checks
// for the CSRF token on POST/PUT requests and therefore
// there is no special need to use the below function...
$this->Token();
$pack = request()->only(['email', 'password']);
// I don't really feel try catch is required here... but completely your choice...
try {
if(auth()->attempt($pack)) {
return redirect('dashboard')
}
return redirect->back()->with('does', 'wrong password');
} catch(Exception $e) {
return redirect->back()->with('does', $e);
}
}
public function ShowDashboard()
{
// You can remove this if/else by adding the 'auth' middleware
// to this route
if(!auth()->check())
return view('pages.dashboard');
else
return redirect(route('login'));
}
I found a lot of problems in your above code...
Please use camelCase for naming functions... (I haven't changed the naming in my code above because I don't really know what rules you are following at your workplace or idk...)
Please don't return strings for a simple true/false situation.
Please try and use Models whenever possible. The raw DB commands are required for very complex and extensive queries
Well I have set validationErrors for login in my UsersController:
public function login() {
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates() && $this->Auth->login()) {
$this->set('ui', $this->Auth->user('id'));
$this->Session->setFlash(__('Loged in!'), 'flash_success');
$this->redirect($this->Auth->redirect());
} else {
$errors = $this->User->validationErrors;
}
}
}
Now how can I use $error in my view or as an element to be listed above my form?
Plz help I have searched a lot, but the answers were for old CakePHP, and I am using CakePHP 2.3.8.
Validation errors are available in the view automatically
There is no action required to get validation errors in the view, as they are a property of the view class. They can be inspected simply with:
debug($this->validationErrors);
In the view.
But you probably don't need to access them
Note however that it's not normal to need to look at this property directly. Using the form helper errors are displayed automatically, or you can generate errors individually
if ($this->Form->isFieldError('email')) {
echo $this->Form->error('email');
}
So I'm trying to use a callback function with the Form_validation library in CodeIgniter (v2.1.4) to check whether a user with a given username or email exists in the database before creating a new user.
login.php (Controller)
function create_member()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|callback_value_check[USERNAME]');
if($this->form_validation->run() != FALSE)
{
// Validation passed; create the new user.
$this->load->model("members_model");
if($query = $this->members_model->create_member())
{
// Load the success page view.
}
else
{
// Reload the signup page view.
}
}
else
{
// Reload the signup page view.
}
}
function _value_check($value, $column)
{
$this->load->model("members_model");
if($this->members_model->check_exist_value($column, $value))
{
$this->form_validation->set_message('value_check', '%s is already taken.');
return FALSE;
}
else
{
return TRUE;
}
}
members_model.php (Model)
function check_exist_value($column, $value)
{
$this->db->where($column, $value);
$result = $this->db->get('MEMBERS');
if($result->num_rows() > 0)
{
// A user with that unique value already exists in the database.
return TRUE;
}
else
{
// There is no user with that unique value in the database.
return FALSE;
}
}
As seen in the code above, I'm only currently testing for an existing username. The standard validation messages appear correctly (i.e. required, min_length, etc). However, if I enter a value that I know to be already in the database (meaning the custom callback validation function should fail) I instead get an HTTP 500 error (Chrome's default 'Server error' page).
Does anyone have any insight as to why I'm getting an HTTP 500 error instead of seeing my custom error message?
I don't know why you are using you callback for the email/username unique check when codeigniter already provides this functionality in the form_validation class just add the unique rule check in the validation rules with the table name and column that has the emails/usernames also provide the table is column
$this->form_validation->set_rules('username', 'Username',
'trim|required|min_length[4]|unique[tablename.column_email_username,tablename.id]');
$this->form_validation->set_rules('username', 'Username',
'trim|required|min_length[4]|is_unique[tablename.column_email_username]');
Hope unique[tablename.column_email_username,tablename.id] does the job and you will not face the server error
OR try this for is_unique
Ahaha, turned out there was a type in the section reloading the view when the validation failed. Just needed to take a break and re-read through what I had to spot it!
I am having trouble trying to pass an valuable after the user fail the authorization. I would like to pass $error to the welcome controller but not sure how. Please help. Thank you.
private function _user_check()
{
//after form validation, I pass username and password to the model
$this->load->model('user_query');
$result=$this->user_query->query($this->input->post('username'),$this->
input->post('password'));
if($result)
{
redirect('main');
}else{
// I am not sure how to pass this error message to my welcome controller
$data['error']='Please check your username or password';
redirect('welcome');
}
}
In the redirect function, you aren't providing a full URL, so CI is going to treat the parameter as an URI segments to the controller.
Knowing this, you could have something like:
redirect('welcome/error/error_user_pass');
and have your "error_user_pass" that is being passed reference error constants defined in your CI project.
Maybe something like this in your application/config/constants.php file:
define('error_user_pass', 'incorrect user or password, please check yo self!');
Then in your 'welcome' controller having something like this:
class Welcome extends CI_Controller {
public function error(){
$errors = func_get_args();
foreach( $errors as $error ){
//echo error, or save it, or whatev
}
}
}
I'm trying to create an account register page with CakePHP 2.0 where user needs to activate it's new account by clicking on a link in the email he's received after insert username, email and password.
My question is how can I set an activation code inside the user record.
I thought to create a table field named activation_code and then to store an hashed version of the username to be sure the user can activate itself by clicking the email link with the activation key.
All the procedure is done but I don't know how can I set the activation_code inside the $data['User'] object and It's not clear for me if this is a good usage of the MVC framework or I should make it in a different way.
During the user registration action I've done this but I get an error when I try to create 'activation_code' dynamically:
// from the UserController class
public function register () {
if (!empty($this->data)) {
if ($this->data['User']['password'] == $this->data['User']['confirm_password']) {
// here is where I get the error
$this->data['User']['activation_key'] = AuthComponent::password($this->data['User']['email']);
$this->User->create();
if ($this->User->save($this->data)) {
// private method
$this->registrationEmail ($this->data['User']['email'], $this->data['User']['username']);
$this->redirect(array('controller'=>'users', 'action'=>'registration', 'success'));
}
}
}
}
Obviously the activation_key is an empty field inside my database.
So how can I create a filed dynamically from the controller?
$this->data['User']['activation_key']
should be:
$this->request->data['User']['activation_key']
(You should change all references to $this->data to the new cakephp2.0 $this->request->data)
I've solved the problem with the method Model::set(), so:
public function register () {
if (!empty($this->data)) {
if ($this->data['User']['password'] == $this->data['User']['confirm_password']) {
$this->User->create();
// I've used set method
$this->User->set('activation_key', AuthComponent::password($this->data['User']['email']));
if ($this->User->save($this->data)) {
$this->registrationEmail ($this->data['User']['email'], $this->data['User']['username']);
$this->redirect(array('controller'=>'users', 'action'=>'registration', 'success'));
}
}
}
}