CakePHP Validation Question with Plugin - php

In my CakePHP application, I have setup the PersistantValidation plugin to validate my forms on the model level thanks to a kind previous suggestion. The plugin essentially makes it so that you can use model validation on a partial without having it redirect to the underlying page (ie. the register.ctp view or the login.ctp view, for example).
The validation works great for the login form, but it's not working properly on the user registration form for some reason.
The controller looks like this:
function register() {
if(!empty($this->data)) {
$name = $this->data['User']['name'];
$email = $this->data['User']['email'];
$password = $this->Password->generatePassword();
$this->data['User']['password'] = $this->Auth->password($password);
$this->User->create();
if($this->User->save($this->data)) {
$this->Session->setFlash(__('Your account has been created!', true));
$this->redirect(array('controller' => 'users', 'action' => 'offers'));
} else {
$this->redirect($this->referer());
}
}
}
The PresistentValidation component is also properly setup and included, since it works just fine in the login() function in the same controller. When I run this code, nothing happens. There is no redirect away from the partial, which is good, but the errors don't show up. Also, the errors do show up going to the register.ctp view, which means it isn't a problem with the validations themselves.
Does anyone have any ideas?

function register() {
if(!empty($this->data)) {
$this->data['User']['password'] = $this->Auth->password($password);
if($this->User->save($this->data)) {
$this->Session->setFlash(__('Your account has been created!', true));
$this->redirect(array('controller' => 'users', 'action' => 'offers'));
} else {
$this->redirect($this->referer());
}
}
}

Related

Flash() method shows the message but not redirecting in CakePHP 2

In Controller
public function add(){
$this->loadModel('User'); //load model
if($this->request->is('post')){
$filename=$this->User->checkFileUpload($this->request->data);
$this->User->set($this->request->data); //set data to model
if ($this->User->validates()){
$datas = array(
'User' => array(
'name' => $this->request->data['User']['name'],
'email'=>$this->request->data['User']['email'],
'password'=>$this->request->data['User']['password'],
'image'=>$filename
)
);
$pathToUpload= WWW_ROOT . 'upload/';
move_uploaded_file($this->request->data['User']['image']['tmp_name'],$pathToUpload.$filename);
// prepare the model for adding a new entry
$this->User->create();
// save the data
if($this->User->save($datas)){
//$this->Session->setFlash('User Information has been saved!');
return $this->Flash('User Information has been saved!',array('action' => 'index'));
//return $this->redirect(array('action' => 'index'));
}
} else {
$errors = $this->User->validationErrors; //handle errors
}
}
//$this->layout = NULL;
$this->viewpPath='Users';
$this->render('add');
}
In above code, i used flash() method to direct a user to a new page after an operation. This method showing the message but not redirecting in given url.
Please help me. What am i doing wrong here for redirecting with help of flash() method?
flash() does not redirect, it renders. It is very similar to the render() function, it will continue the execution of the script, unlike the redirect() function.
but if you still want to use this
you should use following in config file.
Configure::write('debug', 0);
Update
after add this into main.php use like
$this->flash(__("Some message for the user here..."), array("action" => "index"));
it'll work perfactly . Follow this forrefrence
Render != Redirect
If you need to redirect to the referer page you can use:
$this->redirect($this->referer());
if you want redirect to different controller:
$this->redirect(('controller' => 'YOURCONTROLLER', 'action' => 'YOURACTION'));
or if you want redirect to different action in same controller:
$this->redirect(('action' => 'YOURACTION'));

cakephp limit access to login screen when logged in

