Weird Laravel Auth Attempt Always Return False - laravel-6

I encountered this annoying error when using custom LoginController, where the Auth::attempt always return false. I tried every solutions posted online but nothing works, any idea whats happening in this Laravel6 application ?
public function authenticate(Request $request) .......
$ubersmith = ///external api call to get email
if (Auth::attempt(['email' => $ubersmith->data->email, 'password' => $request->input('password')])) {
// Authentication passed...
var_dump('login');
return redirect('/');
}
$user = \App\User::create([
'password' => Hash::make($request->input('password')),
'email' => $ubersmith->data->email,
'name' => $ubersmith->data->fullname
]);
Auth::login($user);
var_dump($user);
return redirect('/2');
}

Looking at your code, seems that there's nothing wrong with it. You can try debugging it, e.g. putting dd($ubersmith->data->email); and dd($request->input('password')); to check if you're passing the correct data.
Another possibility is you're putting the incorrect password. Can you try doing:
dd(Hash::make($request->input('password')));
Then update your password using this value, then try to authenticate again.

Related

the auth_key of yii2 is'nt interference in cookie base

I have problem with auth_key , I have login form and it's work correctly without remember me and with remember me , but I read yii document , in that document wrote about remember me work with id and auth_key for create cookie to stay user in long time , i check the framework code and in there have three parameters (id, auth_key, expire_time()) i save auth_key in user table and it's code here
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
public function getAuthKey()
{
return $this->auth_key;
}
but i have problem , it's if a user login in site and i go to the user table and change the auth_key field , and now if user refresh the page it must be throw out the site because it's auth key is changed , but the user stay login in site , where is problem ?
The main use of auth_key is to authenticate the user by cookie (user don't have to put login data again). When you choose to be remembered at Login, this is how you are remembered. The system has to identify and login you somehow. It won't log out user if u change it.
You can try to change the key yourself in the "ValidateAutney" method, but this will be a bad practice, it is better to set the session time.
'session' => [
'class' => 'yii\mongodb\Session',
'writeCallback' => function($session)
{
return [
'user_id' => Yii::$app->user->id,
'agent' => Yii::$app->request->getUserAgent(),
'ip' => Yii::$app->request->getUserIP(),
'auth_key' => Yii::$app->security->generateRandomString(),
];
}
],
public function getAuthKey()
{
Yii::$app->session->open();
$query = new Query();
$query->select(['auth_key'])
->from('cache')
->where(['id'=> Yii::$app->session->id ]);
$row = $query->one();
return $row['auth_key'];
}

Yii - Calling api request within CConsole

I have the following issue:
I have a local db with comments and I need to do some actions with some users I'm getting via an API request.
Code is something like this:
class RunCronCommand extends CConsoleCommand {
public function actionIndex() {
...
$comments = Comment::model()->findAll('status = :status', array(':status' => Comment::ACTIVE));
foreach ($comments as $comment) {
$profile = Yii::app()->api->get('/users/'. $comment->user_id . '/getProfile');
}
...
}
When I execute the command I'm getting this error
exception 'CException' with message 'Property "CConsoleApplication.api" is not defined.' in /var/www/core/trunk/common/lib/Yii/base/CComponent.php:131
Any thoughts?
thanks in advance!
Thank you for your reply.
Got it fixed by adding the class into console/config/main.php
'components' => array(
'api' => array(
'class' => 'common.extensions.Api.Api'
),
You will have to rethink the design of the application.
From your example, you might want to use Curl, although I think this might be overkill/
To run an action in a controller, you can use something like
Yii::import('application.modules.moduleName.controllers.ControllerName');
$controller_instance = new ControllerName("Default");
$controller_instance->actionIndex();
Look here for additional information.

ZF2 Authentication

i am developing an application using ZF2. I have done the user authentication with username & password. But, i would like to check an additional column(example: status) in authentication.
I have done the following codes.
public function authenticate()
{
$this->authAdapter = new AuthAdapter($this->dbAdapter,
'usertable',
'username',
'password'
);
$this->authAdapter->setIdentity($this->username)
->setCredential($this->password)
->setCredentialTreatment('MD5(?)');
$result = $this->authAdapter->authenticate();
return $result;
}
How can i check the column 'status' in authentication?
Note: status value should be 1.
Thanks.
When I was building my authentication using zf2 and doctrine, I have created authorization plugin and customized this adapter for passing extra column for authentication.
You probably need to go on similar directions.
$adapter = new AuthAdapter($db,
'users',
'username',
'password',
'MD5(?)'
);
// get select object (by reference)
$select = $adapter->getDbSelect();
$select->where('active = "TRUE"');
// authenticate, this ensures that users.active = TRUE
$adapter->authenticate();
Reference
After changes your code should look something like this.
public function authenticate()
{
$this->authAdapter = new AuthAdapter($this->dbAdapter,
'usertable',
'username',
'password'
);
$select = $this->authAdapter->getDbSelect();
$select->where('status= "1"');
$this->authAdapter->setIdentity($this->username)
->setCredential($this->password)
->setCredentialTreatment('MD5(?)');
$result = $this->authAdapter->authenticate();
return $result;
}
ZF2 provides a another way to handle additional checks using other columns than the ones foreseen for identity and credential thanks to the method getResultRowObject. All columns of usertable in your example are available as properties of the object returned by getResultRowObject(). So you could expand your code with this :
if ($result->isValid()) {
$identityRowObject = $this->authAdapter->getResultRowObject();
$status = $identityRowObject->status;
// do whatever complex checking you need with $status...
}
Regards,
Marc

zfcUser getState in another module

how could i getState from zfcUser
in view/index.phtml i get it from $this->zfcUserIdentity()->getState();
but now i need to get this value ( state for this user who is logged in ), in other module /controller (this is my costum module controller)
so i need to get State from:
zfcUser/Entity/User
to
myModule/Controller
i watch this https://github.com/ZF-Commons/ZfcUser/wiki/How-to-check-if-the-user-is-logged-in but this solutons is not helpful
and this helps too, for me:
$sm = $this->getServiceLocator();
$auth = $sm->get('zfcuserauthservice');
if ($auth->hasIdentity()) {
$user_edit = $auth->getIdentity()->getPrem();
}
The state is a property from the user itself. So if you get the user throught the identification service, you can grab the state from there.
public function myFooAction()
{
if ($this->zfcUserAuthentication()->hasIdentity()) {
$user = $this->zfcUserAuthentication()->getIdentity();
$state = $user->getState();
}
}
Mind that when the user is not logged in, the if condition is false. Also the state can be null or any arbitrary value, so do not expect that every user returns a valid state (in other words, check the returned value!)
follow this code, I had same problem then I have manage how to use identity of logged in user via zfcUser
in other modules controller at topside,
use Zend\EventManager\EventManagerInterface;
then create this two function in the sameclass,
public function setEventManager(EventManagerInterface $events)
{
parent::setEventManager($events);
$controller = $this;
$events->attach('dispatch', function ($e) use ($controller) {
if (is_callable(array($controller, 'checkUserIdentity')))
{
call_user_func(array($controller, 'checkUserIdentity'));
}
}, 100);
}
public function checkUserIdentity()
{
if ($this->zfcUserAuthentication()->hasIdentity()) {
echo "<pre>"; print_r($this->zfcUserAuthentication()->getIdentity());die;
}
}
it will give this kind of output
Admin\Entity\User Object
(
[id:protected] => 2
[username:protected] =>
[email:protected] => rajat.modi#softwebsolutions.com
[displayName:protected] =>
[password:protected] => $2y$14$2WxYLE0DV0mH7txIRm7GkeVJB3mhD4FmnHmxmrkOXtUFL7S9PqWy6
[state:protected] =>
)
That's it you will automatically get Identity whether user is logged in if not then it will redirect to login page.
Hope this will helps

Saving data with cakephp won't work

I'm trying to load, edit and save a record with CakePHP 2.0 but I get a generic error during the save method that don't help me to understand where is the problem.
if I try with debug($this->User->invalidFields()); I get an empty array, but I get false from $this->User->save() condition.
Here is the controller action where I get the error:
public function activate ($code = false) {
if (!empty ($code)) {
// if I printr $user I get the right user
$user = $this->User->find('first', array('activation_key' => $code));
if (!empty($user)) {
$this->User->set(array (
'activation_key' => null,
'active' => 1
));
if ($this->User->save()) {
$this->render('activation_successful');
} else {
// I get this error
$this->set('status', 'Save error message');
$this->set('user_data', $user);
$this->render('activation_fail');
}
debug($this->User->invalidFields());
} else {
$this->set('status', 'Account not found for this key');
$this->render('activation_fail');
}
} else {
$this->set('status', 'Empty key');
$this->render('activation_fail');
}
}
When I try the action test.com/users/activate/hashedkey I get the activation_fail template page with Save error message message.
If I printr the $user var I get the right user from cake's find method.
Where I'm wrong?
I think the problem may be in the way you're querying for the User record. When you do this:
$user = $this->User->find('first', array('activation_key' => $code));
The variable $user is populated with the User record as an array. You check to ensure it's not empty, then proceed; but the problem is that $this->User hasn't been populated. I think if you tried debug($this->User->id) it would be empty. The read() method works the way you're thinking.
You could try using the ID from that $user array to set the Model ID first, like so:
if (!empty($user)) {
$this->User->id = $user['User']['id']; // ensure the Model has the ID to use
$this->User->set(array (
'activation_key' => null,
'active' => 1
));
if ($this->User->save()) {
...
Edit: Well another possible approach is to use the $user array instead of modifying the current model. You said that you get back a valid user if you debug($user), so if that's true you can do something like this:
if (!empty($user)) {
$user['User']['activation_key'] = null;
$user['User']['active'] = 1;
if ($this->User->save($user)) {
...
This method works in the same way as receiving form data from $this->request->data, and is described on the Saving Your Data part of the book.
I'm curious though if there's another part of your setup that's getting in the way. Can other parts of your app write to the database properly? You should also check to make sure you aren't having validation errors, like their example:
<?php
if ($this->Recipe->save($this->request->data)) {
// handle the success.
}
debug($this->Recipe->validationErrors);