Login Redirect with cakephp - cakephp

I am current using Usermgmt Plugin for the login function and the users management. What I want to do is to redirect the specific pages based on the group_id after they login. I am current lost with the cake.
This is the code from AppController.
var $helpers = array('Form', 'Html', 'Session', 'Js', 'Usermgmt.UserAuth');
public $components = array('Session','RequestHandler', 'Usermgmt.UserAuth');
function beforeFilter(){
$this->userAuth();
}
private function userAuth(){
$this->UserAuth->beforeFilter($this);
}
This is the login function from UsersController.
public function login() {
if ($this->request -> isPost()) {
$this->User->set($this->data);
if($this->User->LoginValidate()) {
$email = $this->data['User']['email'];
$password = $this->data['User']['password'];
$user = $this->User->findByUsername($email);
if (empty($user)) {
$user = $this->User->findByEmail($email);
if (empty($user)) {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
// check for inactive account
if ($user['User']['id'] != 1 and $user['User']['active']==0) {
$this->Session->setFlash(__('Your registration has not been confirmed please verify your email or contact to Administrator'));
return;
}
$hashed = md5($password);
if ($user['User']['password'] === $hashed) {
$this->UserAuth->login($user);
$remember = (!empty($this->data['User']['remember']));
if ($remember) {
$this->UserAuth->persist('2 weeks');
}
$OriginAfterLogin=$this->Session->read('Usermgmt.OriginAfterLogin');
$this->Session->delete('Usermgmt.OriginAfterLogin');
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
$this->redirect($redirect);
} else {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
}
}
Any help is appreciated. Thank you.

If you want to redirect them somewhere else, then change the redirect line. This assumes your User model is related to a Group model and the recursive level lets your find call pull the data.
// original
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
// new redirect, eg: /groups/view/3
$redirect = array(
'controller' => 'groups',
'action' => 'view',
$user['Group']['id']
);
$this->redirect($redirect);

Related

How to encrypt a password in cakephp 2.x version

Hello everyone i am using cakephp 2.x, as i am new to here, i need to encrypt my password before it stores to database
User.ctp : I am posting like this to post
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
Controller:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
Login controller:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
How can i encrypt the password file and also how can use the Model
As you are using CakePhp go with framework's best practices.
When creating new user records you can hash a password in the
beforeSave callback of your model using appropriate password hasher
class:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
You don’t need to hash passwords before calling $this->Auth->login(). The various authentication objects will hash passwords individually.
If you are using different model than User for authentication you need to define that in AppController. In your Case you need to do something like this in AppController:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
If you wish to hash your password, try this:
$hashedPassword = AuthComponent::password('original_password');
See Here :Cakephp Password Hashing.

AngularJS - Get Authenticated User Data

I'm trying to get the authenticated user data so I can display the name of the user. I'm using AngularJS and Laravel.
When I do:
public function getUser(){
if(Auth::check()){
$user = Auth::user();
$token = JWTAuth::fromUser($user);
dd($user);
return response()->success(compact('user','token'));
}
}
The Auth is null, but I'm logged in.
This is my login method
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:8',
]);
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->error('Invalid credentials', 401);
}
} catch (\JWTException $e) {
return response()->error('Could not create token', 500);
}
$user = Auth::user();
return response()->success(compact('user', 'token'));
}
Thanks !

When I click on login button it is directly going into else part in cakephp

if I click on login button, it is taking empty input values since the condition is directly going into else part of cakephp.
Below is the code:
if($this->request->is('post'))
{
if(isset($this->data['Loginsubmit']))
{
if($this->data['Reg']['email']=='')
{
echo 'hii';
}
elseif( $this->data['Reg']['password']=='')
{
echo "hi";
}
else
{
$result = $this->Reg->find('list',array('conditions'=>array('email'=>$this->request->data['Reg']['email'], 'password'=>$this->request->data['Reg']['password'],'status'=>1)));
pr($result);
if(!empty($result)){
$email=$this->request->data['Reg']['email'];
$this->Session->write('Reg', $result);
$this->redirect(array('action' => 'login'));}
else{$this->Flash->error("invalid");
}
$result = $this->Reg->find('all');
$this->set('results',$result);
}
Hi please do like this:
public function beforeFilter() {
parent::beforeFilter();
// Allow users to register and logout.
$this->Auth->fields = array(
'email' => 'email',
'password' => 'secretword'
);
}
public function login() {
if(!$this->Auth->Reg('id')){
$this->layout="login";
if ($this->request->is('post')) {
App::uses('Validation', 'Utility');
$user=0;
if(Validation::email($this->request->data['email']))
$user = $this->Reg->find('first', array(
'conditions' => array( 'Reg.email' => $this->request->data['email'],
),'recursive' => -1 ));
if($user)
{
$this->request->data['email']=$user['Reg']['email'];
}
$this->request->data=array('Reg'=>$this->request->data);
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
else
{
return $this->redirect($this->Auth->redirectUrl());
}
}
Please review & share your feedback.

How to apply Role based authorization after login in cakephp 2.7?

I'm new on cakephp . I have implementd a code for login and I m trying to providing Role based action for differecnt users.
Such as I have a table in which i store id and role (Admin,Normal,SubAdmin).
I want that super admin can add delete update and edit and view everones record.
Admin can only edit and delete add users and cant delete/edit his record.
How could i achieve this.
you can do by use this code
In your App Controller :
class AppController extends Controller {
public $components =array(
'Session',
'Flash',
'Auth'=>array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'Email','password'=>'Passward'),
)),
'loginRedirect'=>array('controller'=>'Users','action'=>'index'),
'logoutRedirect'=>array('controller'=>'Users','action'=>'login'),
'authError'=>"You Can't access this page",
'authorize' => array('controller')
)
);
public function beforeFilter()
{
$this->Auth->allow('index');
}
public function isAuthorized($user)
{
return true;
}
}
In your Users Controller:
class UsersController extends AppController {
public $helpers = array('Html', 'Form','Session','Flash');
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('add');
}
public function isAuthorized($user) {
// The owner of a post can edit and delete it
if (in_array($this->action, array('edit', 'delete'))) {
switch ($user['Role']) {
case "Super user":
return true;
break;
case "Admin":
if($user['id']==$this->request->params['pass'][0])
{
return false;
}
else
{
return true;
}
break;
default:
return false;
}
}
return true;
}

