2FAuth/app/Http/Controllers/Auth/UserController.php

75 lines
2.5 KiB
PHP
Raw Normal View History

<?php
2022-03-15 14:47:07 +01:00
namespace App\Http\Controllers\Auth;
use App\Api\v1\Resources\UserResource;
use App\Http\Controllers\Controller;
2022-11-22 15:15:52 +01:00
use App\Http\Requests\UserDeleteRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
2022-11-22 15:15:52 +01:00
use Illuminate\Support\Facades\Hash;
2022-10-18 17:34:56 +02:00
use Illuminate\Support\Facades\Log;
class UserController extends Controller
2022-11-22 15:15:52 +01:00
{
/**
* Update the user's profile information.
*
* @return \App\Api\v1\Resources\UserResource|\Illuminate\Http\JsonResponse
*/
public function update(UserUpdateRequest $request)
{
2022-11-22 15:15:52 +01:00
$user = $request->user();
$validated = $request->validated();
$this->authorize('update', $user);
if (config('auth.defaults.guard') === 'reverse-proxy-guard' || $user->oauth_provider) {
Log::notice('Account update rejected: reverse-proxy-guard enabled or account from external sso provider');
return response()->json(['message' => __('errors.account_managed_by_external_provider')], 400);
}
2022-11-22 15:15:52 +01:00
if (! Hash::check($request->password, Auth::user()->password)) {
2022-10-18 17:34:56 +02:00
Log::notice('Account update failed: wrong password provided');
2022-11-22 15:15:52 +01:00
return response()->json(['message' => __('errors.wrong_current_password')], 400);
}
2022-11-22 15:15:52 +01:00
if (! config('2fauth.config.isDemoApp')) {
$user->update([
2022-11-22 15:15:52 +01:00
'name' => $validated['name'],
'email' => $validated['email'],
]);
2022-10-18 17:34:56 +02:00
}
2023-02-27 00:33:42 +01:00
Log::info(sprintf('Account of user ID #%s updated', $user->id));
return new UserResource($user);
}
/**
* Delete the user's account.
*
* @return \Illuminate\Http\JsonResponse
*/
public function delete(UserDeleteRequest $request)
{
$validated = $request->validated();
2023-03-10 22:59:46 +01:00
$user = Auth::user();
2022-11-22 15:15:52 +01:00
if (! Hash::check($validated['password'], Auth::user()->password)) {
return response()->json(['message' => __('errors.wrong_current_password')], 400);
}
// This will delete the user and all its 2FAs & Groups thanks to the onCascadeDelete constrains.
// Deletion will not be done (and returns False) if the user is the only existing admin (see UserObserver clas)
return $user->delete() === false
? response()->json([
'message' => __('errors.cannot_delete_the_only_admin'),
], 400)
: response()->json(null, 204);
}
2022-11-22 15:15:52 +01:00
}