Cakephp with basic Auth Component - php

I try use cakephp with auth component and it's not work.
Somebody can help me, Thank a lot.
this my code:
Controller file here
Class UsersController extends AppController {
var $name = 'Users';
var $uses = array('User');
var $viewPath = 'my_view/user';
var $layout = 'default';
var $helpers = array('javascript');
function beforeFilter() {
parent::beforeFilter();
}
function login() {
$this->layout = 'login';
}
function logout() {
$this->layout = 'login';
$this->redirect($this->Auth->logout());
}
Model File:
Class User extends AppModel {
var $name = 'User';
var $useTable = 'users';
var $belongsTo = array();
var $validate = array(
'username' => array(
'rule' => 'notEmpty',
'message' => 'Username cannot empty'
)
);
}
AppController File:
var $components = array('Auth','Session');
function beforeFilter() {
Security::setHash("md5");
$this->Auth->fields = array('username' => 'username', 'password' => 'password');
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
//$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
$this->Auth->logoutRedirect = '/';
$this->Auth->loginError = 'Invalid e-mail / password combination. Please try again';
$this->Auth->authError = "This error shows up with the user tries to access a part of the website that is protected.";
}
In my view:
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
from my code, I need it to login to redirect to some page(example: dashboards/index).
And from this code must echo String from $this->Auth->loginError when login fail but it not show then I don't know to solve that. And in my db I store password by md5 too.
Code above I copy and try from Google
Thank again.

I don't know, but if you followed the "simple authentication and authorization" tutorial on the site, you'll have to modify your "routes.php" to also allow access to "display" to get to your /pages/ controller. I have no idea if this is what your problem is, but it kind of seems like it.

Well please put this statement $this->Auth->allow('login'); in your users controllers beforeFilter() callback after the parent::beforeFilter(); call this would allow you to use the login action either you are logged in or not

Related

CakePHP: How to use a non-default user model for authentication?

Hi i have a table name chat_users
I have connected users table for last few projects it working fine. But this is my first project i have a different table name chat_users
I want to login this table with username and password
I have tried but unable to login.
Please help me.
Code-
AppController.php
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array('Auth', 'Session', 'Email', 'Cookie', 'RequestHandler', 'Custom');
public $helpers = array('Html', 'Form', 'Cache', 'Session','Custom');
function beforeFilter() {
parent::beforeFilter();
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('ChatUser.is_active' => 1),
'fields' => array('ChatUser.username' => 'username', 'ChatUser.password' => 'password'),
)
);
}
}
?>
UsersController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $name = 'Users'; //Controller name
public $uses = array('ChatUser');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login');
}
public function index() {
}
public function login() {
$this->layout='login';
if ($this->request->is('post')) {
if (!$this->Auth->login()) {
$this->Session->setFlash(__('Invalid username or password, try again'), 'error_message');
$this->redirect($this->Auth->redirect());
}
}
if ($this->Session->read('Auth.ChatUser')) {
return $this->redirect(array('action' => 'index'));
exit;
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
Above query i am getting missing table.
See screenshot-
Your auth component configuration is incorrect. You are missing the appropriate userModel option, which defines the name of the model to use
And the fields configuration doesn't work the way your are using it, the keys must be named username and password, and the value can then contain the actual column name, however since your columns are obviously using the default names, there's no need to use this option at all.
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('ChatUser.is_active' => 1),
'userModel' => 'ChatUser'
)
);
Also the session key will always be Auth.User unless you are explicitly changing it via AuthComponent::$sessionKey:
$this->Auth->sessionKey = 'Auth.ChatUser';
However, you are better of using the auth component to access the user data anyways:
// Use anywhere
AuthComponent::user('id')
// From inside a controller
$this->Auth->user('id');
See also
Cookbook > Authentication > Configuring Authentication handlers
Cookbook > Authentication > Accessing the logged in user

validation is always true in cakephp

Im new to cakePHP and tried to create a simple user registration. Now I'm stuck since two days in the validation of the form. The validation function returns always true and so the form is always saved to the database, even if it is empty.
So here are the model, the controller and the view. Maybe you can see what I did wrong here?
/app/Model/MemberModel.php
<?php
class Member extends AppModel {
var $validate = array(
"username" => array(
"rule" => "alphaNumeric",
"allowEmpty" => false
)
);
}
?>
/app/Controller/MemberController.php
<?php
class MemberController extends AppController {
var $components = array("Security");
var $helpers = array("Html", "Form");
public function index() {
}
public function register() {
if($this->request->is("post")) {
Security::setHash("blowfish");
$this->Member->set($this->request->data);
debug($this->Member->validates());
if($this->Member->save(array("password" => Security::hash($this->request->data["Member"]["password"])))) {
$this->Session->setFlash(__("Saved."));
} else {
$this->Session->setFlash(__("Error: ").$this->validationErrors);
}
}
}
}
?>
/app/View/Member/register.ctp
<?php
echo $this->Form->create("Member");
echo $this->Form->input("username");
echo $this->Form->input("password");
echo $this->Form->end("Register");
?>
Oh, I just realized your problem.
/app/Model/MemberModel.php
should be
/app/Model/Member.php
The controller will look for Member.php, and if it can't find it, it will try the default $validate behavior in AppModel

Posting to a controller with ajax in CakePHP 2.0

