How to display the session 'username' value of the logged-in User using the 'codeigniter4/shield' framework for CodeIgniter 4 - codeigniter

I'm new to CodeIgniter and I installed the codeigniter4/shield authentication and authorization framework for CodeIgniter 4.
I need the session data of the logged-in User such as username, and email.
How can I get it?
What I've tried so far.
$item = $session->get('item');
$name = $_SESSION['name'];

Solution:
Get logged-in username:
auth()->user()->username;
Get logged-in User email:
auth()->user()->getEmail();
Get the 'date & time' when the logged-in User account was created:
auth()->user()->created_at->toDateTimeString();
Get all logged-in User data.
auth()->user()->toRawArray();
Reference:
Auth Helper
The auth functionality is designed to be used with the auth_helper
that comes with Shield. This helper method provides the auth()
command which returns a convenient interface to the most frequently
used functionality within the auth libraries. This must be loaded
before it can be used.
// get the current user
auth()->user();
// get the current user's id
auth()->id();
// or
user_id();

Related

How to login a user at backend without CSRF in Laravel?

I'm trying to make a user logged in at back-end who is already a user of another website of mine. For now I'm able to fetch the user's data from previous website's database using an API and make user registration during the login process. Same time I want this user to be logged in when data is just inserted because now user is existing. I tried to reuse same method $this->processLogin(); but this method takes request function processLogin(Request $request) I can't feel passing email & pass to utilize this same method. I have tried guzzle self request with 3 parms 'email, password, _token' using POST request which didn't work. I don't want to exclude this route as well because it is being used for normal login. How can i make this user logged in right after inserting the required data? Please advise. Thanks in advance.
// if $id is your user that you want to login, then:
auth()->loginUsingId($id);

How to implement ForgotPasswordController in SPA application with Laravel/Sanctum?

I'm using Laravel 7.x and sanctum. Logins are working and I would like to create a Forgot Password option from my SPA application.
I'm struggling with the basics as most of the examples in the documentation rely on the auth scaffolding. So far I've managed to get the following:
I have a controller class called ForgotPasswordController with a method called reset that receives the email to be reset via POST.
I've created a object: $user = User::where('email', $email)->get()->first();
At this point I'm too unfamiliar with the architecture to know where to go next, whether it's the Password facade, I see some additional classes in the Illuminat\Auth\Password namespace. My goal is to create an expiring token, email it to the user via the default email config (I know how to send the email / design the template) and then be able to make the webservice call that will allow the password to be resolved.
Here's what I think I know...
I've set CanResetPassword trait on my user models, which I believe are necessary to support the native methods for password reset
I believe the goal is to create a reset token keyed against the user email that expires after a period of time, then send that token appended to a url in an email (I don't know the architectural implications surrounding the generation of the token beyond the table row)
There's a Password facade with a sendResetLink method - but this
method can't work for spa applications because the base url of the
client app will be different, so I'm assuming something native will have to be re-written. In fact, calling this method will return an error of Route [password.reset] not defined.
I'm assuming I will need the password Facade, if so, what is the method to generate the token? Should I just email the link with the token appended or are there other architectural considerations to support the token expiration?
Apologies if my questions are flawed, I'm unclear on the architecture so I'm making assumptions.
Have you tried Laravel authentication? All authentication requirements have been moved to a package called laravel/ui.
By installing that package you can use Laravel authentication. It will take care of your registration, login, and forgot password processes.
This package will create some controllers for all those processes and those you need for forgot password are
ForgotPasswordController: will generate and send reset password links.
ResetPasswordController: will reset the password by getting user's email, new password, and reset password token.
But if you don't want to use the official Laravel package you should take these steps:
Show a "Request reset password form" to the user.
Validate the provided email by the user.
Generate a random reset password token and store it at DB (Need a table with at least two fields: email and token).
Send that token to the user(It's better if you send it as a URL parameter in the reset password link).
When the user navigated to the reset password page, ask for email again and validate the token by checking your DB table and matching the email and token.
Reset the password to whatever the user wants at this point.
Update: I use this piece of code for generating random tokens:
$email = 'user#email.com';
$token = \Illuminate\Support\Str::random(10);
while(\DB::table('reset_password_tokens')->where('token', $token)->exists()) {
$token = \Illuminate\Support\Str::random(10);
}
\DB::table('reset_password_tokens')->insert(compact('email', 'token'));

Laravel API login with username and token

I am developing a laravel API(MyAPI) with the 5.1 version.I am connecting to this API from a widget which hosted in another website.it has a separate API(hostAPI). I need to authenticate user when widget loaded.
following are my requirement.
" When the widget loads it will attempt to authenticate. It will send a request to the MyAPI with
{
username: username,
token: token
}
MyAPI will POST this information on to the hostAPI. This will return either success or a 401.
On sucess, we log the user in. We may need to create an account if an user with that name does not exist"
how can i auth a user with only username and a token key
Is not a good practice to login user by user interface.
But it is an option and maybe in your case you can use that.
So you know only the username, and token.
I think you can query the database based on you username and token . find the user and login the selected one :)
Example:
$user=User::where('username',$username)->where('token',$token)->first();
Auth::login($user);
return Auth::user();
In case you want to create the user if it does not exist:
$user=User::where('username',$username)->where('token',$token)->firstOrCreate(['username' => $username,'token'=>$token]);

How does Laravel/Lumen verifies the authentication of a user through JWT?

I'm new to Laravel and JWT-auth. I've implemented the process of generating JWT tokens and getting the associated user in my back-end, but I'm still can not understand how the server verifies the authentication of a user from just a token stored on the client side.
If I log in on machine A and change my password on machine B, can I still log in from machine A with the previous token?
You have a 'users' table and generally another table like 'sessions'. When a user makes a request to login through your API, a new line into the 'sessions' table is inserted (the token is saved) and the API return the token to the user. For all requests that need authentification, the user will have to give this token (through HTTP header for example).
When you want to authentificate a user on a request you have to verify if the token exists and remains valid and then retrieve the user. Example in Lumen :
$this->app['auth']->viaRequest('api', function ($request) {
$session = Session::where(['token' => $request->header('token')])->get(); //user gives his token in the header request
if($session){
return $session->user(); //you have setup the hasOne/hasMany relationship between sessions and users
//the user is authenticated
}
return null;
// the user is not authenticated
});
"If I log in on machine A and change my password on machine B, can I still log in from machine A with the previous token?"
If the token is still valid and you allow multiple active sessions then yes. The token isn't set depending of the password.

Laravel 5 - Manually logging in a user without password

I want to login users after authenticating them using OAuth and Google account without entering any password.
I know Auth::login functon can do such action but I don't know how to get the user instance while they haven't been authenticated yet.
Is there a way to do that?
You can 'manually' log a user in in two diefferent ways:
// log user in by ID
Auth::loginUsingId([id of user]);
Or
$user = User::find([id here]);
// or maybe
$user = User::whereUsername([username here])->first();
// and then
Auth::login($user);
See the documentation for authentication.

Resources