How do I manually send a password reset request in Laravel 5.4? - laravel

I would like to manually send a password reset request to a specific user (not the one currently logged in) from within a controller. I did some digging around in the Laravel code and it seems like I should be calling postEmail(Request $request) in ResetsPasswords, but I can't seem to figure out how to get access to the right PasswordController instance to call it.

Seems like you are admin, so from your end, you can set a column in database (is_active), and change that to 0, and check when user logged in if is_active == 0. If it's 0, allow him to set a new password, then make a hash of new password and change is_active to 1

Related

Retain session when login in with Laravel Socialite in google or reset id with previous one

I currently have a Laravel app that signs in using Socialite.
public function redirectToGoogle(Request $request)
{
return Socialite::driver('google')->stateless()->redirect();
}
When it loads and redirects I lose the previous session id.
I need that session id because it's loaded in my db to track some cart info.
Is there away I can retain the previous session id when Socialite loads the google driver?
I can also reset the session id since I have it in my db. However I don't know how to regenerate it with a custom string.
$request->session()->regenerate();
But passing it a custom string?
$request->session()->regenerate('some value');
session()->getId(); //does not regenerate 'some value'
I would setId like so:
session()->setId($myCustomId);
From here

How does Djoser account verification system really works under the hood?

So I'm currently in an attempt to make my own account verification system and I'm using some parts of Djoser as a reference. let me try to walk you to my question
Let's say you're to make a new account in Djoser app
you put in the information of your soon to be made account including email
submit the form to the backend
get an email to the whatever email account you put in earlier to verify your account
click the link in your email
get to the verify account page
now in this page there's a button to submit a UID and a token and both of those information lies in the URL.
My question is:
What are those tokens? is it JWT?
How do they work?
How can I implement that in my own projects without djoser?
The answers to your questions are immersed in the own code of djoser.
You can check djoser.email file and in the classes there, they are few methods get_context_data().
def get_context_data(self):
context = super().get_context_data()
user = context.get("user")
context["uid"] = utils.encode_uid(user.pk)
context["token"] = default_token_generator.make_token(user)
context["url"] = settings.ACTIVATION_URL.format(**context)
return context
So get the context in the class where is instance, and in this context add the 'uid' (this is basically str(pk) and coded in base64, check encode_uid()), the 'token' (just a random string created with a Django function from your Secret key; you can change the algorithm of that function and the duration of this token with PASSWORD_RESET_TIMEOUT setting) to use temporary links, and finally the URL according the action which is performed (in this case the email activation).
Other point to consider is in each of this classes has template assigned and you can override it.
Now, in the views, specifically in UserViewSet and its actions perform_create(), perform_update() and resend_activation(), if the Djoser setting SEND_ACTIVATION_EMAIL is True, call to ActivationEmail to send an email to the user address.
def perform_create(self, serializer):
user = serializer.save()
signals.user_registered.send(
sender=self.__class__, user=user, request=self.request
)
context = {"user": user}
to = [get_user_email(user)]
if settings.SEND_ACTIVATION_EMAIL:
settings.EMAIL.activation(self.request, context).send(to)
...
The email is sent and when a user click the link, whether the token is still valid and uid match (djoser.UidAndTokenSerializer), the action activation() of the same View is executed. Change the user flag 'is_active' to True and it may sent another email to confirm the activation.
If you want code your own version, as you can see, you only have to create a random token, generate some uid to identify the user in the way that you prefer. Code a pair of views that send emails with templates that permit the activation.

Laravel password reset token is different when it is saved in database

I am developing a Laravel application. I am now customising the password reset feature. There is an issue with retrieving the password reset token back from the database because the token string is changed when it is saved in the database from when it is generated.
I explicitly generate the password reset token like this
$token = app('auth.password.broker')->createToken($user)
Then, I tried to retrieve the password reset by using that token like this.
$password_reset = DB::table('password_resets')
->where('token', request('token'))
->first();
I cannot retrieve it. It always return null. Because the token value is different from when it was generated as in the screenshots below.
Why is that happening and how can I fix it?
The token gets hashed before it's stored in the database. It gets hashed in the DatabaseTokenRepository on line 110: 'token' => $this->hasher->make($token).
You won't be able to query by token. You would only be able to check a plain token value against a hashed value with the check method in the HashManager class, for example.
Base on Passport
your code should be something like this
$token = app('auth.password.broker')->createToken($user)->accessToken

Laravel 5.7 Auth::loginUsingId() not working after CSRF token generated

I am trying to auto-login user on step-2 of registration steps. After successful insert into db i am using Auth::loginUsingId($user_id) to auto-login user using ajax.
I am always submitting CSRF token on each steps.
Now the problem is after successful login CSRF token get generated and Auth::user() gets blank on step 3
Also before and after login CSRF is different.
First of all, csrf token is required when using non-GET request, so if in your case using GET request seems reasonable you can use it.
Otherwise, in step 2 you should return new CSRF token for example like this:
Auth::loginUsingId($user_id);
return response()->json(['csrf_token' => csrf_token()];
and then in step 3 use this new token you got from Step 2 response.
You may try this method Auth::User()->id;
You can try Auth::id() to get the current user's id.
If you want all the details about logged in user then you can use Auth::user().
By Auth::user() you can access all details about the user.
You can also log in from the controller by passing user id Auth::login($user_id)
And if you user Auth::loginUsingId() then you have to pass user id and true status for remember the details.
Like :Auth:loginUsingId(user_id, true)
For Example :
Get User's Id : Auth::id()
Get User's Name : Auth::user()->name
Get User's email : Auth::user()->email
etc....
Seems like its not an issue of CSRF at all.
When you create a new user, Like
$user = new App\User;
$user->username = $request->username;
...
...
$user->save();
Auth::loginUsingId($user->id);
Then place dd(Auth::user()->id); to check that user is logged in or not.
Let us know.

Laravel - user login

I use Laravel 5.4 and need to login user in my system. I have next login.blade.php
where i have email and password field. In my controller I have next
protected function log() {
$email=Input::get('email');
$pass=Input::get('password');
$user = DB::select("SELECT * FROM users where email = '".$email."' and password = '".$pass."'");
foreach($user as $users){
if(Input::get('email') == $users->email){
return redirect('/');
}else{
return view('site.warning');
}
}
}
How can I return logged user in my redirect('/') and show them in my site.
Any idea?
Use the attempt() method:
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
From the docs:
The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array.
This method will work for you if you're using bcrypt() or Hash::make() to generate password hash.
Please do not create your own login system!
Now that's out of the way the explanation.
There is (almost) no good reason to create your own login system, as your code already showed. Your current code is very VERY insecure due to storing passwords in plain text. Please read up on resent security advice.
The even better option is using Laravels build-in auth.
https://laravel.com/docs/5.4/authentication
If you do try to use this build-in authentication methods you will be able to get the current authenticated user by using Auth::user() this can be used in your blade files as well as in your controllers.
You cannot (maybe you can) but you certainly should't store user's password unhashed. Laravel has build artisan command: php artisan make:auth. You may use it, and retrieve him in the show method for example (thro the URL, passing id). Or just retrieve him via Auth::user(). Planty of choices.

Resources