cakephp auth component, use two models - cakephp

My site has a public section for employees and back end for admin. It uses 2 different models, Employee and Admin.
I want to use Auth component for employee login and admin login. I know how to setup Auth component to use a Model other than default User model. But can i have auth component use 2 models, one for Employee authentication and other for Admin authentication? I am using admin_ prefix routing.
Is this possible? I searched but all i could found was tutorials on howto make Auth component use models other than User model.
Please advise!
EDIT
I use separate login forms for admin login and employee login. Both use the employee controller, but separate actions.

http://api.cakephp.org/class/auth-component
check the property authenticate, your answer is there!
and more :
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html.
Look at authentication handlers!
Here is an example directly from cake page
<?php
// Basic setup
$this->Auth->authenticate = array('Form');
// Pass settings in
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Member'),
'Basic' => array('userModel' => 'Member')
);
Just put something else instead of Form and Basic and associate the good Model

Considering you are using two radio buttons for Employee and Admin. Then you can use the following code into the login method.
function login()
{
if ($this->request->is('post'))
{
$logged_in = false;
$login_type = $this->request->data['User']['login_type']
if ($login_type == 'Admin')
{
$this->Auth->authenticate = array('Form' => array('userModel' => 'Admin' ));
}
else //if ($login_type == 'Employee')
{
$this->Auth->authenticate = array('Form' => array('userModel' => 'Employee' ));
}
$this->Auth->constructAuthenticate();
if ($this->Auth->login())
{
$logged_in = true;
/*.... Do what you want............*/
}
}
}

Related

Cakephp Auth->loginredirect Problems

i have made a simple cakephp application . at the moment i am just working with auth component
to send user to their respective pages according to their. for ex if role =1 send to admin page and else if role = 2 send it to moderator page . i am using both session and auth component to see how they work and save data in them. below is the code for usercontroller login action
public function login(){
$this->Session->setFlash($this->Auth->user('role'));//checks for data in auth component if any
if($this->request->is('post') ){
$results = $this->User->findByEmail($this->request->data['User']['username']);
if($results &&$results['User']['password']== md5($this->request->data['User']['password']))
{
$this->Session->write('user',$results['User']);
$this->Auth->login($results['User']);
$this->Session->setFlash('User logged in successfully'.$this->Auth->user('role'));
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash('Login is incorrect');
}
}
}
The problem is the login works fine all the data is stored in session and auth variable but loginredirect behave weird. in my chrome browser . it always redirects to admin page no matter what the role is , but it is flashing correct message which i set in flash. the code of beforefilter in appcontroller
public function beforeFilter(){
$this->Auth->allow('display');
$this->Auth->loginAction = array('controller' => 'Users', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'Users', 'action' => 'login');
if($this->Auth->user('role') == '1'){
$this->Session->setFlash($this->Auth->user('role').'adminnnnnnnnnnnnnnnnnnnnn');
$this->Auth->loginRedirect = '/admins/index';
}
if($this->Auth->user('role') == '2'){
$this->Session->setFlash('moderatorrrrrrrrrrrrrrrrr');
$this->Auth->loginRedirect = '/users/index';
}
}
so the problem is the loop runs fine in before filter , the setflash display whether user is admin or moderator , but for some reason it redirects to only single page either admins/index page or users/index page no matter who logs in . This is behavior on chrome browser.
On firefox the loginredirects sends user to webroot/index page but again the flash messages are correct.
I am not sure what i am doing wrong is there a problem in my code or cakephp 2.0 auth component has measure bugs.
after user logs in it gets redirected via Auth->loginRedirect to dashboard() and here i check users role and use redirect to send particular user to the exact location
function dashboard() {
//get user's group (role)
//$role = $this->Session->read('user.role');
$role=$this->Auth->user('role');
//user selection logic here
if($role== '1'){
$this->redirect(array('controller' => 'users','action' => 'admin_index','admin' => false));
}
else if($role == '2'){
$this->redirect(array('controller' => 'users','action' => 'admin_index', 'admin' => false));
}
else if($role == '9'){
$this->redirect(array('controller' => 'users', 'action' => 'index', 'admin' => false));
$this->Session->setFlash('3');
}
}
This is just another way to work things out i included the dashboard function in my users controller and did auth login redirect to this function from appcontroller.
Hope it solves problem for others who are facing the issue. Thanks

Cakephp 2.x does not login manually

I am trying to integrate facebook authentication to my Cakephp 2.2.4 app and once the facebook authentication is done, I am trying to create the user and login the user manually, I see that though the below code is creating a auth session, i.e., $this->Auth->user() contains all the data , it is not logging the user into the app, i.e, I am not able to access other functions of the app
$user = $this->User->findById($user_id);
$this->Auth->login($user);
this is what I am using to manually login and the user saved does not contain a username and password
this is in my AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'Users','action'=>'dashboard'),
'logoutRedirect'=>array('controller'=>'Users','action'=>'login'),
'authError'=>'You can\'t access that page',
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
),'Basic'),
'authorize'=>array('controller')
),
'RequestHandler'
);
public $helpers = array('Js' => array('Jquery'),'Html','Form');
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());
}
}
Try:
$this->Auth->login($user['User']);
This was nothing to do with the cakephp app but the plugin which i was using for facebook, which did not post data
Maybe the Auth component still refer to username field for authentication instead of email. You can try change to username.
I am developing a Plugin that uses Facebook oAuth as an authentication object for Auth Component. If you want an already-built solution that uses server-side Facebook login, please check my website: http://marianofino.github.com/Facebook-Plugin-for-CakePHP/

$this-Session->destroy() is not destroying the session? v. cakephp 2.0