cakephp login redirect

I have a user front end and an admin area. If a user is signed in and trys to go to the to the admin url they are redirected to the index page. I wish to redirect them to the admin login page with a message to login as administrator.
There may be a case where a admin is logged in as a user and then trys to login into the admin area. I have not been able to rediect to the admin login and give option to log out and log in as admin.
app_controller
function beforeFilter() {
$this->Auth->loginError = "Wrong credentials";
$this->Auth->authError = "This part of the website is protected.";
//Configure AuthComponent
$this->Auth->allow('display');
$this->Auth->authorize = 'actions';
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
//$this->Auth->autoRedirect = false;
//$this->Auth->loginRedirect = array('controller' => 'reservatins', 'action' => 'index');
} // end before filter
users_controller
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allowedActions = array('admin_login','admin_logout');
//$this->Auth->allowedActions = array('*');
$this->set('select_nav', array('admin','users'));
}
function admin_login() {
// $this->layout = 'admin'; // nothing required
$this->layout = 'blank'; // nothing required
}
I have done that on one of my projects. The user is ever logged in (as Anonymous, as User or as Admin) and, depending on from where is he coming, and the current permissions he have, I show different login errors.
To do that.. this is what I did...
First, you need to use the "controller" authorize method:
$this->Auth->authorize = 'controller';
From now on, all your actions will pass through the isAuthorized method of your current controller. As I have my users, groups and permissions on my database and every group have different permissions, I created the isAuthorized method on my app_controller:
public function isAuthorized()
{
if ( !$this->__permitted($this->name, $this->action) )
{
$this->cakeError('error403');
return false;
}
return true;
}
What I'm doing here is checking for user permissions through my AppController __permitted method (it simply checks for permissions on session; if we don't have them saved in session, I check for them on the DB and then I store them on the Session).
If the user don't have permissions, I show him the error 403. And here is the funny part.
In your AppError add a method called error403, and here you can control where to redirect the user and what kind of message to show to him.
Here is the code I've used (obviously you must create your own piece of code according to your needs):
public function error403()
{
// Extract params
extract($this->controller->params, EXTR_OVERWRITE);
// Store url to be redirected on success
if (!isset($url))
{
$url = $this->controller->here;
}
if (isset($url['url']))
{
$url = $url['url'];
}
$url = Router::normalize($url);
// The page is trying to access is an admin page?
$is_admin_page = isset($this->controller->params['admin']) && $this->controller->params['admin'] == true ? true : false;
if (!empty($url) && count($url) >= 2)
{
$query = $url;
unset($query['url'], $query['ext']);
$url .= Router::queryString($query, array());
}
// 403 header
$this->controller->header("HTTP/1.0 403 Forbidden");
// If my method is NOT an upload
if (!preg_match('/upload/', $url))
{
// Write referer to session, so we can use it later
$this->controller->Session->write('Auth.redirect', $url);
}
else exit; // else exit, so we prevent 302 header from redirect
// NOTE: we can't use $this->controller->Auth->loginAction because there's no controller loaded
$loginAction = array('controller' => 'users', 'action' => 'login');
// If is ajax...
if (isset($this->controller->params['isAjax']) && $this->controller->params['isAjax'] == true)
{
$this->controller->layout = 'ajax';
$message = __("No tens permisos per fer aquesta acció", true);
// If user is anonymous..
if ( $this->controller->ISession->isAnonymous() )
{
// AJAX Error Message
$message = __('La teva sessió no està iniciada.', true)
. ' <a href="'.Router::url($loginAction).'">'
. __('Fes clic aquí per iniciar-la', true) . '</a>';
}
$this->controller->set(compact('message'));
$this->controller->render('error403');
$this->controller->afterFilter();
echo $this->controller->output;
}
else
{
$message = __("No tens permisos per fer aquesta acció", true);
$redirect = $this->controller->referer();
// If is anonymous...
if ($this->controller->ISession->isAnonymous())
{
$message = __('La teva sessió no està iniciada.', true);
$redirect = $loginAction;
}
// If user can't access the requested page, we redirect him to login
if (!$this->controller->ISession->userCan($redirect))
{
$redirect = $loginAction;
}
// Show different auth messages for admin and user pages
$this->controller->Session->setFlash($message, $is_admin_page ? 'default' : 'gritter', array(), 'auth');
$this->controller->redirect($redirect, null, true);
}
}
Remember, this is the code for my case. You should create your own error403 page according to your needs. Of course, you can start with my method to get it :)

Resources