Laravel - Deleting auth user account while user is logged in - laravel

I'm trying to build a function where a user can delete their own account while they are logged in. I'm struggling to find any example or logic/best practices.
The controller looks like this:
public function postDestroy() {
$user = User::find(Auth::user()->id);
$user = DB::delete('delete from users')->user(id);
return Redirect::route('site-home')->with('global', 'Your account has been deleted!');
}
I'm trying to grab the current Auth (logged in) user and use their id to delete them from the database. Then send them to the home page with a message.
Also, do I need to make sure the session is properly closed during this process, such as Auth::logout(); ?
I'm pretty new to Laravel, so any help would be appreciated.

Not sure how your routing looks like, but this should do the job.
$user = \User::find(Auth::user()->id);
Auth::logout();
if ($user->delete()) {
return Redirect::route('site-home')->with('global', 'Your account has been deleted!');
}
You should logout user before delete.

You merely gotta do like this:
$user=auth()->user();
$user->delete();

Related

Laravel 7 loginUsingId not persisting / causing log out

I am trying to create a "Shadow" user feature, it's basically just to allow admins to log in as another user to use the system as the "shadowed user" would.
I've used Auth::loginUsingId before but i can't figure out why the below isn't working.
public function shadowUser($id, Request $request){
$user = User::query()->find($id);
$previousUserId = $request->user()->id;
Session()->flush();
Session()->put('shadow.user.id', $previousUserId);
$shadowedUser = Auth::loginUsingId($user->id);
dump(Auth::check());
return redirect()->route('home');
}
If I dump out the $shadowedUser it shows the correct user and the Auth::check() returns true.
I have also tried these but they made no difference: Auth::loginUsingId(1, true);, Auth::guard($guard)->loginUsingId($user->ID); and Auth::login($user, true);
There's no crazy middleware just laravel's defaults.
I've tried a few things like removing the session flush but it always just logs me out.
I found that Laravel sessions are a bit funky in this scenario, it looks like you're trying to log someone in when the session is already active, log the current user out, flush the session then log in the new user, this way it will tell Laravel that this is a new user signing in and reset the session.
In your script, once you've logged the user out, flushed the session and logged the new user in, add the previous users id to the new session otherwise it will get deleted then you'll be able to see the previous user who was logged in, or the person shadowing you in this case.
public function shadowUser($id, Request $request){
$user = User::query()->find($id);
$previousUserId = $request->user()->id;
Auth::logout($guard);
Session()->flush();
Auth::loginUsingId($user->id);
Session()->put('shadow.user.id', $previousUserId);
dump(Auth::check());
return redirect()->route('home');
}

Changed to CPF instead of email on login page. Now what?

CPF is a Brazilian code like US Social Secure Number.
I´ve changed my login page to it and it is working fine. The trick now is the following:
Clients and employers will use the same login page with different roles. So far, so good.
The matter is that employers are on the database and clients I need to search via WS, a task that I am already doing ok.
So I need to check if the login user is an employer and send him to his home, or if he is a client, how do I send him to the SoapController to make the call to the WS? I can´t figure where is the "query" to the 'users' table.
In time: A client for me, is a user with a different role, so I put them all on the same data table.
Any hints, please?
OK, I found the solution:
At the LoginController I wrote a new login function that had subscribed Laravel´s original login.
Let´s see some code:
public function username()
{
return 'cpfCnpj';
}
public function login(Request $request)
{
$credentials = $this->credentials($request);
$login = $credentials[$this->username()];
if (User::where($this->username(), $login)->count() > 0) {
return 'Login exists';
} else {
return 'vai pro SoapController';
}
}
Now I can check on another database and then do whatever I need with the answer.
Hope this can help who needs!

How can I add ask username and password feature to only one of my laravel routes?

I have created a few forms in laravel. I want to restrict access to one of them only to a specific user.
I want to create a user and password myself.
This is my routes excerpt. This is the route I want to protect from access
Route::get('/tabledata_id_title', 'KedivimController#appearanceiddata');
This is my controller excerpt:
public function appearanceiddata()
{
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
This is a short fix for your problem.
public function appearanceiddata()
{
if (!Auth::guard('web')->check()) //check if someone is logged in
{
//redirect to login page.
}
else {
/*Check if the logged in user is your desired user.
Maybe try matching the logged in id with your desired id.
If you find that a user is logged in but they are not your desired user
then you may redirect them in some other place or show them a message. */
}
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
However, this practice is ok if you have one or two restricted field. But if you have more than that then you should read about middleware.

How can I logout user after delete with Laravel?

What is the correct way to logout user after I delete his data in Laravel? I would not like to delete him before, in case of delete process goes with errors.
When I am having this code:
if($this->userManipulator->softDeleteUser(Auth::user())){
Auth::logout();
return redirect(url('login'));
}
it works fine in the app, but does not work correctly during testing.
As I mentioned in the comments, you must log the user out of your application first since once deleted Eloquent won't be able to locate/logout the user.
Below is a solution that addresses your concern about what to do if the delete fails. It might need adjustment depending on how you have things setup, but this concept will work:
// Get the user
$user = Auth::user();
// Log the user out
Auth::logout();
// Delete the user (note that softDeleteUser() should return a boolean for below)
$deleted = $this->userManipulator->softDeleteUser($user);
if ($deleted) {
// User was deleted successfully, redirect to login
return redirect(url('login'));
} else {
// User was NOT deleted successfully, so log them back into your application! Could also use: Auth::loginUsingId($user->id);
Auth::login($user);
// Redirect them back with some data letting them know it failed (or handle however you need depending on your setup)
return back()->with('status', 'Failed to delete your profile');
}
This is not possible, Auth won't be able to located them because Eloquent treats them as deleted.
Solution: You should logout user before delete.
$user = \User::find(Auth::user()->id);
Auth::logout();
if ($user->delete()) {
return Redirect::route('home');
}

How to us actingAs() with Sentinel

I am testing a Laravel 5.1 page that requires the user to be logged in. My project uses the Cartalyst/Sentinel packing for authentication.
I tried this but I doesn't recognize that the user is logged in.
public function testPageWithLogin()
{
$user = Sentinel::findById(2);
$this->actingAs($user)
->withSession([])
->visit('/page')
->dontSee('Whoops')
->dontSee('login');
}
What can I do so that the user will be seen as logged in?
I forgot to log the user in using the Sentinel::login method. The user was legit just not seen as logged in.
This is the way it should have been done.
public function testPageWithLogin()
{
$user = Sentinel::findById(2);
Sentinel::login($user);
$this->actingAs($user)
->withSession([])
->visit('/page')
->dontSee('Whoops')
->dontSee('login');
}

Resources