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

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

Related

How to point to a different Controller of a Model in CakePHP

I have one Model class named 'Name' and one Controller class named 'Controller1'. I have created a form using 'Name' model which is by default pointing to 'names' controller as per default naming convention of cakephp. But i want it to point to 'Controller1' controller..
I've replace this code:-
<?php echo $this->Form->create('Name'); ?>
with this one to see if it works:-
<?php
echo $this->Form->create('Name',array('controller'=>'Controller1',
'action'=>'view'));
?>
But it is not working and is pointing to 'names' controller only.
How can i point it to 'Controller1' instead of 'names' controller?
More details:-
Model (Name.php):-
class Name extends AppModel{
public $useTable = "tbl_names";
}
Controller (Controller1Controller.php):-
class Controller1Controller extends AppController
{
public function index(){
}
public function view($id){
$name ='';
if($this->request->is('post')){
$name = $this->request->data('name');
if($name==="xyz"){
$this->redirect('http://www.google.com');
}else{
$this->Save($this->request->data);
$this->request->data['name']= 'Nice';
}
}
return $id;
}
// Save to database if entered name is other than 'xyz'
private function Save($data){
$this->Name->create();
}
public function viewname($id,$name){
}
}
You have to set url key to pass crontroller and action values.
echo $this->Form->create(false, array(
'url' => array('controller' => 'recipes', 'action' => 'add'),
'id' => 'RecipesAdd'
));
See FormHelper > Options for create()

Can not Logged In as an Admin In Laravel4

I have made an Admin Interface(A very simple Admin Interface).But if i want to login as an admin,i can not able to logged in as an admin though my username and password is absolutely right.
My Admin Controllers resides,
app/
controller/
Admin/
AdminController.php
And My views resides
app/
views/
admin/
Admin-login.blade.php
and i have created routes something like this
Route::get('admin',array(
'as' => 'admin',
'uses' =>'Admin\AdminController#AdminLogin'
));
Route::group(array('before' => 'auth'),function(){
//These Urls are Intended page after Admin Sign In
Route::get('marriage-admin/',array(
'as' => 'marriage-admin',
'uses' => 'MarriageController#MarriageAdmin'
));
Route::post('edit-marital-data',array('as' => 'edit-marital-data','uses' => 'MarriageController#EditMarritalStatus'));
Route::post('searched-marital-data',array('as' => 'searched-marital-data','uses' => 'MarriageController#SearchMarriage'));
}
Route::group(array('before' => 'guest'),function(){
/* CSRF Protect*/
Route::group(array('before' => 'csrf'),function(){
Route::post('admin-marriage',array(
'as' => 'admin-marriage',
'uses' => 'Admin\AdminController#AdminLoginPost'
));
}
}
and this is my Admin Controller
<?php
namespace Admin;
class AdminController extends \BaseController{
public function AdminLogin(){
return \View::make('admin.login');
}
public function AdminLoginPost(){
$auth=\Auth::attempt(array(
'username' => \Input::get('username'),
'password' => \Input::get('password')
));
if($auth){
return \Redirect::intended('marriage-admin');
}else{
return \Redirect::route('admin')->with('global','The username or password you provided is wrong!');
}
return Rediret::route('admin')->with('global','Please Review Your Admin Database.');
}
}
?>
and i have also created a Admin.php model since i have a different table namely admins in my database.
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Admin extends Eloquent implements UserInterface, RemindableInterface {
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
/*public static function blood_search($blood_group){
return static::where('blood_group','LIKE','%'.$blood_group.'%');
} */
protected $table = 'admins';
protected $fillable=array
( 'username',
'password'
);
use UserTrait, RemindableTrait;
}
in mention, page after login or you can say the dash bored of the Admin is taken from another controller namely MarriageController
Now if i try to logged in as an Admin.
i am getting the message
The username or password you provided is wrong!
which i have set in my Admin Controller, if auth is fail.
So why i am getting this message though the username and password i am providing is absolutely right ?
now my question is,am i missing some configuration for Admin??
Laravel doesn't use md5 encryption. While creating a user you need to Hash password using laravel Hash::make()
User::create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'))
));
If you want to manually insert it to database then
return Hash::make('yourpass');
then paste the returned result.

Codeigniter static variables in model

Once a user has logged in- I want all my models to know the user's id. (Even if they are called later on).
I thought about using a static variable but it doesn't seem to work
class Base_model extends CI_Model {
static protected $user_id;
}
class Log_in_model extends Base_model {
public function log_in(){
self::$user_id = 69;
}
}
class A_model extends Base_model {
public function do_A(){
echo self::$user_id;
}
}
class B_model extends Base_model {
public function do_B(){
echo self::$user_id;
}
}
initailize session
$this->load->library('session');
after user logs in,save the userdata in session userdata
$newdata = array(
'username' => 'USERNAME',
'email' => 'EMAIL',
'user_id' => 'USERID',
'logged_in' => TRUE
);
$this->session->set_userdata('userdetails',$newdata); //setting data in session with a name userdetails
get the session userdata..
print_r($this->session->userdata('userdetails')); //get userdetails from session
to destroy userdetails from session use..
$this->session->unset_userdata('userdetails');
if u want to read more about session then read this..
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html

Cakephp with basic Auth Component

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

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