Why user didn't logout after browser closed in Yii? - authentication

This problem isset only in Chrome and Firefox. Opera and Safari works fine.
On login, I don't checking rememberMe option.
allowAutoLogin set to TRUE
Here is my login method from LoginForm model:
public function login()
{
if ($this->_identity === NULL)
{
$this->_identity = new UserIdentity($this->login, $this->password);
$this->_identity->authenticate();
}
if ($this->_identity->errorCode === UserIdentity::ERROR_NONE)
{
$duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
Yii::app()->user->login($this->_identity, $duration);
return TRUE;
}
else
return FALSE;
}
And here is my action:
public function actionLogin()
{
$model = new LoginForm;
// if it is ajax validation request
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if (isset($_POST['LoginForm']))
{
$model->attributes = $_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) $this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login', array('model' => $model));
}

In the config (protected/config/main.php) you can change allowAutoLogin to false
'components' => array(
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => false,
),
Read more about Yii login states here http://www.yiiframework.com/doc/api/1.1/CWebUser

Related

Laravel 8 API Authentication

This is Register Function in AuthController.php
public function register(Request $request)
{
if($request->type == 'ServiceMen')
{
$u = Workers::where('mobile',$request->mobile)->first();
if($u != null)
{
if(Auth::attempt(['mobile' => $request->mobile, 'password' => 'password'])){
echo "in";
$user = Auth::user();
$success['token'] = $user->createToken('jhbasdj')->plainTextToken;
$success['mobile'] = $user->mobile;
//return response()->json($success, 200);
}
echo "else";
}
}
elseif($request->type == 'User')
{
$u = User::where('mobile',$request->mobile)->first();
if($u==null)
{
$input = $request->all();
$input['password'] = bcrypt('password');
$user = User::create($input);
}
if(Auth::attempt(['mobile' => $request->mobile, 'password' => 'password'])){
$user = Auth::user();
$success['token'] = $user->createToken('kjsdbvk')->plainTextToken;
$success['mobile'] = $user->mobile;
return response()->json($success, 200);
}
}
}
I need to login staff from workers table and user from user model but user authentication works fine. I don't know how to login with workers model as a staff.
please help me with this.

Yii2 Login failed to validate password

As the title says, i have a little bit of trouble in this area of the application. So basically, in my UserController i hash the password & in the login page it's verified with the standard security tool. Everything from the form to the user is good, but the check fails to return true. I don't have any interactions with the password in beforeSave/beforeValidate. Any ideas?
UserController:
public function actionRegister()
{
$model = new User(['scenario' => 'register']);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->password_usr = Yii::$app->security->generatePasswordHash($model->password_usr);
if ($model->save()) {
Yii::$app->session->setFlash('success', 'User created');
return $this->redirect('/site/login');
} else {
die(print_r($model->getErrors()));
}
}
return $this->render('register', [
'model' => $model,
]);
}
SiteController:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login();
return $this->goBack();
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
User model:
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_usr);
}
Login form is the default as the yii2 generates
Maybe this is a problem
die(print_r($model->getErrors()));
login
public function actionLogin()
{
$this->layout = "login";
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
}
return $this->render('login', [
'model' => $model,
]);
}
signup
public function actionSignup()
{
$this->layout = "login";
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
the problem was the password field in the database, it was varchar(30) whilst generatePasswordHash returns a 60 char string

cakephp 3.0 Auth & single sign on

I am using cakephp 3.0 and in the login page although I try to enter the right credentials i get invalid username or password message.
In my user table , I have the fields username and password by which i want to authenticate user.
I have tried to follow the cake book documentation for 3.0 except the step where for including password hashing.Also used the table structure similiar to the one in cakephp documentation
Is it because it is accessing the wrong table?I have mentioned the fields in App Controller
Also if i have to implement single sign on ,is there a plugin which could help me out?Please provide links to such tutorials as this is important for my graduate studies project
My model file:
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->table('users');
$this->displayField('User_id');
$this->primaryKey('User_id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->notEmpty('id', 'create')
->notEmpty('username','Username is required')
->notEmpty('password','Password is required')
->notEmpty('role');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['username']));
return $rules;
}
}
My UserController file
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Core\App;
use Cake\Event\Event;
class UsersController extends AppController
{
public function view($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
$this->set('user', $user);
$this->set('_serialize', ['user']);
}
public function register()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user basic details has been saved.');
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success('The user has been deleted.');
} else {
$this->Flash->error('The user could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
// Allow users to register and logout.
// You should not add the "login" action to allow list. Doing so would
// cause problems with normal functioning of AuthComponent.
$this->Auth->allow(['register', 'logout']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
$this->set('user',$user);
if ($user) {
$this->Auth->setUser($user);
$this->Flash->error(__('Login successful'));
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users', $this->paginate($this->Users));
$this->set('_serialize', ['users']);
}
}
My AppController file
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginRedirect' => [
'controller' => 'Orders',
'action' => 'view'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
$this->Auth->allow(['display']);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display','login']);
}
}
My login page:
<div class="users_form">
<?=$ this->Flash->render('auth') ?>
<?=$ this->Form->create() ?>
<fieldset>
<legend>
<?=_ _( 'Please enter your username and password') ?>
</legend>
<?=$ this->Form->input('username') ?>
<?=$ this->Form->input('password') ?>
</fieldset>
<?=$ this->Form->button(__('Login')); ?>
<?=$ this->Form->button(__('Register')); ?>
<?=$ this->Form->end() ?>
</div>
I figured out what was wrong.
First place I had not included the password hasher method.
On trying to include that ,I added it to the wrong module.It must be added for the Entity class file whereas I was adding it to The UserTable.php.
This was not helping my case at all.I followed the manual to the T .
After adding the password Hasher module I added a new user.
Also it is true that it works only if the password length is varchar(255)
Therefore the user along with hashed password was created.
I was then able to login