my UserController.php has logout function that looks like this
function logout()
{
$this->Session->destroy('User');
$this->Session->setFlash('You\'ve successfully logged out.');
var_export($this->Session->read('User'));
//$this->redirect('login');
}
my view Users/index.ctp
<?php echo $this->Html->link('Logout', array('controller' => 'users', 'action' => 'logout')); ?>
When I click "log out" the var_export still displays all the User data and if I go back to Users/index.ctp it still shows me that page even though in my my UserController.php I am checking if User is set
function beforeFilter()
{
$this->__validateLoginStatus();
}
function __validateLoginStatus()
{
if($this->action != 'login' && $this->action != 'logout')
{
if($this->Session->check('User') == false)
{
$this->redirect('login');
}
}
It does not redirect to login page and just brings me to index page.
}
$this->Session->destroy();
The destroy method will delete the session cookie and all session data stored in the temporary file system.
User to remove, use better delete.
$this->Session->delete('User');
If you use the AuthComponent to authenticate the users, you can log them out by using the logout() method.
$this->Auth->logout();
See http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out for Cake 2 or http://book.cakephp.org/1.3/en/view/1262/logout for Cake 1.3
And if you don't use the AuthComponent at all, you should maybe have a look at it as it contains out of the box many functionalities that you have already or will likely implement yourself.

CakePHP + Facebook

I am trying to implement facebook Connect to my cakephp Application. i am using Nick's Facebook Plugin.
I wanna implement it this way
When a user Visits the Site he should be able to login via Registration on the site or Facebook Connect
Existing users should be able to connect their account to their FB account
People who first time login to the site using FB Connect and dont have an account on the site. should be redirected to a page where they have to enter details to complete the profile.
What i have done -
I have followed the instruction of Nick to implement it and when i click Login - it connects to my app. but i dont understand how to create a username and password associated with the Fb Connect Id. and user it against the FB token.
Apparently I'm doing the same thing a little before you... ;-)
Here's a method for Facebook login I'm using (slightly redacted and annotated):
public function facebook($authorize = null) {
App::import('Lib', 'Facebook.FB');
$Fb = new FB();
$session = $Fb->getSession();
// not logged into Facebook and not a callback either,
// sending user over to Facebook to log in
if (!$session && !$authorize) {
$params = array(
'req_perms' => /* the permissions you require */,
'next' => Router::url(array('action' => 'facebook', 'authorize'), true),
'cancel_url' => Router::url(array('action' => 'login'), true)
);
$this->redirect($Fb->getLoginUrl($params));
}
// user is coming back from Facebook login,
// assume we have a valid Facebook session
$userInfo = $Fb->api('/me');
if (!$userInfo) {
// nope, login failed or something went wrong, aborting
$this->Session->setFlash('Facebook login failed');
$this->redirect(array('action' => 'login'));
}
$user = array(
'User' => array(
'firstname' => $userInfo['first_name'],
'lastname' => $userInfo['last_name'],
'username' => trim(parse_url($userInfo['link'], PHP_URL_PATH), '/'),
'email' => $userInfo['email'],
'email_validated' => $userInfo['verified']
),
'Oauth' => array(
'provider' => 'facebook',
'provider_uid' => $userInfo['id']
)
);
$this->oauthLogin($user);
}
This gives me an array with all the user details I could grab from Facebook and invokes ::oauthLogin, which either logs the user in with the given information or asks the user to fill in missing details and/or creates a new user record in the database. The most important part you get from the Facebook API is the $userInfo['id'] and/or email address, either of which you can use to identify the user in your database. If you're using the AuthComponent, you can "manually" log in the user using $this->Auth->login($user_id), where $user_id is the id of the user in your own database.
private function oauthLogin($data) {
$this->User->create();
// do we already know about these credentials?
$oauth = $this->User->Oauth->find('first', array('conditions' => $data['Oauth']));
if ($oauth) {
// yes we do, let's try to log this user in
if (empty($oauth['User']['id']) || !$this->Auth->login($oauth['User']['id'])) {
$this->Session->setFlash('Login failed');
}
$this->redirect('/');
}
// no we don't, let's see if we know this email address already
if (!empty($data['User']['email'])) {
$user = $this->User->find('first', array('conditions' => array('email' => $data['User']['email'])));
if ($user) {
// yes we do! let's store all data in the session
// and ask the user to associate his accounts
$data['User'] = array_merge($data['User'], $user['User']);
$data['Oauth']['user_id'] = $user['User']['id'];
$this->Session->write('Oauth.associate_accounts', $data);
$this->redirect(array('action' => 'oauth_associate_accounts'));
}
}
// no, this is a new user, let's ask him to register
$this->Session->write('Oauth.register', $data);
$this->redirect(array('action' => 'oauth_register'));
}
Look no further. Here is an excellent article that'll guide you all the way through (minus any readymade plugins):
Integrating Facebook Connect with CakePHP's Auth component
Simply follow the approach described in there.
Cheers,
m^e

Auto login in CakePHP

I am using the registration form for different users? After a new user logs in, the registered users should redirect to an after-login page. We are using Auth component for the authentication.
How do I do this?
If you want the user to auto-login after registering, you can use the AuthComponent's login() method.
if ($this->User->save($this->data)) {
$this->Auth->login($this->data);
}
On newer Cakes, you only need to add
$this->Auth->login();
after you add the user into the database.
I'm not sure what the question is, but it sounds like you're wondering how to send a user somewhere after a successful login. If that's correct, try this:
$this->Auth->loginAction = array (
'controller' => 'whichever_controller',
'action' => 'desired_action',
'admin' => true
);
The admin key may not be necessary if you're not accessing /admin/whichever_controller/desired_action.
You will have to call the login method manually from your register action.
Save the username + unhashed password in an array then call it from the method after the save like this:
$data = array('username' => 'user', 'password' => $unhashedPw);
$this->User->login($data);

Resources