I have two table user(id,email,username,password) and post(id,user_id,title,body),
i have has many relation in both model,
now when i add post, it shows user id in the add action,it works ok, but i want to see username instead of user_id in the post add action.
how to do it?
this is my post model:
class Post extends AppModel {
public $useTable = 'post';
public $displayField = 'title';
public $validate = array(
'title' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'body' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
);
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
this is my postcontroller add function:
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('The post has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The post could not be saved. Please, try again.'));
}
}
$users = $this->Post->User->find('list');
$this->set(compact('users'));
}
Try this one:
$users = $this->Post->User->find('list', array('fields' => array('User.username')));
try to update your query, specify your fields:
$users = $this->Post->User->find('list',
array("fields" =>array(
"User.id",
"User.email"
)
)
);
Related
I have been trying to get cakephp 2.6.3 auth component for my site to work for a week now.
The problem am facing is that when ever I enter any bogus user ID/password combination, the login function returns true. i have read all is there to read and watched tutorials but I can't seem to get this to work.
I am new to using Cake, your help will be greatly appreciated. Thanks in advance.
Below is my appController.
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'Authenticate' => array(
'Form' => array(
'fields' => array('username' => 'student_id', 'password' => 'password')
)
)
)
);
public function isAuthorized($user){
return true;
}
public function beforeFilter(){
$this->Auth->allow('login');
}
}
UsersController:
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){
$this->redirect($this->Auth->redirectUrl());
}
else{
$this->Session->setFlash('Invalid User ID or password');
}
}
}
User's model:
class User extends AppModel{
public $name = 'User';
public $validate = array(
'student_id' => array(
'Please enter your User ID' => array(
'rule' => 'notEmpty',
'message' => 'Please enter your User ID.'
)
),
'first_name' => array(
'Enter First Name' => array(
'rule' => 'notEmpty',
'Message' => 'Please enter first name.')),
'last_name' => array(
'Enter Last Name' => array(
'rule' => 'notEmpty',
'Message' => 'Please enter last name.')),
'email' => array(
'Valid email' => array(
'rule' => array ('email'),
'Message' => 'Please enter a valid email.')),
'password' => array(
'Not empty' => array(
'rule' => 'notEmpty',
'Message' => 'Please enter your password.'),
'Match passwords' => array(
'rule' => 'matchPasswords',
'Message' => 'Your passwords donot match')),
'password_confirmation' => array(
'Not empty' => array(
'rule' => 'notEmpty',
'Message' => 'Please confirm your password.'))
);
public function matchPasswords($data){
if($data['password'] == $this->data['User']['password_confirmation']){
return true;
}
$this->invalidate('password_confirmation', 'Your passwords do not match');
return false;
}
public function beforeSave($options = array()){
if(isset($this->data['User']['password'])){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
Good answer here :
Cake PHP 2.4.x. AuthComponent login() always return true;
Also read this :
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
Get rid of $this->Auth->allow('login'); from your beforeFilter() method.
I done a user system on a website.
In my UsersController.php I have this method:
public function login()
{
if($this->request->is('post')) {
if($this->Auth->login()) {
$this->Session->setFlash('Connexion établie', 'flash_success');
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash("Nom d'user ou mot de passe invalide, réessayer", 'flash_error');
$this->redirect(array('controller' => 'indexes', 'action' => 'index'));
}
}
}
It works very well, but I need to change it. In my database I have a field "validate" which is a boolean.
On login I want to log user if the field is true but I don't want to log him if the field is on false.
Thanks for help
You need the scope field. You can either add it on the beforeFilter method For example:
public function beforeFilter() {
$this->Auth->authenticate = array(
'YourAuthComponent' => array(
'fields' => array(
'username' => 'username',
'password' => 'password'
),
'userModel' => 'Users.User',
//This is what you need
'scope' => array(
'User.active' => 1,
'User.verified' => 1)
)
);
}
Or you can add the option to your components array at your AppController or UsersController.
class AppController extends Controller {
/**
* Components used from the application
*
* #var array
*/
public $components = array(
'Auth'=> array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email'),
'scope' => array(
'User.active' => 1,
'User.verified' => 1)
)
)
)
),
);
}
I have a problem with HABTM in Cakephp.
There is two models: User (musicians) and Genre.
And there is three tables: users, genres, genres_users (id (primary), genre_id, user_id).
Wrote in User:
<?php
public $hasAndBelongsToMany = array(
'Genre' => array(
'className' => 'Genre',
'joinTable' => 'genres_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'genre_id',
),
);
But as result i'm getting "Missing Database Table".
What am I doing wrong?
Thanks.
upd
User model
class User extends AppModel {
public $primaryKey = 'id';
public $hasOne = array(
'PerformerProfile' => array(
'className' => 'PerformerProfile',
'dependent' => false,
),
'OrganizerProfile' => array(
'className' => 'OrganizerProfile',
'dependent' => false,
),
);
public $hasAndBelongsToMany = array(
'Genre' => array(
'className' => 'Genre',
'joinTable' => 'genres_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'genre_id',
'unique' => 'keepExisting',
),
);
}
Genre model:
class Genre extends AppModel {
public $primaryKey = 'id';
}
Answer is simple.
Error was in AppModel
It was:
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct();
Must be:
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table ,$ds);
I'm trying to use the cakephp built in Auth for a user login. I've managed to validate a user registration (which is located on the same view as the login) but not get the login working.
All i get when trying to login is my 'Invalid username or password, try again' error. I've gone through the blog tutorial but I'm new to cake/php and have only worked on messy projects in 1.3 that sue their own crude authentication.
MarshallsController.php
class MarshalsController extends AppController {
public $helpers = array('Html', 'Form');
public $uses = array("Marshal", "User");
public $components = array("RequestHandler","Session", "Auth");
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('register', 'login');
}
public function index() {
$this->set('users', $this->User->find('all',
array(
'conditions'=>array(
'User.marshall_id'=>$Marshall['Marshall']['id']
)
)));
}
//Run when Marshal attempts to register for login page
public function register(){
if ($this->request->is('post')) {
$this->Marshal->create();
if ($this->Marshal->save($this->request->data)) {
//if new marshall has been saved fetch all their data
$marshal = $this->Marshal->find('first',
array(
'conditions'=>array(
"Marshal.email" => $this->data['Marshal']['email'],
)
)
);
if(!empty($marshal)){
//set marshal session data to track logged in users and their data
$this->Session->write("Marshal",$marshal);
}
$this->Session->setFlash(__('The Marshal has been saved'));
//redirect user to logged in page
$this->redirect(array('controller' => 'pages', 'action' => 'home'));
} else {
$this->Session->setFlash(__('The Marshal could not be saved. Please, try again.'));
echo $this->render('login');
exit();
}
}
else{
//if Marshal has not attempted to login redirect the back to the login/register page
echo $this->render('login');
exit();
}
}
public function login() {
//if user has atempted a login
if ($this->request->is('post')) {
if ($this->Auth->login()) {
//If login detials are correct get user data
$marshal = $this->Marshal->find('first',
array(
'conditions'=>array(
"Marshal.email" => $this->data['Marshal']['email'],
)
)
);
if(!empty($marshal)){
//set marshal session data to track logged in users and their data
$this->Session->write("Marshal",$marshal);
}
//redirect user to the logged in page
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
debug($this->Auth->request->data);
}
Marshal model
class Marshal extends AppModel {
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'marshal_id',
'conditions' => array('User.status' => '1'),
)
);
public $validate = array(
'first_name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A first name is required'
)
),
'last_name' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'A last name is required'
)
),
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
)
),
'email' => 'email'
);
}
login.ctp
<div class="row">
<?php echo $this->Session->flash('auth'); ?>
<div class="sixcol">
<?php
echo $this->Form->create('Marshal', array('action' => 'login'));
echo $this->Form->inputs(array(
'legend' => __('Login'),
'email',
'password'
));
echo $this->Form->end('Login');
?>
</div>
<div class="sixcol last">
<?php
echo $this->Form->create('Marshal', array('action' => 'register'));
echo $this->Form->inputs(array(
'legend' => __('register'),
'first_name',
'last_name',
'email',
'password'
));
echo $this->Form->end('Register');
?>
</div>
By default, CakePHP uses username and password fields but you have email instead of username. You need to specify it:
public $components = array(
'Auth' => array('authenticate' => array('Form' => array( 'userModel' => 'User',
'fields' => array(
'username' => 'email',
'password' => 'password'
)
)
),
'authorize' => array('Controller'),
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'loginRedirect' => array('controller' => 'home', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'You don\'t have access here.',
),
);
This is my working example, feel free to change it for your needs.
You also could check the Security hash method and compare with the password in the database :
Security::setHash('sha1');
(sha1 or md5)
to compare passwords :
Security::hash($password,"sha1", true);
function login() {
//if already logged-in, redirect
// if($this->Session->check('email')){
// $this->redirect(array('action' => ''));
// }
// if we get the post information, try to authenticate
if ($this->request->is('post')) {
$data = $this->request->data;
print_r($data); die;
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Your username or password was incorrect.'));
}
}
only else codition is true
I use Cakephp framework, and I have problem with my association.
How create belong to association in models in cake php.
When I use belongto and hasMany in my model.
Can I find sample model to view this example?
Simple belongsTo association:
<?php
class Profile extends AppModel {
var $name = 'Profile';
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
?>
Simple hasMany association:
<?php
class User extends AppModel {
var $name = 'User';
var $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id',
'conditions' => array('Comment.status' => '1'),
'order' => 'Comment.created DESC',
'limit' => '5',
'dependent'=> true
)
);
}
?>
More specific information about associations is in the CakePHP Book.
User has Many Photos
Photos belongs to User
In User Model :
var $hasMany = array(
'Photo' => array(
'className' => 'Photo',
'foreignKey' => 'user_id'
);
In Photo Model :
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'PhotoAlbum' => array(
'className' => 'PhotoAlbum',
'foreignKey' => 'photo_album_id',
'conditions' => '',
'fields' => '',
'order' => '',
))