When I post to this controller, I get this back as the response: Fatal error: Call to a member function find() on a non-object in /app/Controller/AppController.php on line 26 which probably has to do with using $this->data() explicitly. I was using CakePHP save without form
per a recommendation in there, but since I'm not using a form to send the data (thus not using $this->request->data()), I'd like to know what the replacement is for $this->data() so I can get this working.
My database table is is submissions_favorites.
This is my SubmissionFavorite model:
class SubmissionFavorite extends AppModel {
var $name = 'SubmissionFavorite';
var $belongsTo = array(
'User' => array(
'className' => 'User'
)
);
}
This is AjaxController (what I'm posting to):
class AjaxController extends AppController {
var $layout = 'ajax'; // uses an empty layout
var $autoRender = false; // renders nothing by default
var $uses = 'SubmissionFavorite';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->loginRedirect = array('controller' => 'home', 'action' => 'index');
$this->Auth->allow('addFavorite');
$this->Auth->flashElement = 'flash_error';
}
public function addFavorite() {
$this->autoRender = false;
$this->data['SubmissionFavorite']['user_id'] = $this->Session->read('Auth.User.id');
$this->data['SubmissionFavorite']['submission_id'] = $_POST['id'];
$this->data['SubmissionFavorite']['when'] = DboSource::expression('NOW()');
$message = array('success' => 'success');
$toReturn = json_encode($message);
if ($this->RequestHandler->isAjax()) {
if ($this->Session->read('Auth.User')) {
$this->SubmissionFavorite->save($this->data);
return $toReturn;
} else {
$login = array('login' => 'Please log in to add favorites');
return json_encode($login);
}
}
}
Line 26 in my AppController is:
protected function getSubmissionCount() {
$totalSubmissions = $this->Submission->find('count');
return $totalSubmissions;
}
Which is totally unrelated to anything else. I didn't even add anything to AppController when I wrote the new method within my AjaxController, so I'm not sure how it's relevant (or why I'm even getting an error in that file).
First, following cake conventions, you should name your model SubmissionsFavorite (note the s between Submission and Favorite). This is because your table name is composed by 2 words, even representing a relationship between 2 other tables.
Also, you can't do $this->Submission->... on AppController without telling cake whatever is "Submission". Take a look at this link to see how to initialize Submission model and use it on AppController: Can I use one model inside of a different model in CakePHP?
Regards.
Try to change all
var $name = 'SubmissionFavorite';
to:
public $name = 'SubmissionFavorite';
Also change: var $uses = 'SubmissionFavorite';
to: public $uses = array ('SubmissionFavorite');

Can I get the action in the before() method of a controller in Kohana 3?

My controller has...
class Controller_Staff extends Controller {
public function before() {
parent::before();
$id = $this->request->param('id');
$action = $this->request->param('action');
}
public function action_get($id) {
var_dump($id);
}
}
My route is...
Route::set('a', 'bla/<action>/<id>',
array('id' => '\d+', 'action' => '(get|set)'))
->defaults(array(
'controller' => 'staff',
'action' => 'set'
));
When I enter a URL (bla/get/42) which calls Controller_Staff->before() (before calling action_get()), I can access $id in before(), but $action is always NULL.
Is there a better way to access the current $action in the before() method?
Thanks.
Found it!
It ended up being very easy.
$action = $this->request->action;

Change admin layout in CakePHP

I am working in cakephp, and I have the following two lines in my /app/config/routes.php file:
/**
* ...and setup admin routing
*/
Router::connect('/admin/:controller/:action/*', array('action' => null, 'prefix' => 'admin', 'admin' => true, 'layout' => 'admin' ));
/**
* ...and set the admin default page
*/
Router::connect('/admin', array('controller' => 'profiles', 'action' => 'index', 'admin' => true, 'layout' => 'admin'));
I also have a layout at /app/views/layouts/admin.ctp
However, the layout is not changed when I visit admin URLs
Create a app/app_controller.php and put this in:
<?php
class AppController extends Controller {
function beforeFilter() {
if (isset($this->params['prefix']) && $this->params['prefix'] == 'admin') {
$this->layout = 'admin';
}
}
}
Don't forget to call parent::beforeFilter(); in your controllers if you use it in other controllers.
Semi related to the question, you don't need the routes defined, you just need to enable Routing.admin config option and set it to admin in the app/config/core.php. (CakePHP 1.2)
Add this code in beforeFilter() function in
app_controller.php
<?php
class AppController extends Controller {
function beforeFilter() {
if (isset($this->params['prefix']) && $this->params['prefix'] == 'admin') {
$this->layout = 'admin';
} else {
$this->layout = 'user';
}
}
}
?>
Set layout='admin' in
routes.php
<?php
Router::connect('/admin', array('controller' => 'users', 'action' => 'index','add', 'admin' => true,'prefix' => 'admin','layout' => 'admin'));
?>
For CakePHP 3.X you should edit your src/View/AppView.php file and add the following code to your initialize() method:
public function initialize()
{
if ($this->request->getParam('prefix') === 'admin') {
$this->layout = 'Plugin.layout';
}
}
the approaches above are good but if you are looking to change the layout for every page when logged in you might try the following using Auth Component
function beforeFilter() {
if ($this->Auth->user()) {
$this->layout = 'admin';
}
}
For cakephp 3.0 you can set a view variable by calling Auth->user in the beforeRender in AppController. This is my beforeRender:
public function beforeRender(Event $event)
{
///...other stuff
$userRole = $this->Auth->user();
$this->set('userRole', $userRole['role']);
}

Categories