CakePhp:Users login functionality - cakephp

<div>//login.ctp
<?php echo $this->Form->create('Register'); ?>
<?php echo $this->Form->input('username'); ?>
<?php echo $this->Form->input('password'); ?>
<?php echo $this->Form->end('Login'); ?>
this is login page of my application.
If i give invalid details or valid details it logged in to home.please help hear..
public function login(){
if($this->Auth->loggedIn()){
$this->redirect(array('action' => 'home'));
}
if($this->request->is('post')){
if ($this->Auth->login($this->request->data)) {
$this->Session->write('Register',$this->request->data);
$this->redirect(array('controller' => 'Registers','action' => 'home'));
} else {
$this->Session->setFlash(__('Username or password is incorrect'));
}
}
}
this is RegistersController page..

change your form as below --
<?php echo $this->Form->create('Register'); ?>
<?php echo $this->Form->input('User.username'); ?>
<?php echo $this->Form->input('User.password'); ?>
<?php echo $this->Form->end('Login'); ?>
and check that in your AUTH component you have setted the model name to 'User' and fields mapped to Auth component settings -- and in your login function
$this->Session->write('Register',$this->request->data); this line is not needed any more.
go on below link for detail --
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

Related

Redirecting to a different controller view in Cakephp

I have to 2 models that are related ItQuery and ItQueryComment. When a user adds a ItQuery other users should be able to comment on it. What i am trying to achieve is when other users add comments on a query they should be redirect to the view of the query not the index page for the it_query_comments
here is my code for my comments add view
<?php echo $this->Form->create('ItQueryComment'); ?>
<fieldset>
<legend><?php echo __('Add It Query Comment'); ?></legend>
<?php
echo $this->Form->input('it_query_id');
echo $this->Form->input('comment');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
and here is my add function in the controller
public function add() {
if ($this->request->is('post')) {
$this->ItQueryComment->create();
if ($this->ItQueryComment->save($this->request->data)) {
$this->Session->setFlash(__('The it query comment has been saved'));
$this->redirect(array('controller' => 'it_queries','action' => 'view', $itQuery['ItQuery']['id']));
} else {
$this->Session->setFlash(__('The it query comment could not be saved. Please, try again.'));
}
}
$itQueries = $this->ItQueryComment->ItQuery->find('list');
$this->set(compact('itQueries'));
}
If anyone could show me how to do this, that would be awesome. Thanks in advance
try the following
$this->redirect(array(
'controller' => 'it_queries',
'action' => 'view',
$this->request->data['ItQuery']['id'])
);

how to match input field before save it in cakephp

when user enter the full url..i want to save only youtube id... pregmatch examine and extract video id and then it will be saved into database..the problem is how to make this pregmatch check and extract youtube id before save the full url
thanks for helping
// this is add() function in videos_controller
function add() {
if (!empty($this->data)) {
$this->Video->create();
if ($this->Video->save($this->data)) {
$this->Session->setFlash(__('The Video has been saved', true));
$this->redirect(array('action' => 'admin_index'));
} else {
$this->Session->setFlash(__('The Video could not be saved. Please, try again.', true));
}
}
$vcats = $this->Video->Vcat->find('list');
$this->set(compact('vcats'));
}
// this is add.ctp file
<div class="videos form">
<?php // echo $this->Form->create('Image');?>
<?php echo $form->create('Video'); ?>
<fieldset>
<legend><?php __('Add Video'); ?></legend>
<?php
echo $this->Form->input('vcat_id');
echo $this->Form->input('title');
$url= $this->Form->input('link');
echo $url
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true)); ?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Videos', true), array('action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Vcats', true), array('controller' => 'vcats', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Vcat', true), array('controller' => 'vcats', 'action' => 'add')); ?> </li>
</ul>
</div>
// we get the unique video id from the url by matching the pattern but where i put this code to match before save
preg_match("/v=([^&]+)/i", $url, $matches);
$id = $matches[1];
Here
function add() {
if (!empty($this->data)) {
$this->Video->create();
$url = $this->data['Video']['link'];
/*assuming you have a column `id` in your `videos` table
where you want to store the id,
replace this if you have different column for this*/
preg_match("/v=([^&]+)/i", $url, $matches);
$this->data['Video']['id'] = $matches[1];
//rest of the code
}
}
I guess a better place for it is in the Model's beforeSave or beforeValidate method:
class Video extends AppModel {
...
public function beforeSave() {
if (!empty($this->data[$this->alias]['link'])) {
if (preg_match("/v=([^&]+)/i", $this->data[$this->alias]['link'], $matches)) {
$this->data[$this->alias]['some_id_field'] = $matches[1];
}
}
return true;
}
...
}