Not authorized to perform this action when admin login

in file Controller:
class Controller extends CController
{
public function filters()
{
return array('accessControl');
}
public function accessRules()
{
return array(
array('allow',
'actions' => array('login', 'logout'),
'users' => array('*'),
),
array('allow',
'actions' => array('*'),
'roles' => array('admin'),
),
array('deny',
'users' => array('*'),
),
);
}
}
in file WebUser:
class WebUser extends CWebUser
{
public function checkAccess($operation, $params = array())
{
if (empty($this->id)) {
return false;
}
$role = $this->getState("roles");
if ($role === 'admin') {
return true;
}
return ($operation === $role);
}
}
in file UserIdentity:
class UserIdentity extends CUserIdentity
{
private $id;
public function authenticate()
{
$record = AdminModel::model()->findByAttributes(array(
'username'=>$this->username));
if ($record == null) {
$this->errorCode = 'Username invalid';
} elseif($record->password !== $this->password) {
$this->errorCode = 'Password invalid';
} elseif($record->level == 'banned') {
$this->errorCode = 'Account being banned or not enabled';
} else {
$this->id = $record->id;
$this->setState('nameDisplay', $record->display_name);
$this->setState('roles', $record->level);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->id;
}
}
when login, i check: Yii::app()->user->checkAccess('admin'); //return true
but this is error: You are not authorized to perform this action. somebody can help me?
I think this part of code is the problem:
array('deny',
'users' => array('*'),
),
It sais "Deny access to all pages for all users".
try to remove this part of code

Authorization adapter was not found in cakePHP

I'm trying to move my code from local to server
when i try to login into the application
Here is my AppController
class AppController extends Controller{
/* Determines what logged-in users access to */
var $components = array('Auth','Session');
public function isAuthorized($user){
return true;
}
public function beforeFilter(){
$userdetails = array();
$this->Auth->autoRedirect = false;
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'matches', 'action' => 'index');
$this->Auth->authorize = 'controller';
$this->Auth->authError= 'You need permissions to access this page';
$this->Auth->allow('users');
$this->set('Auth',$this->Auth);
$userdetails = $this->Auth->user();
$this->set('myUser', $userdetails['username']);
$this->set('myRole', $userdetails['user_role_id']);
$this->set('pStatus', $userdetails['password_status']);
}
}
Here is my Login Action in UsersController
public function login(){
$this->Auth->autoRedirect = false;
$id = $this->Auth->user('id');
if(empty($id)){
if($this->request->is('post')){
if($this->Auth->login()){
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash('Invalid Username or password');
}
}
}else{
$this->redirect(array('action'=>'index'));
}
}
Thanks for the help
The part where you authorise controllers in your beforeFilter should be capitalised properly:
So:
$this->Auth->authorize = 'Controller';
Instead of:
$this->Auth->authorize = 'controller';
That particular statement tries to find controllerAuthorize.php and should be looking for ControllerAuthorize.php. This doesn't cause a problem on Windows, but it does on Unix systems.