Trying to Authenticate user without password in Laravel - php

I am trying to implement the login without password in laravel application but it shows an error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, string given
And the code i am using is:
$checkUser = 'manish.arora4926#gmail.com';
Auth::login($checkUser, true);
Please help me to resolve this issue.

Considering your email column name is email, try
$user = User::whereEmail('manish.arora4926#gmail.com')->first();
Auth::login($user)
or
Auth::loginUsingId($user->id);

If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. Of course, the App\User model included with Laravel already implements this interface:
$checkUser must be eloquent instance. so you need to access eloquent before authenticate user
$checkUser=App\User::where('email','manish.arora4926#gmail.com')->first();
Auth::login($checkUser, true);
in case you know id of user just using login using id
Auth::loginUsingId(1);
// Login and "remember" the given user...
Auth::loginUsingId(1, true);

Related

Laravel blade: Access method inside User model for authorized user

Authorized user info can be accessed in blades using auth()->user()->info.. , also other users info by App\User::where('id' , someid) , but how to call methods inside User Model for authorized user?
What i tried:
App\User::where('id' , auth()->user()->id)->MyMethod(another-user-instance); //Error: undefined method
App\User::MyMethod(another-user-instance): //Error: Wrong call, Its not static method!
App\User->MyMethod(another-user-instance): //Error: What? Unexpected ->
I have a Post model that is connected to User model using belongsTo, I can easily access my method in User by $AnyPostInstance->BelongToUser->MyMethod(another-user-instance) , but i don't know how to handle it for authorized user.
Well, first of all, calling the following is redundant:
App\User::where('id' , auth()->user()->id)
You're accessing the existing User, via auth()->user() to get its id and query for the exact same User. Don't do that.
Secondly, you need to use ->first() if you're calling App\User:
$user = App\User::first()->myMethod();
If you don't call ->first(), then you're accessing the Builder class, which doesn't have a myMethod() function.
So, ways to access:
auth()->user()->myMethod();
// This will access the currently logged in User
App\User::first()->myMethod();
// This will get the first User from the database
App\User::where("id", "=", $someUserId)->first()->myMethod();
// This will return a specific user matching `$someUserId`
You should do something like this:
App\User::where('id' , auth()->user()->id)->first()->MyMethod(another-user-instance);
The line above can be replaced with this one:
auth()->user()->myMethod(another-user-instance);
Hope it helps.

How do I get the logged in user's id in symfony 4?

The user can log in, but i need his id to show his profile. Since i'm working in symfony 4, the many possible answers i've found were obsolete.
https://symfony.com/doc/current/security.html#retrieving-the-user-object
After authentication, the User object of the current user can be accessed via the getUser() shortcut (which uses the security.token_storage service). From inside a controller, this will look like:
public function index()
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
}
The user will be an object and the class of that object will depend on your user provider. But, you didn't tell us what user provider you are using, so I have no way of telling you, beyond this, how to get to the id itself.
One other way to get the user:
An alternative way to get the current user in a controller is to type-hint the controller argument with UserInterface (and default it to null if being logged-in is optional):
use Symfony\Component\Security\Core\User\UserInterface\UserInterface;
public function indexAction(UserInterface $user = null)
{
// $user is null when not logged-in or anon.
}
This is only recommended for experienced developers who don't extend from the Symfony base controller and don't use the ControllerTrait either. Otherwise, it's recommended to keep using the getUser() shortcut.

Symfony token getCredentials returns null

I created a way to authenticate a user with API keys, thanks to a class A implementing the SimplePreAuthenticatorInterface interface. Everything works well (the user is successfully authenticated).
I'm trying to store the API keys, for a later use during the user's journey. To do so, inside the authenticate method of my class A, I return a PreAuthenticatedToken in which the credentials are my API keys.
The problem is : Inside a custom service, when I try to get the token credentials, I get null... I successfully get the API keys when I comment the line 76 of the PreAuthenticatedToken Symfony core class :
public function eraseCredentials()
{
parent::eraseCredentials();
//$this->credentials = null;
}
My questions are:
1) Why is the method eraseCredentials called whereas the user is authenticated? I thought this method was called during user's logging out...
2) What am I doing wrong? Is the PreAuthenticatedToken token the right place to store my API keys? How can I get them back from a custom service ?
Thanks for helping me. :)
PS : I'm a newbee on posting in Stackoverflow (and in English ^^). Sorry in advance for any mistakes.
I found another similar question but it has no helping response and I added some more precisions.
EDIT: The code of my custom service where I try to get the credentials is:
$token = $this->container->get("security.token_storage")->getToken();
if ($token !== null) {
$credentials = $token->getCredentials();
// $credentials is null here
}
EDIT 2: The return part in my code of my SimplePreAuthenticatorInterface::authenticateToken method :
return new PreAuthenticatedToken(
$user,
$apiKeys,
$providerKey,
$user->getRoles()
);
Ad 1. It depends on your AuthenticationProviderManager: this class accepts $eraseCredentials as second parameter - by default set to true (here).
That's why eraseCredentials method is being called on PreAuthenticatedToken $token during authenication (here).
Ad 2. Please check How to Authenticate Users with API Keys tutorial. You should create your custom ApiKeyAuthenticator class and add logic there.
According to your comment:
Note that authenticateMethod from tutorial is being called inside authenticate method (here). At that time token credentials are not erased yet and you can access them. For security reason they are erased after authentication (but this can also be changed / configured via security.yml file). If you need them later you can introduce custom token class and store API key there.

create custom authenticate controller with different database filed in Laravel

Auth::attempt(['u_email'=>$credentials['email'],'u_password'=>sha1($credentials['password'])])
i'm use this code for authentication but i'm getting Undefined index: password error can any one help for create custom authentication control without changing in vendor library
Thank you in advance for help me...
There are 3 things you need to do.
Pass plain-text password to Auth::attempt() as Laravel will hash that itself before verifying it against the hash stored in the database.
Auth::attempt(['u_email'=>$credentials['email'],'password' => $credentials['password']]);
Pass password as password, not u_password to Auth::attempt(). The key doesn't need to match the password column name (why? see point 3.), but it must be equal to password - see point 1 for example.
Implement getAuthPassword() method in your user model, that will return value of u_password column. This method is used by user provider to fetch the password hash that is later verified against what was passed to Auth::attempt()
//in your User.php
public function getAuthPassword() {
return $this->u_password;
}

FOSOAuthServerBundle - How to get User in a controller

I implemented FOSOAuthServerBundle in my application to provide an API for mobile application. It seems to work, the user gets the Token and also the RefreshToken but if I make the controller require the user object that always returns null. Also fails the control of the permission, which is only IS_AUTHENTICATED_ANONIMOUSLY.
example:
public function showUserAction(){
$user = $this->getUser()
//$user = null
$auth = $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')
//$auth = false
}
How to get the user object in a controller with this type of authentication?
Based on your comment you have created client with different grant_types.
NOTE: If you use grant_type=client_credentials during authentication, there is no User available since you do not specify exact user/password for generating token. In case of grant_type=password you pass username & password and token is linked to user in this case. Hope this makes sense.
Try this:
$user = $this->get('security.token_storage')->getToken()->getUser();

Categories