Add a user in Cakephp authentication tutorial

There is a problem when I write add() function for UsersController.
public function add(){
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('The new user has been saved.');
$this->redirect(array('action' => 'test'));
}
}
$this->set('title_for_layout', 'Register');
}
This is add view ctp.
<?php
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Save User');
?>
There's always a internal error when I try to access to users/add. Anyone know how to deal with this problem? Thanks.
Have you tried testing for $this->data instead of $this->request->is('post')? It might not matter, but that's typically the way it is done.
Also, for saving, you should most likely (unless you are setting userid manually) do something like:
$this->User->create();
$this->User->save($this->data);
So your add function should look something like:
public function add(){
if ($this->data) {
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash('The new user has been saved.');
$this->redirect(array('action' => 'test'));
}
}
$this->set('title_for_layout', 'Register');
}
And you probably want your view to be something like:
<?php echo $form->create('User', array('action' => 'add')); ?>
<?php echo $form->input("username", array('label' => 'Username')) ?>
<?php echo $form->input("password",array("type"=>"password", 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>

print username when login

i use this controller to login and logout users, and i want to display welcome message and the login username with logout link the problem is when i try to login this message apear to me
Notice (8): Undefined variable: results [APP\views\users\login.ctp, line 4]
users_controller.php
<?php
# /controllers/users_controller.php
# please note that not all code is shown...
uses('sanitize');
class UsersController extends AppController {
var $name = 'Users';
// Include the Email Component so we can send some out :)
var $components = array('Email','Auth','Recaptcha');
var $helpers = array('Recaptcha');
// Allow users to access the following action when not logged in
function beforeFilter () {
$this->Auth->allow('register','activate','logout','login');
$this->Auth->autoRedirect = false;
}
function login() {
// Check for incoming login request.
if ($this->data) {
// Use the AuthComponent's login action
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
// Check to see if the User's account isn't active
if ($results['User']['active'] == 0) {
// Uh Oh!
$this->Session->setFlash('Your account has not been activated yet!');
$this->Auth->logout();
$this->data['User']['password'] = null;
//if not active user
}else {
$this->set('users', $results);
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
}
}
function logout() {
$this->redirect($this->Auth->logout());
}
users/login.ctp
<?php if ($this->Session->read('Auth.User')):?>
<?php
echo "Welcome".'<br />' ;
echo $results;
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User');?>
<fieldset>
<legend><?php echo ('Please enter your username and password'); ?></legend>
<?php
echo $form->input('username');
echo $form->input('password');
?>
</fieldset>
<?php echo $form->end(('Login'));?>
</div>
<?php endif; ?>
You have to pass the data from your controller to the view by using the set method: $this->set('results', $results);. See also http://book.cakephp.org/view/977/Controller-Methods#Interacting-with-Views-978
AppController.php
function beforeFilter(){
$this->set('username', $this->_usersUsername());
}
function _usersUsername(){
$users_username = NULL;
if($this->Auth->user()){
$users_username = $this->Auth->user('username');
}
return $users_username;
}
view.ctp
<?php if(isset($username)) :?>
hello <?php echo $username; ?>! Welcome back.
<?php endif; ?>

Avoiding redirect and perssisting the session

I am trying to finish this website in cake php that was previously in regular php, but as newbie in the cakephp world.. I have found some difficulties such as these.
1) .When I click on login, it transfers me to another page although i have specified no redirects in app controller except when there is a registration. The login is at the top and its viewable through out all the pages, but if i click login, it redirects me to the login page (which i do not want).
2.) After I login, it brings in the session with the user name saying welcome 'username' but then if I go to another page, it seems like it forgets the session and brings back the inputs for the login form at the top of the page.
Here is my code
app_controller
<?php
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript', 'Session');
var $components = array('Auth', 'Session');
function beforeFilter() {
$this->Auth->allow('add','get_categories','get_home', 'get_others', 'pages');
$this->Auth->autoRedirect = false;
}
}
?>
UsersController
<?php
class UsersController extends AppController {
var $uses = array("User");
var $components = array('Auth', 'Session');
function index()
{
$this->set('users', $this->User->find('all'));
$this->layout = 'master_layout';
}
function add() {
if (!empty($this->data)) {
//pass is hashed already
//->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your were registered!.');
$this->redirect(array('action' => 'get_home'));
}
}
$this->layout = 'master_layout';
}
//IF THE DATABASE IS SET UP CORRECTLY CAKE AUTHENTICATES AUTOMATICALLY NO
//LOGIC IS NEEDED FOR LOGIN http://book.cakephp.org/view/1250/Authentication
function login() {
$this->layout = 'master_layout';
if ($this->data) {
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$this->data['User']['password'] = '';
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
elements/loginform.ctp
<?php
if ($this->Session->read('Auth.User.username')):?>
<?php
echo "Welcome".' ' ;
echo $this->Session->read('Auth.User.username');
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>
UPDATE
I added the following to the app_controller
<?php
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript', 'Session');
var $components = array('Auth', 'Session');
function beforeFilter() {
//new addition
$this->set('userData', $this->Session->read());
$this->Auth->allow('add','get_categories','get_home', 'get_others', 'pages', '*');
$this->Auth->autoRedirect = false;
}
}
?>
WHEN I LOGIN I GET THIS ARRAY
Array ( [Config] => Array
( [userAgent] => 8f12200c2d48fa7955465842befe1c9e
[time] => 1323562284 [timeout] => 10 )
[Auth] => Array (
[User] => Array (
[id] => 63
[user_role] => 2 [
[user_fname] => test
[user_lname] => test
[user_email] => test#test.com
[user_phone] => 677-988-7777
[user_cellphone] => 555-456-9999
[user_address1] => 1st Avenue
[user_address2] =>
[user_city] => Citiland FL
[user_zip] => 55555
[username] => admin2 ) ) )
BUT WHEN I NAVIGATE TO A NEW PAGE
Array ( [Config] => Array (
[userAgent] => 8f12200c2d48fa7955465842befe1c9e
[time] => 1323562591 [timeout] => 10 ) )
ADDED PRINT_R TO elements/loginform TO SEE THE VARIABLE CONTENTS ACROSS ALL PAGES
<?php
print_r($userData);
if ($this->Session->read('Auth.User.username')):?>
<?php
echo "Welcome".' ' ;
echo $this->Session->read('Auth.User.username');
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>
1) This is because in your UsersController you have a redirect after the user is logged in.
Your login function should instead read:
function login() {
$this->layout = 'master_layout';
if ($this->data) {
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
/*This is the offending line, I've commented it out, but you could have it redirect somewhere else (it might be a good idea to redirect to the index action, for example, or just delete it:*/
//$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$this->data['User']['password'] = '';
}
As for 2), I believe it may be because you are not setting the data afterwards, so that while it exists in a tmp directory on the server (using the Session component) it is not actually being passed along to the view. So basically I think it's because you can't call Session methods in the view. Even if I'm not entirely correct about that, what I'm suggesting to do should work: Instead of calling session methods in the view, call them in the controller, set them in a variable for the view to access using $this->set();, then test against that variable in the view.
If you need to do this for ton of views and actions, you could consider adding something like this to your controller or even your app controller:
function beforeFilter() {
// Get session data for appllication use
$this->appuserstuff = $this->Session->read();
}
function beforeRender() {
// Make app variables available to view
$this->set('userData', $this->appuserstuff);
}
Alternatively, if you just need this in a couple actions, you could just set the user data in those actions with a:
$this->set('userData', $this->Session->read());
Now I'd recommend that you do a <?php debug($userData); ?> in one of your views so you can see how the data is structured in the array when it is set, so that you can user or test conditionals against. Finally, you could replace the direct calls to Session in your view with instead checks against the array of data:
Please note that I'm not sure how your specific array is structured so do a debug as recommended above and plug in your own keys for it to work:
<?php
if (!empty($userData['User'])):?>
<?php
echo "Welcome".' ' ;
echo $userData['User']['username'];
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>

Resources