I don't want my users to be able to go to the login page if they are logged in. They have to log out first to be able to login. It seems simple enough, am i not understanding something correctly
class UsersController extends AppController {
public function isAuthorized($user) {
if( $this->Auth->login() ){
return false;
} else {
return true;
}
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
There are also actions like register or lost password etc.
Basically you just check on blacklisted controller/actions and redirect to your home screen or login redirect accordingly
// Do not allow access to these public actions when already logged in
$allowed = array('Account' => array('login', 'lost_password', 'register'));
foreach ($allowed as $controller => $actions) {
if ($this->name === $controller && in_array($this->request->action, $actions)) {
$this->Common->flashMessage('The page you tried to access is not relevant if you are already logged in. Redirected to main page.', 'info');
return $this->redirect($this->Auth->loginRedirect);
}
}
See
https://github.com/dereuromark/cakefest/blob/master/Controller/AppController.php#L66
I use laravel, and in situations like that, my login route is filtered like this.
Route::get('login', array('before' => 'guest', "uses" => "SessionController#create"));
guest is the name of a filter, defined as return !Auth::check();
For CakePHP, I'd imagine it'd be pretty similar. Look for a way that you can filter your routes, based on if your current user is authenticated.

cakephp $this->User->save($this->data) error on edit function of a logged user

I am trying to create the "edit" profile page for a logged user in cakephp. This would be the function to add/edit information about the user.
I get an error during the $this->User->save($this->data) function and I don't understand what is the problem.
public function edit() {
$this->User->id = $this->Auth->User('id');
if ($this->request->is('post')) {
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The user has been saved'), 'flash_success');
// $this->redirect($this->Auth->redirect());
} else {
var_dump($this->invalidFields());
$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'flash_failure');
}
} else {
//autocompleto il form
$this->data = $this->User->read(null, $this->Auth->User('id'));
}
}
The view is:
<?php
echo $this->Form->create('User',array('action' => 'edit'));
echo $this->Form->input('name', array('label'=> 'Name'));
echo $this->Form->input('surname', array('label'=> 'Surname'));
echo $this->Form->input('id', array('type'=> 'hidden'));
echo $this->Form->end(__('Submit'));
?>
I see you use Auth component. If your Auth::authorize default value is overridden ensure that you give user proper rights to perform data writing (maybe he only allowed to read).
Another issue could be your $validate declaration in model, where you force user to enter field value (using 'required' = true) but actually this field is not even displayed on View. You could avoid this validation rule on data edit if 'on' => 'create' is defined inside.
Also I would recommend use CakePHP debug() instead of var_dump() for debugging purpose.

CakePHP 2.0 Account validation

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.

CakePHP passing id to edit form

I've noticed that their is many different ways to pass an ID to a form when editing a database entry. So for example for a edit user profile form I have the following code:
function edit($id = null)
{
$this->layout = 'page';
// this line isn't needed?
//$this->User->id = $id;
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your profile has been updated', 'flash', array('header' => 'Announcement', 'myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'view', $id));
}
}
}
Now the function expects an id passing in the url e.g. /users/edit/2 But let's say I wanted it to be something more user friendly like /profile/edit (rewrote by routing) I would no longer be passing in the ID as part of the url. As you can see in my code I have a line I have commented out because it isn't needed?
Also in the form I ALSO Need <?php echo $this->Form->input('id', array('type' => 'hidden')); ?> why?
Basically this is more of what are the options available to me to build various types of edit forms and passing data to the form. And what is the need for the hidden field in the form if the data is being passed either via the URL or some other way
I've also noticed on some sites that they have things like Form Keys and the username stored in meta tags in the page header???
EDIT:
public function beforeFilter()
{
$this->set('authUser', $this->Auth->user());
//
$user = $this->Auth->user();
if (!empty($user))
{
Configure::write('User', $user[$this->Auth->getModel()->alias]);
}
}
public function beforeRender()
{
$user = $this->Auth->user();
if (!empty($user))
{
$user = $user[$this->Auth->getModel()->alias];
}
$this->set(compact('user'));
}
// NEW VERSION
function settings()
{
$this->layout = 'page';
$this->set('title_for_layout', 'Edit Profile');
$this->User->id = $user['id'];
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your settings have been updated', 'flash', array('myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'settings'));
}
}
}
Also in the form I ALSO Need Form->input('id',
array('type' => 'hidden')); ?> why?
Having the id hidden in the form removes the need for your controller action to grab the $id from the uri (aka passed as parameter). When in the form, it will automatically be placed into your $data array.
what is the need for the hidden field
in the form if the data is being
passed either via the URL or some
other way
It's not needed in the form if it's available from the uri. You'd simply grab the $id and assign it to the User model (as the commented out code does).
let's say I wanted it to be something
more user friendly like /profile/edit
I assume that would be when the user is editing his own profile. In that case, your system should be able to retrieve the user's id via the session.

Categories