Laravel 5 reset password for a logged in user - laravel

I want to use laravel's reset password functionality to reset password for a logged in user (I'll use that instead of enabling users to change their password).
My problem is, when I redirect to the password reset route (/password/email/) and the user is logged in, they will be automatically redirected to the home logged in screen.
My first try then.. was to implement a method at the User model called sendResetPasswordLink. But, as I looked more into the platform I would need to generate the token and add to the password_resets table..
I looked into DatabaseTokenRepository and PasswordResetServiceProvider classes, looking for a function I could call to generate the token, but there is no function I could call statically..
I'm really lost, can someone point me the way?

From the ResetsPasswords trait, the answer is:
Password::sendResetLink(['email' => Auth::user()->email], function (Illuminate\Mail\Message $message) {
$message->subject('Your Password Reset Link');
});
You'll need to create your own route and controller method that allows this to be called for logged-in users.

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);

Is there a way I can access authenticated user information in an API route in Laravel?

I have a callback URL(mywebsite.com/final/results), which is a POST route, like:
Route::post('final/results','FinalResultsController#someMethod')
On this route, I am waiting for data that comes like
{"trx_id":"12","session":2,"method":"do","retry":true,"minus":20,"sign":"rthrtghert", "plus":0}
When the data comes, it is handled by the someMethod on FinalResultsController Now I need to get the logged-in information so that I can be able to update the user with the information. The problem is however that when I try to get the authenticated user through auth('api')->user(). it returns null. Is there any other way I can get the logged-in user information from the API route?
My project's Laravel version is 6.
instead of this use Auth::user() which will return current authenticated user data
in your someMethod(){ $user=Auth::user(); }
here is your $user you can do whatever you want with $user or as you said update the information like
$user=User::find(Auth::id())
$user->name=$request->name;
$user->update();
You can get user object using
Auth()::user()

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 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.

How to implement one controller mapping method for different scenarios

I have a spring controller method which could be called in different scenarios. here is the example...
#RequestMapping("/resetpassword")
public ModelAndView resetpassword( #Valid #ModelAttribute("resetpasswordForm") ResetPawdFormForm resetPawdFormForm, ModelAndView modelAndView){
... this method could be executed in 3 different scenarios....
using the hyper link coming from the user reset password link sent to user email..
eg: localhost/myApp/login/resetpassword//
Here I can authenticate userID and activationSecretCode in DB and let user reset password
user can click on resetpassword link from user settings page.
eg: Since the user is already coming from user settings page, I can validate userSession and allow him to reset password
User can login for first time successfully, but are forced to reset password due to admin requirements for reset initial default password.
eg: in this user neither have session, nor passing any activationcode to validate.
login method validates userid/default password and redirects to resetpassword mapping(method=GET).
How can the system authenticate the user request and allow him to reset password?
One alternative for this is, to use flash attributes and set a authenticationKey as flash attributes...which could be verified in resetpassword method.
is there other way to implement this....
Note: I posted an issue in implementing this approach in
Post: Spring: How to pass Java objects during redirect while using ModelAttribute
Any help?
I think the best way to implement this is using three different action methods:
resetPassword (e-mails)
resetLoggedUserPassword (via settings)
changeDefaultPassword
They may even share the same view, but the behaviors are not equal, so I would avoid overloading the action responsibility.
EDIT: elaborating on your comment:
1) To secure the e-mail link, one way is to add a authentication token. The token can be as weak as a hashed user id plus some salt string, or as strong as a GUID with expiration time in a database table, generated whenever a user requests a password reset.
2) The settings way is not a problem, considering that the user is already logged in.
3) The temporary password action can be secured the same way as 1, or the same way as 2, if you put the user on the session. Logging in the user even with the default password status shouldn't be a concern if the code that verify the status of the account are inside a request filter.

Resources