diff --git a/app/Api/v1/Controllers/GroupController.php b/app/Api/v1/Controllers/GroupController.php index 1298fc5f..f9bb596f 100644 --- a/app/Api/v1/Controllers/GroupController.php +++ b/app/Api/v1/Controllers/GroupController.php @@ -2,18 +2,16 @@ namespace App\Api\v1\Controllers; -use App\Models\Group; -use App\Facades\Groups; -use App\Api\v1\Requests\GroupStoreRequest; use App\Api\v1\Requests\GroupAssignRequest; +use App\Api\v1\Requests\GroupStoreRequest; use App\Api\v1\Resources\GroupResource; use App\Api\v1\Resources\TwoFAccountCollection; +use App\Facades\Groups; use App\Http\Controllers\Controller; -use Illuminate\Support\Facades\App; +use App\Models\Group; class GroupController extends Controller { - /** * Display a listing of the resource. * @@ -26,7 +24,6 @@ class GroupController extends Controller return GroupResource::collection($groups); } - /** * Store a newly created resource in storage. * @@ -44,7 +41,6 @@ class GroupController extends Controller ->setStatusCode(201); } - /** * Display the specified resource. * @@ -56,12 +52,11 @@ class GroupController extends Controller return new GroupResource($group); } - /** * Update the specified resource in storage. * * @param \App\Api\v1\Requests\GroupStoreRequest $request - * @param \App\Models\Group $group + * @param \App\Models\Group $group * @return \App\Api\v1\Resources\GroupResource */ public function update(GroupStoreRequest $request, Group $group) @@ -71,10 +66,8 @@ class GroupController extends Controller Groups::update($group, $validated); return new GroupResource($group); - } - /** * Associate the specified accounts with the group * @@ -87,12 +80,10 @@ class GroupController extends Controller $validated = $request->validated(); Groups::assign($validated['ids'], $group); - + return new GroupResource($group); - } - /** * Get accounts assign to the group * @@ -102,12 +93,10 @@ class GroupController extends Controller public function accounts(Group $group) { $twofaccounts = Groups::getAccounts($group); - + return new TwoFAccountCollection($twofaccounts); - } - /** * Remove the specified resource from storage. * @@ -120,5 +109,4 @@ class GroupController extends Controller return response()->json(null, 204); } - } diff --git a/app/Api/v1/Controllers/IconController.php b/app/Api/v1/Controllers/IconController.php index e3f06e82..579345a7 100644 --- a/app/Api/v1/Controllers/IconController.php +++ b/app/Api/v1/Controllers/IconController.php @@ -2,12 +2,11 @@ namespace App\Api\v1\Controllers; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Storage; use App\Http\Controllers\Controller; use App\Services\LogoService; +use Illuminate\Http\Request; use Illuminate\Support\Facades\App; - +use Illuminate\Support\Facades\Storage; class IconController extends Controller { @@ -31,7 +30,6 @@ class IconController extends Controller : response()->json(['message' => __('errors.file_upload_failed')], 500); } - /** * Fetch a logo * @@ -43,26 +41,25 @@ class IconController extends Controller $this->validate($request, [ 'service' => 'string|regex:/^[^:]+$/i', ]); - + $logoService = App::make(LogoService::class); - $icon = $logoService->getIcon($request->service); + $icon = $logoService->getIcon($request->service); return $icon ? response()->json(['filename' => $icon], 201) : response()->json(null, 204); } - /** * delete an icon * - * @param string $icon + * @param string $icon * @return \Illuminate\Http\JsonResponse */ public function delete(string $icon) { - Storage::disk('icons')->delete($icon); + Storage::disk('icons')->delete($icon); return response()->json(null, 204); } -} \ No newline at end of file +} diff --git a/app/Api/v1/Controllers/QrCodeController.php b/app/Api/v1/Controllers/QrCodeController.php index 68822e7b..aaecf011 100644 --- a/app/Api/v1/Controllers/QrCodeController.php +++ b/app/Api/v1/Controllers/QrCodeController.php @@ -2,15 +2,13 @@ namespace App\Api\v1\Controllers; -use App\Models\TwoFAccount; -use App\Facades\QrCode; use App\Api\v1\Requests\QrCodeDecodeRequest; +use App\Facades\QrCode; use App\Http\Controllers\Controller; - +use App\Models\TwoFAccount; class QrCodeController extends Controller { - /** * Show a QR code image * @@ -24,7 +22,6 @@ class QrCodeController extends Controller return response()->json(['qrcode' => QrCode::encode($uri)], 200); } - /** * Decode an uploaded QR Code image * @@ -39,5 +36,4 @@ class QrCodeController extends Controller ? response()->json(['data' => QrCode::decode($file)], 200) : response()->json(['message' => __('errors.file_upload_failed')], 500); } - -} \ No newline at end of file +} diff --git a/app/Api/v1/Controllers/SettingController.php b/app/Api/v1/Controllers/SettingController.php index 02f4e035..55d821c5 100644 --- a/app/Api/v1/Controllers/SettingController.php +++ b/app/Api/v1/Controllers/SettingController.php @@ -2,38 +2,36 @@ namespace App\Api\v1\Controllers; -use App\Facades\Settings; use App\Api\v1\Requests\SettingStoreRequest; use App\Api\v1\Requests\SettingUpdateRequest; +use App\Facades\Settings; use App\Http\Controllers\Controller; - class SettingController extends Controller { /** * List all settings - * + * * @return \Illuminate\Http\JsonResponse */ public function index() { - $settings = Settings::all(); + $settings = Settings::all(); $settingsResources = collect([]); $settings->each(function (mixed $item, string $key) use ($settingsResources) { $settingsResources->push([ - 'key' => $key, - 'value' => $item + 'key' => $key, + 'value' => $item, ]); }); return response()->json($settingsResources->all(), 200); } - /** * Display a setting * - * @param string $settingName + * @param string $settingName * @return \Illuminate\Http\JsonResponse */ public function show($settingName) @@ -45,16 +43,15 @@ class SettingController extends Controller } return response()->json([ - 'key' => $settingName, - 'value' => $setting + 'key' => $settingName, + 'value' => $setting, ], 200); } - /** * Store a setting - * - * @param \App\Api\v1\Requests\SettingStoreRequest $request + * + * @param \App\Api\v1\Requests\SettingStoreRequest $request * @return \Illuminate\Http\JsonResponse */ public function store(SettingStoreRequest $request) @@ -64,16 +61,15 @@ class SettingController extends Controller Settings::set($validated['key'], $validated['value']); return response()->json([ - 'key' => $validated['key'], - 'value' => $validated['value'] + 'key' => $validated['key'], + 'value' => $validated['value'], ], 201); } - /** * Update a setting - * - * @param \App\Api\v1\Requests\SettingUpdateRequest $request + * + * @param \App\Api\v1\Requests\SettingUpdateRequest $request * @return \Illuminate\Http\JsonResponse */ public function update(SettingUpdateRequest $request, string $settingName) @@ -83,17 +79,15 @@ class SettingController extends Controller Settings::set($settingName, $validated['value']); return response()->json([ - 'key' => $settingName, - 'value' => $validated['value'] + 'key' => $settingName, + 'value' => $validated['value'], ], 200); - } - /** * Delete a setting - * - * @param string $settingName + * + * @param string $settingName * @return \Illuminate\Http\JsonResponse */ public function destroy(string $settingName) @@ -105,16 +99,15 @@ class SettingController extends Controller } $optionsConfig = config('2fauth.options'); - if(array_key_exists($settingName, $optionsConfig)) { + if (array_key_exists($settingName, $optionsConfig)) { return response()->json( - ['message' => 'bad request', - 'reason' => [__('errors.delete_user_setting_only')] - ], 400); + ['message' => 'bad request', + 'reason' => [__('errors.delete_user_setting_only')], + ], 400); } Settings::delete($settingName); return response()->json(null, 204); } - } diff --git a/app/Api/v1/Controllers/TwoFAccountController.php b/app/Api/v1/Controllers/TwoFAccountController.php index c4db9fec..b1c2de16 100644 --- a/app/Api/v1/Controllers/TwoFAccountController.php +++ b/app/Api/v1/Controllers/TwoFAccountController.php @@ -2,26 +2,25 @@ namespace App\Api\v1\Controllers; -use App\Models\TwoFAccount; +use App\Api\v1\Requests\TwoFAccountBatchRequest; +use App\Api\v1\Requests\TwoFAccountDynamicRequest; +use App\Api\v1\Requests\TwoFAccountImportRequest; use App\Api\v1\Requests\TwoFAccountReorderRequest; use App\Api\v1\Requests\TwoFAccountStoreRequest; use App\Api\v1\Requests\TwoFAccountUpdateRequest; -use App\Api\v1\Requests\TwoFAccountImportRequest; -use App\Api\v1\Requests\TwoFAccountBatchRequest; use App\Api\v1\Requests\TwoFAccountUriRequest; -use App\Api\v1\Requests\TwoFAccountDynamicRequest; use App\Api\v1\Resources\TwoFAccountCollection; use App\Api\v1\Resources\TwoFAccountReadResource; use App\Api\v1\Resources\TwoFAccountStoreResource; use App\Facades\Groups; use App\Facades\TwoFAccounts; -use Illuminate\Support\Arr; -use Illuminate\Http\Request; use App\Http\Controllers\Controller; +use App\Models\TwoFAccount; +use Illuminate\Http\Request; +use Illuminate\Support\Arr; class TwoFAccountController extends Controller { - /** * List all resources * @@ -32,12 +31,10 @@ class TwoFAccountController extends Controller return new TwoFAccountCollection(TwoFAccount::ordered()->get()); } - /** * Display a 2FA account * * @param \App\Models\TwoFAccount $twofaccount - * * @return \App\Api\v1\Resources\TwoFAccountReadResource */ public function show(TwoFAccount $twofaccount) @@ -45,7 +42,6 @@ class TwoFAccountController extends Controller return new TwoFAccountReadResource($twofaccount); } - /** * Store a new 2FA account * @@ -60,13 +56,12 @@ class TwoFAccountController extends Controller // - The advanced form has been used and all individual parameters // -> We use the parameters array to define the account - $validated = $request->validated(); + $validated = $request->validated(); $twofaccount = new TwoFAccount; if (Arr::has($validated, 'uri')) { $twofaccount->fillWithURI($validated['uri'], Arr::get($validated, 'custom_otp') === TwoFAccount::STEAM_TOTP); - } - else { + } else { $twofaccount->fillWithOtpParameters($validated); } $twofaccount->save(); @@ -79,8 +74,6 @@ class TwoFAccountController extends Controller ->setStatusCode(201); } - - /** * Update a 2FA account * @@ -98,10 +91,8 @@ class TwoFAccountController extends Controller return (new TwoFAccountReadResource($twofaccount)) ->response() ->setStatusCode(200); - } - /** * Convert a migration resource to a valid TwoFAccounts collection * @@ -114,17 +105,15 @@ class TwoFAccountController extends Controller if (Arr::has($validated, 'file')) { $migrationResource = $request->file('file'); - + return $migrationResource instanceof \Illuminate\Http\UploadedFile ? new TwoFAccountCollection(TwoFAccounts::migrate($migrationResource->get())) : response()->json(['message' => __('errors.file_upload_failed')], 500); - } - else { + } else { return new TwoFAccountCollection(TwoFAccounts::migrate($request->payload)); } } - /** * Save 2FA accounts order * @@ -140,10 +129,9 @@ class TwoFAccountController extends Controller return response()->json(['message' => 'order saved'], 200); } - /** * Preview account using an uri, without any db moves - * + * * @param \App\Api\v1\Requests\TwoFAccountUriRequest $request * @return \App\Api\v1\Resources\TwoFAccountStoreResource */ @@ -155,12 +143,11 @@ class TwoFAccountController extends Controller return new TwoFAccountStoreResource($twofaccount); } - /** * Get a One-Time Password * * @param \Illuminate\Http\Request $request - * @param string|null $id + * @param string|null $id * @return \Illuminate\Http\JsonResponse */ public function otp(Request $request, $id = null) @@ -173,17 +160,16 @@ class TwoFAccountController extends Controller } // The request input is an uri - else if ( $request->has('uri') ) { + elseif ($request->has('uri')) { // return 404 if uri is provided with any parameter other than otp_type if ((count($inputs) == 2 && $request->missing('custom_otp')) || count($inputs) > 2) { return response()->json([ 'message' => 'bad request', - 'reason' => ['uri' => __('validation.onlyCustomOtpWithUri')] + 'reason' => ['uri' => __('validation.onlyCustomOtpWithUri')], ], 400); - } - else { + } else { $validatedData = $request->validate((new TwoFAccountUriRequest)->rules()); - $twofaccount = new TwoFAccount; + $twofaccount = new TwoFAccount; $twofaccount->fillWithURI($validatedData['uri'], Arr::get($validatedData, 'custom_otp') === TwoFAccount::STEAM_TOTP, true); } } @@ -191,14 +177,13 @@ class TwoFAccountController extends Controller // The request inputs should define an account else { $validatedData = $request->validate((new TwoFAccountStoreRequest)->rules()); - $twofaccount = new TwoFAccount(); + $twofaccount = new TwoFAccount(); $twofaccount->fillWithOtpParameters($validatedData, true); } return response()->json($twofaccount->getOTP(), 200); } - /** * A simple and light method to get the account count. * @@ -207,33 +192,30 @@ class TwoFAccountController extends Controller */ public function count(Request $request) { - return response()->json([ 'count' => TwoFAccount::count() ], 200); + return response()->json(['count' => TwoFAccount::count()], 200); } - /** - * * Withdraw one or more accounts from their group - * - * @param \App\Api\v1\Requests\TwoFAccountBatchRequest $request + * + * @param \App\Api\v1\Requests\TwoFAccountBatchRequest $request * @return \Illuminate\Http\JsonResponse */ public function withdraw(TwoFAccountBatchRequest $request) - { + { $validated = $request->validated(); - + if ($this->tooManyIds($validated['ids'])) { return response()->json([ 'message' => 'bad request', - 'reason' => [__('errors.too_many_ids')] + 'reason' => [__('errors.too_many_ids')], ], 400); } TwoFAccounts::withdraw($validated['ids']); - - return response()->json([ 'message' => 'accounts withdrawn' ], 200); - } + return response()->json(['message' => 'accounts withdrawn'], 200); + } /** * Remove the specified resource from storage. @@ -248,7 +230,6 @@ class TwoFAccountController extends Controller return response()->json(null, 204); } - /** * Remove the specified resources from storage. * @@ -262,7 +243,7 @@ class TwoFAccountController extends Controller if ($this->tooManyIds($validated['ids'])) { return response()->json([ 'message' => 'bad request', - 'reason' => [__('errors.too_many_ids')] + 'reason' => [__('errors.too_many_ids')], ], 400); } @@ -271,19 +252,17 @@ class TwoFAccountController extends Controller return response()->json(null, 204); } - /** * Checks ids length - * - * @param string $ids comma-separated ids + * + * @param string $ids comma-separated ids * @return bool whether or not the number of ids is acceptable */ private function tooManyIds(string $ids) : bool { $arIds = explode(',', $ids, 100); - $nb = count($arIds); + $nb = count($arIds); return $nb > 99 ? true : false; } - } diff --git a/app/Api/v1/Controllers/UserController.php b/app/Api/v1/Controllers/UserController.php index b73dbcb3..f4b1d451 100644 --- a/app/Api/v1/Controllers/UserController.php +++ b/app/Api/v1/Controllers/UserController.php @@ -2,16 +2,16 @@ namespace App\Api\v1\Controllers; -use App\Models\User; use App\Api\v1\Resources\UserResource; use App\Http\Controllers\Controller; +use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { /** * Get detailed information about a user - * + * * @return \App\Api\v1\Resources\UserResource|\Illuminate\Http\JsonResponse */ public function show(Request $request) @@ -24,6 +24,5 @@ class UserController extends Controller return $user ? new UserResource($user) : response()->json(['name' => null], 200); - } -} \ No newline at end of file +} diff --git a/app/Api/v1/Requests/GroupAssignRequest.php b/app/Api/v1/Requests/GroupAssignRequest.php index 08f1ea06..316368ce 100644 --- a/app/Api/v1/Requests/GroupAssignRequest.php +++ b/app/Api/v1/Requests/GroupAssignRequest.php @@ -25,8 +25,8 @@ class GroupAssignRequest extends FormRequest public function rules() { return [ - 'ids' => 'required|array', - 'ids.*' => 'integer' + 'ids' => 'required|array', + 'ids.*' => 'integer', ]; } } diff --git a/app/Api/v1/Requests/QrCodeDecodeRequest.php b/app/Api/v1/Requests/QrCodeDecodeRequest.php index b2f3f543..e2cb6591 100644 --- a/app/Api/v1/Requests/QrCodeDecodeRequest.php +++ b/app/Api/v1/Requests/QrCodeDecodeRequest.php @@ -28,4 +28,4 @@ class QrCodeDecodeRequest extends FormRequest 'qrcode' => 'required|image', ]; } -} \ No newline at end of file +} diff --git a/app/Api/v1/Requests/SettingStoreRequest.php b/app/Api/v1/Requests/SettingStoreRequest.php index 955e63cf..f4cf10fa 100644 --- a/app/Api/v1/Requests/SettingStoreRequest.php +++ b/app/Api/v1/Requests/SettingStoreRequest.php @@ -25,7 +25,7 @@ class SettingStoreRequest extends FormRequest public function rules() { return [ - 'key' => 'required|alpha|max:128|unique:options,key', + 'key' => 'required|alpha|max:128|unique:options,key', 'value' => 'required', ]; } diff --git a/app/Api/v1/Requests/TwoFAccountBatchRequest.php b/app/Api/v1/Requests/TwoFAccountBatchRequest.php index 91ae6316..669db68d 100644 --- a/app/Api/v1/Requests/TwoFAccountBatchRequest.php +++ b/app/Api/v1/Requests/TwoFAccountBatchRequest.php @@ -28,4 +28,4 @@ class TwoFAccountBatchRequest extends FormRequest 'ids' => 'required|string|regex:/^\d+(,{1}\d+)*$/i', ]; } -} \ No newline at end of file +} diff --git a/app/Api/v1/Requests/TwoFAccountDynamicRequest.php b/app/Api/v1/Requests/TwoFAccountDynamicRequest.php index 1fb5ac9c..daba1eb2 100644 --- a/app/Api/v1/Requests/TwoFAccountDynamicRequest.php +++ b/app/Api/v1/Requests/TwoFAccountDynamicRequest.php @@ -2,27 +2,27 @@ namespace App\Api\v1\Requests; -use Illuminate\Support\Arr; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\Auth; class TwoFAccountDynamicRequest extends FormRequest { /** - * Determine if the user is authorized to make this request. - * - * @return bool - */ + * Determine if the user is authorized to make this request. + * + * @return bool + */ public function authorize() { return Auth::check(); } - + /** - * Get the validation rules that apply to the request. - * - * @return array - */ + * Get the validation rules that apply to the request. + * + * @return array + */ public function rules() { $rules = Arr::has($this->validationData(), 'uri') @@ -32,7 +32,6 @@ class TwoFAccountDynamicRequest extends FormRequest return $rules; } - /** * Prepare the data for validation. * @@ -41,8 +40,8 @@ class TwoFAccountDynamicRequest extends FormRequest protected function prepareForValidation() { $this->merge([ - 'otp_type' => strtolower($this->otp_type), + 'otp_type' => strtolower($this->otp_type), 'algorithm' => strtolower($this->algorithm), ]); } -} \ No newline at end of file +} diff --git a/app/Api/v1/Requests/TwoFAccountImportRequest.php b/app/Api/v1/Requests/TwoFAccountImportRequest.php index 924382aa..dcc95fd9 100644 --- a/app/Api/v1/Requests/TwoFAccountImportRequest.php +++ b/app/Api/v1/Requests/TwoFAccountImportRequest.php @@ -26,7 +26,7 @@ class TwoFAccountImportRequest extends FormRequest { return [ 'payload' => 'required_without:file|string', - 'file' => 'required_without:payload|mimes:txt,json,csv', + 'file' => 'required_without:payload|mimes:txt,json,csv', ]; } -} \ No newline at end of file +} diff --git a/app/Api/v1/Requests/TwoFAccountStoreRequest.php b/app/Api/v1/Requests/TwoFAccountStoreRequest.php index 92b59e11..7736a16e 100644 --- a/app/Api/v1/Requests/TwoFAccountStoreRequest.php +++ b/app/Api/v1/Requests/TwoFAccountStoreRequest.php @@ -25,19 +25,18 @@ class TwoFAccountStoreRequest extends FormRequest public function rules() { return [ - 'service' => 'nullable|string|regex:/^[^:]+$/i', - 'account' => 'required|string|regex:/^[^:]+$/i', - 'icon' => 'nullable|string', - 'otp_type' => 'required|string|in:totp,hotp,steamtotp', - 'secret' => ['string', 'bail', new \App\Rules\IsBase32Encoded], - 'digits' => 'nullable|integer|between:5,10', + 'service' => 'nullable|string|regex:/^[^:]+$/i', + 'account' => 'required|string|regex:/^[^:]+$/i', + 'icon' => 'nullable|string', + 'otp_type' => 'required|string|in:totp,hotp,steamtotp', + 'secret' => ['string', 'bail', new \App\Rules\IsBase32Encoded], + 'digits' => 'nullable|integer|between:5,10', 'algorithm' => 'nullable|string|in:sha1,sha256,sha512,md5', - 'period' => 'nullable|integer|min:1', - 'counter' => 'nullable|integer|min:0', + 'period' => 'nullable|integer|min:1', + 'counter' => 'nullable|integer|min:0', ]; } - /** * Prepare the data for validation. * @@ -46,7 +45,7 @@ class TwoFAccountStoreRequest extends FormRequest protected function prepareForValidation() { $this->merge([ - 'otp_type' => strtolower($this->otp_type), + 'otp_type' => strtolower($this->otp_type), 'algorithm' => strtolower($this->algorithm), ]); } diff --git a/app/Api/v1/Requests/TwoFAccountUpdateRequest.php b/app/Api/v1/Requests/TwoFAccountUpdateRequest.php index 6e8109cb..6665c9c2 100644 --- a/app/Api/v1/Requests/TwoFAccountUpdateRequest.php +++ b/app/Api/v1/Requests/TwoFAccountUpdateRequest.php @@ -25,19 +25,18 @@ class TwoFAccountUpdateRequest extends FormRequest public function rules() { return [ - 'service' => 'present|nullable|string|regex:/^[^:]+$/i', - 'account' => 'required|string|regex:/^[^:]+$/i', - 'icon' => 'present|nullable|string', - 'otp_type' => 'required|string|in:totp,hotp,steamtotp', - 'secret' => ['present', 'string', 'bail', new \App\Rules\IsBase32Encoded], - 'digits' => 'present|integer|between:5,10', + 'service' => 'present|nullable|string|regex:/^[^:]+$/i', + 'account' => 'required|string|regex:/^[^:]+$/i', + 'icon' => 'present|nullable|string', + 'otp_type' => 'required|string|in:totp,hotp,steamtotp', + 'secret' => ['present', 'string', 'bail', new \App\Rules\IsBase32Encoded], + 'digits' => 'present|integer|between:5,10', 'algorithm' => 'present|string|in:sha1,sha256,sha512,md5', - 'period' => 'nullable|integer|min:1', - 'counter' => 'nullable|integer|min:0', + 'period' => 'nullable|integer|min:1', + 'counter' => 'nullable|integer|min:0', ]; } - /** * Prepare the data for validation. * @@ -46,7 +45,7 @@ class TwoFAccountUpdateRequest extends FormRequest protected function prepareForValidation() { $this->merge([ - 'otp_type' => strtolower($this->otp_type), + 'otp_type' => strtolower($this->otp_type), 'algorithm' => strtolower($this->algorithm), ]); } diff --git a/app/Api/v1/Requests/TwoFAccountUriRequest.php b/app/Api/v1/Requests/TwoFAccountUriRequest.php index 19b2bcaa..2798f0dd 100644 --- a/app/Api/v1/Requests/TwoFAccountUriRequest.php +++ b/app/Api/v1/Requests/TwoFAccountUriRequest.php @@ -30,7 +30,6 @@ class TwoFAccountUriRequest extends FormRequest ]; } - /** * Prepare the data for validation. * @@ -42,4 +41,4 @@ class TwoFAccountUriRequest extends FormRequest 'custom_otp' => strtolower($this->custom_otp), ]); } -} \ No newline at end of file +} diff --git a/app/Api/v1/Resources/GroupResource.php b/app/Api/v1/Resources/GroupResource.php index c66825fa..c1bbf736 100644 --- a/app/Api/v1/Resources/GroupResource.php +++ b/app/Api/v1/Resources/GroupResource.php @@ -20,9 +20,9 @@ class GroupResource extends JsonResource public function toArray($request) { return [ - 'id' => $this->id, - 'name' => $this->name, - 'twofaccounts_count' => is_null($this->twofaccounts_count) ? 0 : $this->twofaccounts_count, + 'id' => $this->id, + 'name' => $this->name, + 'twofaccounts_count' => is_null($this->twofaccounts_count) ? 0 : $this->twofaccounts_count, ]; } -} \ No newline at end of file +} diff --git a/app/Api/v1/Resources/TwoFAccountCollection.php b/app/Api/v1/Resources/TwoFAccountCollection.php index 5c9a4353..081b6595 100644 --- a/app/Api/v1/Resources/TwoFAccountCollection.php +++ b/app/Api/v1/Resources/TwoFAccountCollection.php @@ -3,7 +3,6 @@ namespace App\Api\v1\Resources; use Illuminate\Http\Resources\Json\ResourceCollection; -use App\Api\v1\Resources\TwoFAccountReadResource; class TwoFAccountCollection extends ResourceCollection { @@ -14,7 +13,6 @@ class TwoFAccountCollection extends ResourceCollection */ public $collects = TwoFAccountReadResource::class; - /** * Transform the resource collection into an array. * @@ -27,10 +25,10 @@ class TwoFAccountCollection extends ResourceCollection // The underlying TwoFAccountReadResource hides the secret only when withSecret == false. // When withSecret is provided the underlying resource will return secret according to the parameter value // If no withSecret is set we force it to false to ensure the secret will not being returned. - if (!$request->has('withSecret')) { + if (! $request->has('withSecret')) { $request->merge(['withSecret' => false]); } return $this->collection; } -} \ No newline at end of file +} diff --git a/app/Api/v1/Resources/TwoFAccountReadResource.php b/app/Api/v1/Resources/TwoFAccountReadResource.php index d50a84a6..51955de2 100644 --- a/app/Api/v1/Resources/TwoFAccountReadResource.php +++ b/app/Api/v1/Resources/TwoFAccountReadResource.php @@ -18,10 +18,10 @@ class TwoFAccountReadResource extends TwoFAccountStoreResource { return array_merge( [ - 'id' => (int) $this->id, - 'group_id' => is_null($this->group_id) ? null : (int) $this->group_id, + 'id' => (int) $this->id, + 'group_id' => is_null($this->group_id) ? null : (int) $this->group_id, ], parent::toArray($request) ); } -} \ No newline at end of file +} diff --git a/app/Api/v1/Resources/TwoFAccountStoreResource.php b/app/Api/v1/Resources/TwoFAccountStoreResource.php index 04608681..94cb55d2 100644 --- a/app/Api/v1/Resources/TwoFAccountStoreResource.php +++ b/app/Api/v1/Resources/TwoFAccountStoreResource.php @@ -26,18 +26,18 @@ class TwoFAccountStoreResource extends JsonResource public function toArray($request) { return [ - 'otp_type' => $this->otp_type, - 'account' => $this->account, - 'service' => $this->service, - 'icon' => $this->icon, - 'secret' => $this->when( - !$request->has('withSecret') || (int) filter_var($request->input('withSecret'), FILTER_VALIDATE_BOOLEAN) == 1, - $this->secret - ), - 'digits' => (int) $this->digits, - 'algorithm' => $this->algorithm, - 'period' => is_null($this->period) ? null : (int)$this->period, - 'counter' => is_null($this->counter) ? null : (int)$this->counter + 'otp_type' => $this->otp_type, + 'account' => $this->account, + 'service' => $this->service, + 'icon' => $this->icon, + 'secret' => $this->when( + ! $request->has('withSecret') || (int) filter_var($request->input('withSecret'), FILTER_VALIDATE_BOOLEAN) == 1, + $this->secret + ), + 'digits' => (int) $this->digits, + 'algorithm' => $this->algorithm, + 'period' => is_null($this->period) ? null : (int) $this->period, + 'counter' => is_null($this->counter) ? null : (int) $this->counter, ]; } -} \ No newline at end of file +} diff --git a/app/Api/v1/Resources/UserResource.php b/app/Api/v1/Resources/UserResource.php index b943ec2a..160ac9ec 100644 --- a/app/Api/v1/Resources/UserResource.php +++ b/app/Api/v1/Resources/UserResource.php @@ -20,9 +20,9 @@ class UserResource extends JsonResource public function toArray($request) { return [ - 'id' => $this->when(!is_null($request->user()), $this->id), + 'id' => $this->when(! is_null($request->user()), $this->id), 'name' => $this->name, - 'email' => $this->when(!is_null($request->user()), $this->email), + 'email' => $this->when(! is_null($request->user()), $this->email), ]; } -} \ No newline at end of file +} diff --git a/app/Console/Commands/CheckDbConnection.php b/app/Console/Commands/CheckDbConnection.php index 81829dc6..835b88c9 100644 --- a/app/Console/Commands/CheckDbConnection.php +++ b/app/Console/Commands/CheckDbConnection.php @@ -4,7 +4,6 @@ namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Storage; class CheckDbConnection extends Command { @@ -44,9 +43,10 @@ class CheckDbConnection extends Command try { DB::connection()->getPDO(); $this->line(DB::connection()->getDatabaseName()); + return 1; } catch (\Exception $e) { return 0; } } -} \ No newline at end of file +} diff --git a/app/Console/Commands/Maintenance/FixUnsplittedAccounts.php b/app/Console/Commands/Maintenance/FixUnsplittedAccounts.php index ebbc87d8..359fbf04 100644 --- a/app/Console/Commands/Maintenance/FixUnsplittedAccounts.php +++ b/app/Console/Commands/Maintenance/FixUnsplittedAccounts.php @@ -42,12 +42,13 @@ class FixUnsplittedAccounts extends Command */ public function handle() { - - if (!Schema::hasColumn('twofaccounts', 'legacy_uri')) { + if (! Schema::hasColumn('twofaccounts', 'legacy_uri')) { $this->comment('2fauth:fix-unsplitted-accounts is useful only after SplitTwofaccountsUriInMultipleColumns migration ran'); + return; + } else { + $this->line('Fetching accounts...'); } - else $this->line('Fetching accounts...'); $twofaccounts = TwoFAccount::where('otp_type', '') ->where('secret', '') @@ -61,24 +62,23 @@ class FixUnsplittedAccounts extends Command if ($twofaccounts->count() == 0) { $this->info('Nothing to fix'); + return; } $this->line('Try to fix them...'); - + foreach ($twofaccounts as $twofaccount) { if ($twofaccount->legacy_uri === __('errors.indecipherable')) { $this->error(sprintf('Account #%d cannot be deciphered', $twofaccount->id)); - } - else { + } else { try { // Get a consistent account $twofaccount->fillWithURI($twofaccount->legacy_uri, false, true); $twofaccount->save(); $this->info(sprintf('Account #%d fixed', $twofaccount->id)); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { $this->error(sprintf('Error while updating account #%d', $twofaccount->id)); } } @@ -86,4 +86,4 @@ class FixUnsplittedAccounts extends Command $this->line('Task completed'); } -} \ No newline at end of file +} diff --git a/app/Console/Commands/ResetDemo.php b/app/Console/Commands/ResetDemo.php index 90dd275a..83e09b37 100644 --- a/app/Console/Commands/ResetDemo.php +++ b/app/Console/Commands/ResetDemo.php @@ -2,8 +2,8 @@ namespace App\Console\Commands; -use Illuminate\Console\Command; use App\Console\Commands\Utils\ResetTrait; +use Illuminate\Console\Command; class ResetDemo extends Command { @@ -40,15 +40,15 @@ class ResetDemo extends Command */ public function handle() { - if( !config('2fauth.config.isDemoApp') ) { + if (! config('2fauth.config.isDemoApp')) { $this->comment('2fauth:reset-demo can only run when isDemoApp option is On'); + return; } - if( $this->option('no-confirm') ) { + if ($this->option('no-confirm')) { $demo = 'demo'; - } - else { + } else { $this->line('This will reset the app in order to run a clean and fresh demo.'); $demo = $this->ask('To prevent any mistake please type the word "demo" to go on'); } @@ -57,9 +57,8 @@ class ResetDemo extends Command $this->resetIcons(); $this->resetDB('DemoSeeder'); $this->info('Demo app refreshed'); - } - else { + } else { $this->comment('Bad confirmation word, nothing appened'); } } -} \ No newline at end of file +} diff --git a/app/Console/Commands/ResetTesting.php b/app/Console/Commands/ResetTesting.php index 7a02547b..f6a0715a 100644 --- a/app/Console/Commands/ResetTesting.php +++ b/app/Console/Commands/ResetTesting.php @@ -40,15 +40,15 @@ class ResetTesting extends Command */ public function handle() { - if( !config('2fauth.config.isTestingApp') ) { + if (! config('2fauth.config.isTestingApp')) { $this->comment('2fauth:reset-testing can only run when isTestingApp option is On'); + return; } - if( $this->option('no-confirm') ) { + if ($this->option('no-confirm')) { $testing = 'testing'; - } - else { + } else { $this->line('This will reset the app in order to run a clean and fresh testing app.'); $testing = $this->ask('To prevent any mistake please type the word "testing" to go on'); } @@ -58,10 +58,8 @@ class ResetTesting extends Command $this->resetDB('TestingSeeder'); $this->info('Testing app refreshed'); - } - else { + } else { $this->comment('Bad confirmation word, nothing appened'); } } - -} \ No newline at end of file +} diff --git a/app/Console/Commands/Utils/IconGenerator.php b/app/Console/Commands/Utils/IconGenerator.php index d5811fc1..90e415cb 100644 --- a/app/Console/Commands/Utils/IconGenerator.php +++ b/app/Console/Commands/Utils/IconGenerator.php @@ -28,5 +28,4 @@ class IconGenerator const LINKEDIN = 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAACXBIWXMAAAzrAAAM6wHl1kTSAAAdRElEQVR4nO3de3yV1Zkv8N+z3r137gm5AYEEAkHuoBREi04NXgEVHZ0w1dpjL17mtNXp2H7mtLVnCKPH47R1bM8ZW/XUarVTKxmrdZh6o5KiVkXCnXBJAgE2SSD3y86+vus5f+wdjAgkgYS9dt7n64fPB7bZO0929vq9a613veslnCVmJgB9f4QQ8cEAmIj4bJ48pMbLzEREwMJ7XEuWLsi+embxPE+ylcmaJASEOK8iAIB2X+jgs+/85UD7gfZeVD0dRrRNDzoMBttwCSinki+6JhJ4QVjb14a1vo6ZC5nZPfTihRDDQRF6QOqo21LveFzWm2Gf/V79q+UdGGQQDCIAmKbc8sNJ8CR9CcRlBJoEUDaIoy/OMgQQIm4I/dohtwO0jcGP2uTZfPi33+sAzjw0OHPjLS13TR5H1yjCahBd3O9JajhqF0IMKx07IPs0+N2ICv+9N7zvACoq7NM9wTrN4zThtvK8vAz1L0T0PwCaAYAIICJp/EKYjAEPEU212Fo5Ro0LdMzK24rq6lP2BE4VAFTy1+X5Lkv9iAhfISCDCIoI0f+EEKYiEIgIRIACcRaBLstW42s78q7Yj/pKffITTg4AKi4rH0ce9SQItzLDRZCGL0RCYgIIyQCuyc6kto7cK7afHAKfDoCF97iz88fcDeBuAG4iKGn8QiQmotgUIXEygS7JzsCR9lml+1FdeWJOoF8AlKspSzO+RKB/ASNNxvpCJL7ocIAIjGQmmp9FtLFz1xXHgUoGTszml6vCsnABabqXgbR4FiyEGBEWgGmK8EBhWWZS34MKAKYtb3W7Lc+9THQhODbhJ4QYPaLDAUXATUmu3lWItX0FgCLpudkEuh1AsjR+IUanWNtOY/B1hWX/mgQAqqxsrXInWcsBFIJl3C/EaMYAiHB9ONQ+n5mVVZ2S7crJy3yIGTMIgMz6CzGKMUCKPKFI+IBvnPpAZY3NmqQ1JoDA0viFGN1ipwYVay7d3dzMyu12T2JwAQ/hEkIhRAIj6PSUpJKcI3qumjExvwSMJMjGHkI4BLHLpTJtzdlqbE76Qs1Ilyv8hHAOZmJii5VmnPZSQSHE6KaiVwwIIZxIuv1COJgEgBAOJgEghINJAAjhYBIAQjiYBIAQDiYBIISDSQAI4WASAEI4mASAEA4mASCEg0kACOFgEgBCOJgEgBAO5op3AcMktp0ZnfgnA5oY/XY6I3B0z8PYvRNPPFUuhxaONRoCgEFgZsCO2AQAbrcVyElLrrdcrlYFhKCItW27mZHlC4QKuv3B/NjuqHBZSjODJAiEEyVwABCDGUzMFqm2lCR37fjsjM1zpoz7U5josO33ecdMyAmPS01jADjW6KNDx7us/GxPtttyF3tb2xcfaGxd3NntX2Azj9XMbiIiyN6IwkESMQCYCByxNblcyn/B+LyXcrLTX/nipQs2rbxqbjNifX4iYubPHtWJqIWZawGsr6yvT3r9jV3zt9d6/6ql23dXS6dvmqWU1fdtzucPJUQ8JFgAEDOYLaL2kgm5FaXzp/5KFydvXV1aagPRRv+prz7p36d4PMDMH69Zs2Zz4SXXPrt+X+2tO+uOftMfCM0BUd+dkyUIxKiVKAHAAMCs7YyUpD3zSgr+102XTfqvstJSHxFx+Tm8cCwMmHl1e2aF91f5WSXv76479t364+1fBCEpNocoISBGpUQIgGiXHhQqHJv1u5svn/vgP5Rd2XC6o/vZir2eDaD6Pzdv/lbFG3v/XFVzeHVvMDw5OjUgISBGH9PXAcTG8whOKch5/uI5U787Eo3/ZDcuWtT71csm/vucqYX/PTXJswdghtw5SYxCpgcAAERmFI19asWlJd/7yT03tI504++zdOnSyEv/9OW3rl4w/aspHk89M0sAiFHH4AAgBjhYNDb7xWXzLvqnB1Ytaztfjf9EBUSc3bGzasH0wr9L8XgOMKCjdQkxOhgaAMRaM7LTU/98ybRJ37//jku74lVJeXm5fuEHd7wze/L4J4jIlpGAGE2MDACG5pQkq2nFkrn/80f33dQY73qIyP7CjHG/Kswf8zyAiPQCxGhhYAAQE1R42sS8Z68sTt4KQw65931pefeSuVN+4XJZxwwpSYhzZthpwOhCn4yU5F1XLip5ZunSpZF4V9QntrJwe93hY09s2n/kIYuUBZJTgyKxmdUDYIZtM88szK/49i1XHY53Oadgj8vKejUrLbkWSroBIvEZFQBMzNkZyYenT8j7PWDebcuJiG9duLA+Lyvtda0hawNEwjMoAIiJSWenpfypaGLB0XhXczqlpcXBJbNL1oHZB5IAEInNoAAAQAjmZaW9e88NC/3n+5z/YBER33bTok1j0lK8WtYGiQRnTgAQM4C25UtmfBTvUgYyOz/fN2ls9kZp/yLRGRIAxKxBaclJx76weFbcz/sPhIiYSW8jJjkLIBKaIQHAsLXWE/Mztk/Lyek2tfvfn5ssr9ulfCDoeNcixNkyJAAAzRrpqckdSJDLbvNz070el6uZZFWgSGCGBAABUEhxewLxrmQwmFnl56T1MtgX71qEOBeGBABAxGS5KBjvOgbL5UmxAY6QrAUQCcyYAGAGbJs98a5j0PwRxSCLE2TIIsSpGBIA0W35gqFIcrwrGQwi0t72tlQFpMW7FiHOhSEBABABPn8wAwnSpW7vDhSEbTuPZftwkcCMCQCXsqihtWtedXNz2qn28zdNKGwXhsI6AyxDAJG4TAkAIkXo8Pkn7t7TmB/vYgbCzORy0WyOrl6UABAJy5QAAJhIEXJeqdx6abxLGUhVY2NKfWPbNdLyRaIzJwAAsEbKsfbuS16vrTX2bAAz0xvv7J7f0RMoVEoiQCQ2gwKAiQnU1u1fsXF9bYGp8wCvv17r2bitZiXAMv4XCc+gAACIoTp6/MVHW1uXwbDagOjR/+19OyY2t3evIEUKMv4XCc6sRkYEUmTtOnj0zp//YeOEeJdzCtaRzo6VHb7gbGhp/CLxmRUAYCIQdflDc9dvrrl97Vq2Bn7O+cHM9L9ffGva7gNN3yCCJc1fjAaGBQAAMGnWqTXelm80YMO0eFfT57nKyqQNVQfuCobtydFlSxIBIvEZGAAAMVFPIFj423e2PPz9X6/PjXc9a9ey9fa73v9W19jyDQBuyOo/MUoYGQAgkCJFrZ29y7btqvnHp57a7I5XKcxM7ze8PGdnfcM3mTlJDvxiNDEzAAAATAyk7fM2f/vNo9sfLP/NHzPPewXM9K3HX579zvbaF7t7A3MJUHL0F6OJwQEQw3Dvqmv6dtVu73e+++Pnz9t1AsysvvbIbxa8t/vAL3oCwZmKZP8/MfoYdmuwzyAQOKLtzN31Tf/YG8gZ838r3n2YmVtGct/ADQcPJn/9R7+7dsuBhke6fIFZRDLpJ0Yn0wMAiDY8BiPpYFPbPc+9/dHMnfXeR/5YU/Ph8mnTQsMZBMysfvjkuoKfPPnmPTVHW/4uYus8afxiNEuEAADQdxtOSmrv6b363V0H5zS2df7y8GUN/w6g5lxemJmJiHjD7t3pX3/0xeu21nnv6+gJLCEFC9GGL41fjFp00w+efmJbXeO9liJjFt0MILp9ELPtcbma5xSPfyY12fNG6aKSvV+/7vMdsf/fdzffTzXevt5C3+NVVXC9+MG6kpqmxoVNrT33Nrd3LyCitNgXQyb8xGhEStkKaCm9cPrfJkoPoD8CQESKQrY9fkvt0R8ke1xf33/kWNUb71dvXPVXC9fPmFrQwMytwGf37N/b3Jzx2vs7JmzYUrdoS633823dvqX+YHiqbXOSsog/ucAnITYmEuKcJGIP4GRMBNaaKRJhMDQ8HldwfHbGvtQkz1EQQpZSdkRrTyRs57Z295Z09gTGgjWUsuByETNLV184R6L3AE5GzAARwe1WACxAc1JDa/dcZp4TnT8EUWzLESKQ22VFvw7Rib+4Vi9EHI2GAABwUrc9umLHOv2SfeneCwEkwkIgIcSIkQAQwsEkAIRwMAkAIRxMAkAIB5MAEMLBJACEcDAJACEcTAJACAcbLSsBxahBHF2pGd0Gou9BAGD+ZAVnvw2auN+X9HuOXM05GBIAwgDERNHLvG2tSWuGrRlKAYqICIqJoo0+dpl37JJugo6FgmabtY5e9KEUwaUUiEgDILne4/QkAMT5Fm2xBGYd+ysRe1xWMzO35GWlH01PTTqSl5HaVpQ35ujYnPT9vYHI8U5/V1fEdnMSWdq2wgR2qYitedK4jCl2hK3Gls4FLZ2B7A5/r+rtDUxs9wWn+YPBdEupnEA4ks8axGBNoNj2jtFtI+L2LhjC3AAgaCJis3px3Hf14AgV1XckHLn9DoeGKXqp9PD8EghgBti2NYFg52akNU4en/NhKBLZNGVcTtVFUyd6F0+Z2Dpv3qRufLKXw4kNXk5ZIfOB2F/f7nusvr7ec6AzlFtd25BRfbh5XF1jy/zM1OSLWjp7Fja1dpd0+YOpHpdFSpEG07D9fInIyABgBrss5XMp1XrikbgjAtgKhe0CHpn3jQHWbss6TkTBEXj9IWNGcigSyUd0svhsGwkjul8DXJYKZKYm14zPzthw4+XzX715UfHHBQUF/n47NSkAPJR9Hvt9bf/nBJi58coLpzcS0V4Af+7bBepPm2umvLer5tJ3ttTd2uULzOsOBCfZNnuit3p33ryBkQEAMPIz01+YVzL+6XA4DGVZcQ8AbduUNyY979X3dv86YuuJw/4NCEyMY9cvmfO19s7upmF//bMQimD2x3sPPxbReizzkO7TeKJRRrdYop7i8dlbi8flPjejMPe9lZ8rOjx79uzwyQ09NmYfFie/Vt8WcVctuuDgVYsuOLhsVu26im27C5tbekq9rR231De1LWZwKjFULOocEQSGBgDgclHDkw/87W7E9gCMdz0A1Fub9hW9+t7uyEh9A5s58KWln9u5YEbRcZxiO7PzzPqHJ35vgRA4mydrzUj2uNvHZae9ff3n5/z8tsuv2lxURP6+TViHu9jBOOn7djHzHgB7vF7vsy9s2LP4rS37vtrc3rPCFwzmfnL399HdIzA2AABgzZo1ury8PN4NAUB0F9JIRI94LVprBmDHq5H0YWay9ZCHXgwGlKLewrFZm+dOmfDIhfOmfHTP1Qu7+47I8f65+utXi5+ZN04rmlj17s59C6sPHP32keaO0rDWmX3bUcexzBFlbACY9EE5n1JSUhP152bNzDkZaYenFOQ+cveyxS8vWzKnDQDujXdlgxD7vPUA+PPaDburNm7fc92mvYcePd7RM1XR6A0BYwNAJApiMMNS5Js6Pue1S+eW/LPra8tqrjNj2HZWVi2d08PMv3/4uXU7Ptzb8J3ahuayUFhn0yjcKl4CQJwThma3y+pdPHPy6hUXznr+thsWthIRl8e7sHMU6xHUbN/e9J0fv/b29qqaIw8FQpGc6OOjJwRkhZQ4W6yZdV5m+uZbr7jozpUP3vGzvsYf78KG04UXjvetnJH0dNkXPndnblbaVjDb5qzTOHfSAxBngzWzHjcmY/vFcybd+chd1+8fzlN4plm1apXNzK/7dOj4u1tq/s/xDt/FimhU3CpeegBiiIg1Q0/MzXr7moXT/ubf7vubvaO58fchIv2Tu2+sWrFoxt35WalVDOjR0BOQHoAYCgY4kj8mbdPc6YX3P3z3yoPxLuh8IiLNzHtdHus7L23YUeELBMciwc8OSA9ADBYDzDmZqVuuv2TuXU/ef2ttvAuKByKKPPjlZX/5/Jzi73lcruMgaCTwGQ8JADEgiq3GTE3ytF4+Z8pDq79y7f7RNtk3FESk587O+N2lM4seZQ073vWcCwkAMaDotfjoXTyzaM210+avd8KYfyD3LV8e+vvbL//1pHHZ73L0YrWEDESZAxAD0hr21Al5Ly+buuD/rVhxQSje9ZggdnFR5yXTJz3c3uWb3BMITUnEawekByDOiABkZ6bUXzp38mNlZbPD8a7HJETEy2evfHduyYTnbJ2QHQAJAHF64TBga44snj75kX/+yopdTh73n87SpRRJdmf9bGJe5jY2Yt+KoZEhgDgdPXV8fg9djBevWzT3FWn8p7dsSrA3HMl7qrmj5zHNnBrdRSkxTg9KAIhT6lsLD2D1L+JdjOHKysp0zqa9L9cebb6jsa37MkUJ0fYByBBAiHNGRHzV4pltc6cUvKCASCKdD5AAEGIYEBGPG5OzPm9MxkFQ4kSABIAQw2RJ6dSG3MyUdeDEWR0oASDEMFk+bVromkXT1yqL2vpudBLvmgYiASDEMCEi/uuLp+6YkJu58zxsHzksJACEGEbFxcXBorHZ64kT41SABIAQw4iI2I5gfXpKUnO8axkMCQAhhhEz01ULph9JSrJ2AWT8piESAEIMIyLiu1Ze0jY+O+vj6DyA0e1fAkCIEWBffMGkLQps/F4BEgDivGFmYmY1wJ+EmDw7EyLSSxdP+0ApZZt9/JdrAcR5ELvrL7xeb1Ltsd609mBAoQcIWP4TjT05JYWzk5J14cLp3cwcxhDvEmwa3XKkcdK47G31TW2XEJl7RkACQAy7/kfxnYcPj/nZf7x32ba6I9MbmtvnNHf4JgciEQt80tVyRJzsdofH56TXTczN2nPFRSWbmXkTEY3YzVhHUmlpqf34+rpdWvPFyiJje9oSAGLYMDNVVlZaj/6msnjPEe9VTa1dt3ubuxZ2+4OpNmt2KUUul6VPeUBkIBiOoLWr5+odBxr47S378MQf3j9w8w9/+V+zigpevHZ66vbS0tJgIvUKstM8u9wuFWGGBUMvD5YAEMNi7dq11prn/pjvPd755Y/3HbnNFwzNiNg6mUDkdllwk+q70bti1qdpDMQuS8HlUgCDmtq7px5r77qv9mjzzbsO5v2htjv1p8x8KFH2JOzpjVRbpHptaA+f3OMxhASAOGebN292//bD+ms+qN6/pqGt63OWin7WFSmK7pHH+KTLf6YDeGzoEPtaBRCguDcQLtp5sOGbLV09V26tO7Rm7Vp+ZdUqMn2GnQrzMrv3Hz3u7w2GxsS7mNMxdmwiEkP52g3pP319zwOvb9r/zLG27ossIgITgTFMt85iAqCUItXU3j27cnvdT17d+0LZhg0bTD948aWzJjVYpBrY4GXBEgDirDGz2r7j4A8/3Fv/YDASGQui2Fh3RE7lEQHKHwwXbatr+NnaquM3mHzKkIi4aHJmR0RHOuJdy5lIAIiz8vyb29Nuf/iF72+r895va04D00g1/E8hEPnDoby/7Dn00EPPvbHI5BAYZ80IZWekt2mtYeqSYAkAMWTMTB9U7yvdXuP9FhGSCMPV3R/Udydiom5fYOaHe488aPJZgWnTEJo+MW9LRJu7Z7gEgBgSZqZ171cXfVR96Kf+UGQs4jK+ZQJg7T3ceN1Dz755c99CIwOp/NyMQ7bWAJm5ZbjpEynCMNXV1e6fv7bxro5u/2SiERvvD4wIzOx5s2rPPSVFWR8w83ETewPjstODYDAMXQdganIKAzEzPVe5f3ZTa/edoHgvbmFSpKi503f5H96rvtjExg+Ax6QkBTxul4m1AZAAEENDh5o7yjp6/BM+s5Q3DhhMwXA4zR+MfJGZrXjXcwqclp62Ly3J3WvmAEACQAwSM1PlR7UT9h5uvgVEFij+AQAABMKBhrYrPtpRW2DiGYHODn+vZamgqfsCSACIwaJfrf9gqS8QnKgMamakCF3+wJj//HjvAhg2ziYifqvucJfb5fIZ2v4lAMTAmJnWratKbmrvuYqZUwzo/X+CiZRSKR9WH74chgUAAOCIFy6XYjY0ASQAxICIiF8/fCCz2xe4hM/rOf/BYFIE5fOHZr1auS3DtGFA2vwFnOQycXoiSgJADEqSjUkt3b0XwMSjLMC25pkb9xzNiXchJysGYClzm5m5lQljMLOKwLU0GI4Ye1WLzx/I6ezuNi4AWrv97LJUm5m5KQEgBocONrQUmzqTDQaFtU7JSvMUxbuUk90yL8VO8bh2mdn8JQDEAJiZqr3erJYu3yxju7IE+IOhpN5gpARGHmpNXQUgASAGRvu9LZmtnb48Syljl7QCQI8/qGBiN8XMVYoAJADEwLimti1HKUqDsY2fQEQUidgFhi4JNradGVuYMAMRcV3jsbEEZJi6rx0AKBC19wSmrF1r1pLg0tJS7QuEm6L7mZhHAkAMqLaxfaKtdZaJvesoJlJELZ0908vK4I53Nf2tWbMGgUikx9R3TgJADKg7GITBe1oAiI5NQiET9wldDTJscVJ/EgBiQJEwK7Obf1RIm3gPkTXxLuCMJADEGTEz5Wak5LChY9iTeb3ehKjTFBIA4owqKipUSpIrB+Zuu3UCa5BlWRIAQ2D8L1WIQYl1UJqbTbpY2XwSAEI4mASAEA4mASCEg0kACOFgEgBCOJgEgBAOJgEghINJAAjhYBIAQjiYBIAQDiYBIISDSQAI4WASAEI4mASAEA4mASCEg0kACOFgEgBCOJgEgBAOJgEghINJAAjhYBIAQjiYBIAQDiYBIISDSQAI4WASAEI4mASAEA4mASCEg0kACOFgEgBCOJgEgBAOJgEghINJAAjhYBIAQjiYBIAQDiYBIISDSQAI4WASAEI4mASAEA4mASCEg0kACOFgEgBCOJgEgBAOJgEghINJAAjhYBIAQjiYBIAQDiYBIISDSQAI4WASAEI4mASAEA4mASCEg0kACOFgEgBCOJgEgBAOJgEghINJAAjhYBIAQjiYBIAQDiYBIISDSQAI4WDGBgAzE1avjncZ553f30vxriFxsXnv3erVMLiZwRXvAk6HlFKzKyqI2cBf6gghQEXcLgsAMXO8yznhha2/1PGuYTCYifyp3ZZJn5kKgP5ksbHtzNDCCG2dvtsfrzw667F3/jXexZzgdlkpzJw3Ii/OIKVo7AM//Y+nbNvuHJHvMVQKUFAIhMPzyZgmdXoEnvDA4+t+zdB+bUJkKUApBV9vcKGpb5+RAUAE6vGHZnT5AjMAAKYcDImgFGGEGgNpjZSjzZ3LYcrRn6JvvYr+3KZ+hgEABCCiOe1oS9dNAJvxmYm9Y6QUFMHI98/IAAAAIoJlWfEu4zRG5tMV/ZmN/JzAjBZ1ZvL+DZ2xAWDkhM6Ic+LPPJzk/Rsqc6cnhRAjTgJACAeTABDCwSQAhHAwCQAhHEwCQAgHkwAQwsEkAIRwMAkAIRxMAkAIB5MAEMLBJACEcDAJACEcTAJACAeTABDCwSQAhHAwCQAhHEwRlOyiIoRDqW013tcUoY3BJuyjKoQ4L5iYbFI9/kAAIA2QmbsWCiGGF7MKhOxDIcuqUWHGdqWohljmA4RwAAaAYCTsTd7bflx1NrX1EKGBATAbunexEGJYcHTrZBuMV5566h6tyjc/ZYPwCwK6QBIAQoxmBAYDjS5NmwBoVU7EIe3bDnAdTL17gRDinEV7+BRhjWcaulx1RMQKAB/e19YD0GMAOhiQswFCjD4MgmbgALH9MirLNdC3EKjq6XC3rV8D+B0ADJkLEGJ0iU7yBaH5N3Uv7d6D2IH+xMx/c8VqH2n6McC7maAlBIQYHZjBIEQI9CFrfgaYc6Jt9zv1R3xglq7SjHJi9MRmCyQEhEhgscavmbEtYuv76ivKjwHlJ4b5n779bmUlZ8xaeYisUIiAzzPBRQyCobc2FkKcXuy0vgZ4CzPff2ht+TacNNH/mftvd1W/aafPunGLpUKtBMxgwhgJASESTPTIzyDerVndcegl3gFUfqZH/5kAAICu6jcj7bOu2J5F9AEB04lQAECBAQkCIQzFYAYAYiaiEAEvk6bv17+kd/bv9vc3UGOmKbc/PIlY3w/wXWDKiH4DsPQKhDAEg5lix3wCA7QDWv82rDv+zVvxeABnWN8zmAZMKCt3T3HjIti4E8paAvBkAJnEUBICQsQPA5oAzUA3MWqZ+CV/xP18E7a2oaLCHuj5Q2i8TChbpYqtOUUWaAETbgTTDSDkQjYWEeJ86zuqb2HW7zNZGyhIWw/+PnIEKGcMclXv/weI6Gs1KH2w+QAAAABJRU5ErkJggg=='; const TWITTER = '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'; - -} \ No newline at end of file +} diff --git a/app/Console/Commands/Utils/ResetTrait.php b/app/Console/Commands/Utils/ResetTrait.php index 7dd48eb3..dca23895 100644 --- a/app/Console/Commands/Utils/ResetTrait.php +++ b/app/Console/Commands/Utils/ResetTrait.php @@ -2,7 +2,6 @@ namespace App\Console\Commands\Utils; -use App\Console\Commands\Utils\IconGenerator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; @@ -45,7 +44,7 @@ trait ResetTrait $this->line('Icons regenerated'); } - + /** * Reset DB */ @@ -81,10 +80,9 @@ trait ResetTrait protected function seedDB(string $seeder) : void { $this->callSilent('db:seed', [ - '--class' => $seeder + '--class' => $seeder, ]); $this->line('Database seeded'); } - } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 6d0166cc..7ba4c52d 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -27,7 +27,7 @@ class Kernel extends ConsoleKernel */ protected function commands() { - $this->load(__DIR__.'/Commands'); + $this->load(__DIR__ . '/Commands'); require base_path('routes/console.php'); } diff --git a/app/Events/TwoFAccountDeleted.php b/app/Events/TwoFAccountDeleted.php index 51a12d30..3e024b5a 100644 --- a/app/Events/TwoFAccountDeleted.php +++ b/app/Events/TwoFAccountDeleted.php @@ -28,4 +28,4 @@ class TwoFAccountDeleted $this->twofaccount = $twofaccount; Log::info(sprintf('TwoFAccount #%s deleted', $twofaccount->id)); } -} \ No newline at end of file +} diff --git a/app/Exceptions/DbEncryptionException.php b/app/Exceptions/DbEncryptionException.php index 5cf6a447..a392d62d 100644 --- a/app/Exceptions/DbEncryptionException.php +++ b/app/Exceptions/DbEncryptionException.php @@ -11,4 +11,4 @@ use Exception; */ class DbEncryptionException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/EncryptedMigrationException.php b/app/Exceptions/EncryptedMigrationException.php index 9b2cee10..da9725a7 100644 --- a/app/Exceptions/EncryptedMigrationException.php +++ b/app/Exceptions/EncryptedMigrationException.php @@ -11,4 +11,4 @@ use Exception; */ class EncryptedMigrationException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 52fb0f7b..69b4aef1 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -14,7 +14,7 @@ class Handler extends ExceptionHandler protected $levels = [ // ]; - + /** * A list of the exception types that are not reported. * @@ -44,65 +44,72 @@ class Handler extends ExceptionHandler { $this->renderable(function (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception, $request) { return response()->json([ - 'message' => 'not found'], 404); + 'message' => 'not found', + ], 404); }); $this->renderable(function (InvalidOtpParameterException $exception, $request) { return response()->json([ 'message' => 'invalid OTP parameters', - 'reason' => [$exception->getMessage()] + 'reason' => [$exception->getMessage()], ], 400); }); $this->renderable(function (InvalidQrCodeException $exception, $request) { return response()->json([ - 'message' => 'not a valid QR code'], 400); + 'message' => 'not a valid QR code', ], 400); }); $this->renderable(function (InvalidSecretException $exception, $request) { return response()->json([ - 'message' => 'not a valid base32 encoded secret'], 400); + 'message' => 'not a valid base32 encoded secret', ], 400); }); $this->renderable(function (DbEncryptionException $exception, $request) { return response()->json([ - 'message' => $exception->getMessage()], 400); + 'message' => $exception->getMessage(), ], 400); }); $this->renderable(function (InvalidMigrationDataException $exception, $request) { return response()->json([ - 'message' => __('errors.invalid_x_migration', ['appname' => $exception->getMessage()])], 400); + 'message' => __('errors.invalid_x_migration', ['appname' => $exception->getMessage()]), + ], 400); }); $this->renderable(function (UnsupportedMigrationException $exception, $request) { return response()->json([ - 'message' => __('errors.unsupported_migration')], 400); + 'message' => __('errors.unsupported_migration'), + ], 400); }); $this->renderable(function (EncryptedMigrationException $exception, $request) { return response()->json([ - 'message' => __('errors.encrypted_migration')], 400); + 'message' => __('errors.encrypted_migration'), + ], 400); }); $this->renderable(function (UndecipherableException $exception, $request) { return response()->json([ - 'message' => __('errors.cannot_decipher_secret')], 400); + 'message' => __('errors.cannot_decipher_secret'), + ], 400); }); $this->renderable(function (UnsupportedOtpTypeException $exception, $request) { return response()->json([ - 'message' => __('errors.unsupported_otp_type')], 400); + 'message' => __('errors.unsupported_otp_type'), + ], 400); }); $this->renderable(function (\Illuminate\Auth\AuthenticationException $exception, $request) { if ($exception->guards() === ['reverse-proxy-guard']) { return response()->json([ - 'message' => $exception->getMessage()], 407); - } - else { + 'message' => $exception->getMessage(), + ], 407); + } else { return response()->json([ - 'message' => $exception->getMessage()], 401); + 'message' => $exception->getMessage(), + ], 401); } }); } -} \ No newline at end of file +} diff --git a/app/Exceptions/InvalidMigrationDataException.php b/app/Exceptions/InvalidMigrationDataException.php index 042fa468..0c310ef4 100644 --- a/app/Exceptions/InvalidMigrationDataException.php +++ b/app/Exceptions/InvalidMigrationDataException.php @@ -11,4 +11,4 @@ use Exception; */ class InvalidMigrationDataException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/InvalidOtpParameterException.php b/app/Exceptions/InvalidOtpParameterException.php index 67b0b21a..cf3ed3e9 100644 --- a/app/Exceptions/InvalidOtpParameterException.php +++ b/app/Exceptions/InvalidOtpParameterException.php @@ -11,4 +11,4 @@ use Exception; */ class InvalidOtpParameterException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/InvalidQrCodeException.php b/app/Exceptions/InvalidQrCodeException.php index ccabe6ef..9002538b 100644 --- a/app/Exceptions/InvalidQrCodeException.php +++ b/app/Exceptions/InvalidQrCodeException.php @@ -11,4 +11,4 @@ use Exception; */ class InvalidQrCodeException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/InvalidSecretException.php b/app/Exceptions/InvalidSecretException.php index 236e806a..45c23f26 100644 --- a/app/Exceptions/InvalidSecretException.php +++ b/app/Exceptions/InvalidSecretException.php @@ -11,4 +11,4 @@ use Exception; */ class InvalidSecretException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/UndecipherableException.php b/app/Exceptions/UndecipherableException.php index f76cfcd2..7922d6b7 100644 --- a/app/Exceptions/UndecipherableException.php +++ b/app/Exceptions/UndecipherableException.php @@ -11,4 +11,4 @@ use Exception; */ class UndecipherableException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/UnsupportedMigrationException.php b/app/Exceptions/UnsupportedMigrationException.php index c7cb3e5f..399a1f5b 100644 --- a/app/Exceptions/UnsupportedMigrationException.php +++ b/app/Exceptions/UnsupportedMigrationException.php @@ -11,4 +11,4 @@ use Exception; */ class UnsupportedMigrationException extends Exception { -} \ No newline at end of file +} diff --git a/app/Exceptions/UnsupportedOtpTypeException.php b/app/Exceptions/UnsupportedOtpTypeException.php index 16316574..4633510b 100644 --- a/app/Exceptions/UnsupportedOtpTypeException.php +++ b/app/Exceptions/UnsupportedOtpTypeException.php @@ -11,4 +11,4 @@ use Exception; */ class UnsupportedOtpTypeException extends Exception { -} \ No newline at end of file +} diff --git a/app/Extensions/RemoteUserProvider.php b/app/Extensions/RemoteUserProvider.php index 8f5ad83e..9a8b1ab4 100644 --- a/app/Extensions/RemoteUserProvider.php +++ b/app/Extensions/RemoteUserProvider.php @@ -6,10 +6,10 @@ namespace App\Extensions; use App\Models\User; +use Exception; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Support\Arr; -use Exception; class RemoteUserProvider implements UserProvider { @@ -23,7 +23,6 @@ class RemoteUserProvider implements UserProvider // The downside of this approach is that we have to be sure that no change that needs // to be persisted will be made to the user instance afterward (i.e through middlewares). - /** * The currently authenticated user. * @@ -31,26 +30,24 @@ class RemoteUserProvider implements UserProvider */ protected $user; - /** * Get the In-memory user - * + * * @return \App\Models\User */ protected function getInMemoryUser() { if (is_null($this->user)) { - $this->user = new User; - $this->user->name = 'Remote User'; + $this->user = new User; + $this->user->name = 'Remote User'; $this->user->email = 'fake.email@do.not.use'; } - + return $this->user; } - /** - * @inheritDoc + * {@inheritDoc} */ public function retrieveById($identifier) { @@ -67,8 +64,8 @@ class RemoteUserProvider implements UserProvider } /** - * @inheritDoc - * + * {@inheritDoc} + * * @codeCoverageIgnore */ public function retrieveByToken($identifier, $token) @@ -77,8 +74,8 @@ class RemoteUserProvider implements UserProvider } /** - * @inheritDoc - * + * {@inheritDoc} + * * @codeCoverageIgnore */ public function updateRememberToken(Authenticatable $user, $token) @@ -87,8 +84,8 @@ class RemoteUserProvider implements UserProvider } /** - * @inheritDoc - * + * {@inheritDoc} + * * @codeCoverageIgnore */ public function retrieveByCredentials(array $credentials) @@ -97,12 +94,12 @@ class RemoteUserProvider implements UserProvider } /** - * @inheritDoc - * + * {@inheritDoc} + * * @codeCoverageIgnore */ public function validateCredentials(Authenticatable $user, array $credentials) { return true; } -} \ No newline at end of file +} diff --git a/app/Extensions/WebauthnCredentialBroker.php b/app/Extensions/WebauthnCredentialBroker.php index 991cc2c8..35379c46 100644 --- a/app/Extensions/WebauthnCredentialBroker.php +++ b/app/Extensions/WebauthnCredentialBroker.php @@ -2,8 +2,8 @@ namespace App\Extensions; -use Closure; use App\Models\WebAuthnAuthenticatable; +use Closure; use Illuminate\Auth\Passwords\PasswordBroker; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; @@ -14,14 +14,13 @@ class WebauthnCredentialBroker extends PasswordBroker * * @param array $credentials * @param \Closure|null $callback - * * @return string */ - public function sendResetLink(array $credentials, Closure $callback = null): string + public function sendResetLink(array $credentials, Closure $callback = null) : string { $user = $this->getUser($credentials); - if (!$user instanceof WebAuthnAuthenticatable) { + if (! $user instanceof WebAuthnAuthenticatable) { return static::INVALID_USER; } @@ -40,20 +39,18 @@ class WebauthnCredentialBroker extends PasswordBroker return static::RESET_LINK_SENT; } - /** * Reset the password for the given token. * * @param array $credentials * @param \Closure $callback - * * @return \Illuminate\Contracts\Auth\CanResetPassword|string */ public function reset(array $credentials, Closure $callback) { $user = $this->validateReset($credentials); - if (!$user instanceof CanResetPasswordContract || !$user instanceof WebAuthnAuthenticatable) { + if (! $user instanceof CanResetPasswordContract || ! $user instanceof WebAuthnAuthenticatable) { return $user; } diff --git a/app/Facades/Groups.php b/app/Facades/Groups.php index dd10fece..6616668e 100644 --- a/app/Facades/Groups.php +++ b/app/Facades/Groups.php @@ -11,4 +11,4 @@ class Groups extends Facade { return GroupService::class; } -} \ No newline at end of file +} diff --git a/app/Facades/QrCode.php b/app/Facades/QrCode.php index c9b8f0f7..ebf34a7f 100644 --- a/app/Facades/QrCode.php +++ b/app/Facades/QrCode.php @@ -11,4 +11,4 @@ class QrCode extends Facade { return QrCodeService::class; } -} \ No newline at end of file +} diff --git a/app/Facades/Settings.php b/app/Facades/Settings.php index 3822eda4..ef6852d2 100644 --- a/app/Facades/Settings.php +++ b/app/Facades/Settings.php @@ -11,4 +11,4 @@ class Settings extends Facade { return SettingService::class; } -} \ No newline at end of file +} diff --git a/app/Facades/TwoFAccounts.php b/app/Facades/TwoFAccounts.php index be9c3553..dd166f18 100644 --- a/app/Facades/TwoFAccounts.php +++ b/app/Facades/TwoFAccounts.php @@ -11,4 +11,4 @@ class TwoFAccounts extends Facade { return TwoFAccountService::class; } -} \ No newline at end of file +} diff --git a/app/Factories/MigratorFactory.php b/app/Factories/MigratorFactory.php index bec5c53e..1027b704 100644 --- a/app/Factories/MigratorFactory.php +++ b/app/Factories/MigratorFactory.php @@ -2,67 +2,63 @@ namespace App\Factories; -use App\Services\Migrators\GoogleAuthMigrator; +use App\Exceptions\EncryptedMigrationException; +use App\Exceptions\UnsupportedMigrationException; use App\Services\Migrators\AegisMigrator; +use App\Services\Migrators\GoogleAuthMigrator; use App\Services\Migrators\Migrator; use App\Services\Migrators\PlainTextMigrator; use App\Services\Migrators\TwoFASMigrator; -use Illuminate\Support\Facades\App; use Illuminate\Support\Arr; +use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Validator; -use App\Exceptions\UnsupportedMigrationException; -use App\Exceptions\EncryptedMigrationException; class MigratorFactory implements MigratorFactoryInterface { /** * Infer the type of migrator needed from a payload and create the migrator - * - * @param string $migrationPayload The migration payload used to infer the migrator type + * + * @param string $migrationPayload The migration payload used to infer the migrator type * @return Migrator */ public function create(string $migrationPayload) : Migrator { if ($this->isAegisJSON($migrationPayload)) { return App::make(AegisMigrator::class); - } - else if ($this->is2FASv2($migrationPayload)) { + } elseif ($this->is2FASv2($migrationPayload)) { return App::make(TwoFASMigrator::class); - } - else if ($this->isGoogleAuth($migrationPayload)) { + } elseif ($this->isGoogleAuth($migrationPayload)) { return App::make(GoogleAuthMigrator::class); - } - else if ($this->isPlainText($migrationPayload)) { + } elseif ($this->isPlainText($migrationPayload)) { return App::make(PlainTextMigrator::class); + } else { + throw new UnsupportedMigrationException(); } - else throw new UnsupportedMigrationException(); - } - /** * Determine if a payload comes from Google Authenticator - * - * @param string $migrationPayload The payload to analyse + * + * @param string $migrationPayload The payload to analyse * @return bool */ private function isGoogleAuth(string $migrationPayload) : bool { // - Google Auth migration URI : a string starting with otpauth-migration://offline?data= on a single line - $lines = preg_split('~\R~', $migrationPayload, -1 , PREG_SPLIT_NO_EMPTY); + $lines = preg_split('~\R~', $migrationPayload, -1, PREG_SPLIT_NO_EMPTY); - if (!$lines || count($lines) != 1) + if (! $lines || count($lines) != 1) { return false; + } return preg_match('/^otpauth-migration:\/\/offline\?data=.+$/', $lines[0]) == 1; } - /** * Determine if a payload is a plain text content - * - * @param string $migrationPayload The payload to analyse + * + * @param string $migrationPayload The payload to analyse * @return bool */ private function isPlainText(string $migrationPayload) : bool @@ -70,18 +66,17 @@ class MigratorFactory implements MigratorFactoryInterface // - Plain text : one or more otpauth URIs (otpauth://[t|h]otp/...), one per line return Validator::make( - preg_split('~\R~', $migrationPayload, -1 , PREG_SPLIT_NO_EMPTY), + preg_split('~\R~', $migrationPayload, -1, PREG_SPLIT_NO_EMPTY), [ '*' => 'regex:/^otpauth:\/\/[h,t]otp\//i', ] )->passes(); } - /** * Determine if a payload comes from Aegis Authenticator in JSON format - * - * @param string $migrationPayload The payload to analyse + * + * @param string $migrationPayload The payload to analyse * @return bool */ private function isAegisJSON(string $migrationPayload) : mixed @@ -107,15 +102,14 @@ class MigratorFactory implements MigratorFactoryInterface if (Arr::has($json, 'db')) { if (is_string($json['db']) && is_array(Arr::get($json, 'header.slots'))) { throw new EncryptedMigrationException(); - } - else { + } else { return count(Validator::validate( $json, [ - 'db.entries.*.type' => 'required', - 'db.entries.*.name' => 'required', + 'db.entries.*.type' => 'required', + 'db.entries.*.name' => 'required', 'db.entries.*.issuer' => 'required', - 'db.entries.*.info' => 'required' + 'db.entries.*.info' => 'required', ] )) > 0; } @@ -124,11 +118,10 @@ class MigratorFactory implements MigratorFactoryInterface return false; } - /** * Determine if a payload comes from 2FAS Authenticator - * - * @param string $migrationPayload The payload to analyse + * + * @param string $migrationPayload The payload to analyse * @return bool */ private function is2FASv2(string $migrationPayload) : mixed @@ -155,18 +148,17 @@ class MigratorFactory implements MigratorFactoryInterface // } $json = json_decode($migrationPayload, true); - + if (Arr::get($json, 'schemaVersion') == 2 && (Arr::has($json, 'services') || Arr::has($json, 'servicesEncrypted'))) { if (Arr::has($json, 'servicesEncrypted')) { throw new EncryptedMigrationException(); - } - else { + } else { return count(Validator::validate( $json, [ 'services.*.secret' => 'required', - 'services.*.name' => 'required', - 'services.*.otp' => 'required' + 'services.*.name' => 'required', + 'services.*.otp' => 'required', ] )) > 0; } @@ -174,5 +166,4 @@ class MigratorFactory implements MigratorFactoryInterface return false; } - } diff --git a/app/Factories/MigratorFactoryInterface.php b/app/Factories/MigratorFactoryInterface.php index 4792ae0a..ed899c2c 100644 --- a/app/Factories/MigratorFactoryInterface.php +++ b/app/Factories/MigratorFactoryInterface.php @@ -8,9 +8,9 @@ interface MigratorFactoryInterface { /** * Infer the type of migrator needed from a payload and create the migrator - * - * @param string $migrationPayload The migration payload used to infer the migrator type + * + * @param string $migrationPayload The migration payload used to infer the migrator type * @return Migrator */ public function create(string $migrationPayload) : Migrator; -} \ No newline at end of file +} diff --git a/app/Helpers/Helpers.php b/app/Helpers/Helpers.php index 2227bb87..34301009 100644 --- a/app/Helpers/Helpers.php +++ b/app/Helpers/Helpers.php @@ -8,17 +8,22 @@ class Helpers { /** * Generate a unique filename - * - * @param string $extension + * + * @param string $extension * @return string The filename */ - public static function getUniqueFilename(string $extension): string + public static function getUniqueFilename(string $extension) : string { - return Str::random(40).'.'.$extension; + return Str::random(40) . '.' . $extension; } - - public static function cleanVersionNumber(?string $release): string|false + /** + * Clean a version number string + * + * @param string|null $release + * @return string|false + */ + public static function cleanVersionNumber(?string $release) : string|false { return preg_match('/([[0-9][0-9\.]*[0-9])/', $release, $version) ? $version[0] : false; } diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index cb99e067..795f24fa 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -2,9 +2,9 @@ namespace App\Http\Controllers\Auth; -use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\SendsPasswordResetEmails; +use Illuminate\Http\Request; class ForgotPasswordController extends Controller { @@ -21,7 +21,6 @@ class ForgotPasswordController extends Controller use SendsPasswordResetEmails; - /** * Validate the email for the given request. * diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 23b9f8bd..fb919457 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -2,17 +2,16 @@ namespace App\Http\Controllers\Auth; +use App\Http\Controllers\Controller; +use App\Http\Requests\LoginRequest; +use Carbon\Carbon; +use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Http\Response; -use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Lang; -use App\Http\Requests\LoginRequest; -use Illuminate\Foundation\Auth\AuthenticatesUsers; -use Carbon\Carbon; use Illuminate\Support\Facades\Log; - class LoginController extends Controller { /* @@ -28,7 +27,6 @@ class LoginController extends Controller use AuthenticatesUsers; - /** * Handle a login request to the application. * @@ -65,10 +63,10 @@ class LoginController extends Controller return $this->sendFailedLoginResponse($request); } - /** * log out current user - * @param Request $request + * + * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function logout(Request $request) @@ -79,7 +77,6 @@ class LoginController extends Controller return response()->json(['message' => 'signed out'], Response::HTTP_OK); } - /** * Send the response after the user was authenticated. * @@ -96,11 +93,10 @@ class LoginController extends Controller return response()->json([ 'message' => 'authenticated', - 'name' => $name + 'name' => $name, ], Response::HTTP_OK); } - /** * Get the failed login response instance. * @@ -111,7 +107,6 @@ class LoginController extends Controller { return response()->json(['message' => 'unauthorised'], Response::HTTP_UNAUTHORIZED); } - /** * Redirect the user after determining they are locked out. @@ -128,7 +123,6 @@ class LoginController extends Controller return response()->json(['message' => Lang::get('auth.throttle', ['seconds' => $seconds])], Response::HTTP_TOO_MANY_REQUESTS); } - /** * Get the needed authorization credentials from the request. * @@ -139,13 +133,12 @@ class LoginController extends Controller { $credentials = [ $this->username() => strtolower($request->input($this->username())), - 'password' => $request->get('password'), + 'password' => $request->get('password'), ]; return $credentials; } - /** * The user has been authenticated. * @@ -160,4 +153,4 @@ class LoginController extends Controller Log::info('User authenticated'); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/PasswordController.php b/app/Http/Controllers/Auth/PasswordController.php index 1f490ca2..b2258d5f 100644 --- a/app/Http/Controllers/Auth/PasswordController.php +++ b/app/Http/Controllers/Auth/PasswordController.php @@ -2,8 +2,8 @@ namespace App\Http\Controllers\Auth; -use App\Http\Requests\UserPatchPwdRequest; use App\Http\Controllers\Controller; +use App\Http\Requests\UserPatchPwdRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; @@ -13,19 +13,20 @@ class PasswordController extends Controller /** * Update the user's password. * - * @param \App\Http\Requests\UserPatchPwdRequest $request + * @param \App\Http\Requests\UserPatchPwdRequest $request * @return \Illuminate\Http\JsonResponse */ public function update(UserPatchPwdRequest $request) { $validated = $request->validated(); - if (!Hash::check( $validated['currentPassword'], Auth::user()->password) ) { + if (! Hash::check($validated['currentPassword'], Auth::user()->password)) { Log::notice('Password update failed: wrong password provided'); + return response()->json(['message' => __('errors.wrong_current_password')], 400); } - if (!config('2fauth.config.isDemoApp') ) { + if (! config('2fauth.config.isDemoApp')) { $request->user()->update([ 'password' => bcrypt($validated['password']), ]); @@ -34,4 +35,4 @@ class PasswordController extends Controller return response()->json(['message' => __('auth.forms.password_successfully_changed')]); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index adfa3c3b..89f3e63d 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -2,12 +2,12 @@ namespace App\Http\Controllers\Auth; -use App\Models\User; -use App\Http\Requests\UserStoreRequest; use App\Http\Controllers\Controller; -use Illuminate\Support\Facades\Hash; +use App\Http\Requests\UserStoreRequest; +use App\Models\User; use Illuminate\Auth\Events\Registered; use Illuminate\Foundation\Auth\RegistersUsers; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; class RegisterController extends Controller @@ -25,7 +25,6 @@ class RegisterController extends Controller use RegistersUsers; - /** * Handle a registration request for the application. * @@ -42,11 +41,10 @@ class RegisterController extends Controller return response()->json([ 'message' => 'account created', - 'name' => $user->name, + 'name' => $user->name, ], 201); } - /** * Create a new user instance after a valid registration. * @@ -56,8 +54,8 @@ class RegisterController extends Controller protected function create(array $data) { return User::create([ - 'name' => $data['name'], - 'email' => $data['email'], + 'name' => $data['name'], + 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); } diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index 8aee96a4..aa1afd2d 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -19,5 +19,4 @@ class ResetPasswordController extends Controller */ use ResetsPasswords; - } diff --git a/app/Http/Controllers/Auth/UserController.php b/app/Http/Controllers/Auth/UserController.php index 1597058b..ab6a9497 100644 --- a/app/Http/Controllers/Auth/UserController.php +++ b/app/Http/Controllers/Auth/UserController.php @@ -2,37 +2,38 @@ namespace App\Http\Controllers\Auth; -use App\Http\Requests\UserUpdateRequest; -use App\Http\Requests\UserDeleteRequest; use App\Api\v1\Resources\UserResource; use App\Http\Controllers\Controller; -use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Hash; -use Illuminate\Support\Facades\DB; +use App\Http\Requests\UserDeleteRequest; +use App\Http\Requests\UserUpdateRequest; use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; class UserController extends Controller -{ +{ /** * Update the user's profile information. * - * @param \App\Http\Requests\UserUpdateRequest $request + * @param \App\Http\Requests\UserUpdateRequest $request * @return \App\Api\v1\Resources\UserResource|\Illuminate\Http\JsonResponse */ public function update(UserUpdateRequest $request) { - $user = $request->user(); + $user = $request->user(); $validated = $request->validated(); - if (!Hash::check( $request->password, Auth::user()->password) ) { + if (! Hash::check($request->password, Auth::user()->password)) { Log::notice('Account update failed: wrong password provided'); + return response()->json(['message' => __('errors.wrong_current_password')], 400); } - if (!config('2fauth.config.isDemoApp') ) { + if (! config('2fauth.config.isDemoApp')) { $user->update([ - 'name' => $validated['name'], + 'name' => $validated['name'], 'email' => $validated['email'], ]); } @@ -41,11 +42,10 @@ class UserController extends Controller return new UserResource($user); } - /** * Delete the user's account. * - * @param \App\Http\Requests\UserDeleteRequest $request + * @param \App\Http\Requests\UserDeleteRequest $request * @return \Illuminate\Http\JsonResponse */ public function delete(UserDeleteRequest $request) @@ -53,7 +53,7 @@ class UserController extends Controller Log::info('User deletion requested'); $validated = $request->validated(); - if (!Hash::check( $validated['password'], Auth::user()->password) ) { + if (! Hash::check($validated['password'], Auth::user()->password)) { return response()->json(['message' => __('errors.wrong_current_password')], 400); } @@ -79,6 +79,7 @@ class UserController extends Controller // @codeCoverageIgnoreStart catch (\Throwable $e) { Log::error('User deletion failed'); + return response()->json(['message' => __('errors.user_deletion_failed')], 400); } // @codeCoverageIgnoreEnd @@ -86,4 +87,4 @@ class UserController extends Controller return response()->json(null, 204); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/WebAuthnConfirmController.php b/app/Http/Controllers/Auth/WebAuthnConfirmController.php index 4477eeab..190360ee 100644 --- a/app/Http/Controllers/Auth/WebAuthnConfirmController.php +++ b/app/Http/Controllers/Auth/WebAuthnConfirmController.php @@ -27,4 +27,4 @@ // * @var string // */ // protected $redirectTo = RouteServiceProvider::HOME; -// } \ No newline at end of file +// } diff --git a/app/Http/Controllers/Auth/WebAuthnDeviceLostController.php b/app/Http/Controllers/Auth/WebAuthnDeviceLostController.php index 946fc038..b19faace 100644 --- a/app/Http/Controllers/Auth/WebAuthnDeviceLostController.php +++ b/app/Http/Controllers/Auth/WebAuthnDeviceLostController.php @@ -2,26 +2,25 @@ namespace App\Http\Controllers\Auth; -use App\Http\Controllers\Controller; -use Illuminate\Http\Request; -use Illuminate\Validation\ValidationException; use App\Extensions\WebauthnCredentialBroker; -use Illuminate\Foundation\Auth\ResetsPasswords; -use Illuminate\Support\Facades\Password; +use App\Http\Controllers\Controller; use App\Http\Requests\WebauthnDeviceLostRequest; +use Illuminate\Foundation\Auth\ResetsPasswords; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Password; +use Illuminate\Validation\ValidationException; class WebAuthnDeviceLostController extends Controller { use ResetsPasswords; - /** * Send a recovery email to the user. * - * @param \App\Http\Requests\WebauthnDeviceLostRequest $request + * @param \App\Http\Requests\WebauthnDeviceLostRequest $request * @param \App\Extensions\WebauthnCredentialBroker $broker - * * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse + * * @throws \Illuminate\Validation\ValidationException */ public function sendRecoveryEmail(WebauthnDeviceLostRequest $request, WebauthnCredentialBroker $broker) @@ -35,14 +34,13 @@ class WebAuthnDeviceLostController extends Controller : $this->sendRecoveryLinkFailedResponse($request, $response); } - /** * Get the response for a failed account recovery link. * * @param \Illuminate\Http\Request $request * @param string $response - * * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse + * * @throws \Illuminate\Validation\ValidationException */ protected function sendRecoveryLinkFailedResponse(Request $request, string $response) @@ -56,17 +54,15 @@ class WebAuthnDeviceLostController extends Controller ->withErrors(['email' => trans($response)]); } - /** * Get the response for a successful account recovery link. * * @param \Illuminate\Http\Request $request * @param string $response - * * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse */ protected function sendRecoveryLinkResponse(Request $request, string $response) { return response()->json(['message' => __('auth.webauthn.account_recovery_email_sent')]); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/WebAuthnLoginController.php b/app/Http/Controllers/Auth/WebAuthnLoginController.php index 50b5e5fb..ca519947 100644 --- a/app/Http/Controllers/Auth/WebAuthnLoginController.php +++ b/app/Http/Controllers/Auth/WebAuthnLoginController.php @@ -2,14 +2,14 @@ namespace App\Http\Controllers\Auth; -use App\Models\User; -use Illuminate\Http\JsonResponse; use App\Http\Controllers\Controller; +use App\Models\User; use Carbon\Carbon; -use Illuminate\Support\Facades\Log; -use Laragear\WebAuthn\Http\Requests\AssertionRequest; -use Laragear\WebAuthn\Http\Requests\AssertedRequest; use Illuminate\Contracts\Support\Responsable; +use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\Log; +use Laragear\WebAuthn\Http\Requests\AssertedRequest; +use Laragear\WebAuthn\Http\Requests\AssertionRequest; use Laragear\WebAuthn\WebAuthn; class WebAuthnLoginController extends Controller @@ -31,13 +31,13 @@ class WebAuthnLoginController extends Controller * @param \Laragear\WebAuthn\Http\Requests\AssertionRequest $request * @return \Illuminate\Contracts\Support\Responsable|\Illuminate\Http\JsonResponse */ - public function options(AssertionRequest $request): Responsable|JsonResponse + public function options(AssertionRequest $request) : Responsable|JsonResponse { switch (env('WEBAUTHN_USER_VERIFICATION')) { case WebAuthn::USER_VERIFICATION_DISCOURAGED: $request = $request->fastLogin(); // Makes the authenticator to only check for user presence on registration break; - case WebAuthn::USER_VERIFICATION_REQUIRED: + case WebAuthn::USER_VERIFICATION_REQUIRED: $request = $request->secureLogin(); // Makes the authenticator to always verify the user thoroughly on registration break; } @@ -50,10 +50,9 @@ class WebAuthnLoginController extends Controller return $user ? $request->toVerify($user) : response()->json([ - 'message' => 'no registered user' + 'message' => 'no registered user', ], 400); } - /** * Log the user in. @@ -70,28 +69,27 @@ class WebAuthnLoginController extends Controller // Some authenticators do not send a userHandle so we hack the response to be compliant // with Larapass/webauthn-lib implementation that waits for a userHandle - if(!$response['userHandle']) { + if (! $response['userHandle']) { $response['userHandle'] = User::getFromCredentialId($request->id)?->userHandle(); $request->merge(['response' => $response]); } } - + $user = $request->login(); if ($user) { $this->authenticated($user); + return response()->noContent(); } return response()->noContent(422); } - /** * The user has been authenticated. * * @param mixed $user - * * @return void|\Illuminate\Http\JsonResponse */ protected function authenticated($user) @@ -101,4 +99,4 @@ class WebAuthnLoginController extends Controller Log::info('User authenticated via webauthn'); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/WebAuthnManageController.php b/app/Http/Controllers/Auth/WebAuthnManageController.php index 017fc254..200a0499 100644 --- a/app/Http/Controllers/Auth/WebAuthnManageController.php +++ b/app/Http/Controllers/Auth/WebAuthnManageController.php @@ -4,16 +4,15 @@ namespace App\Http\Controllers\Auth; use App\Facades\Settings; use App\Http\Controllers\Controller; -use Illuminate\Http\Request; use App\Http\Requests\WebauthnRenameRequest; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class WebAuthnManageController extends Controller -{ - +{ /** * List all WebAuthn registered credentials - * + * * @return \Illuminate\Http\JsonResponse */ public function index(Request $request) @@ -23,12 +22,11 @@ class WebAuthnManageController extends Controller return response()->json($allUserCredentials, 200); } - /** * Rename a WebAuthn credential - * - * @param \App\Http\Requests\WebauthnRenameRequest $request - * @param string $credential + * + * @param \App\Http\Requests\WebauthnRenameRequest $request + * @param string $credential * @return \Illuminate\Http\JsonResponse */ public function rename(WebauthnRenameRequest $request, string $credential) @@ -38,17 +36,15 @@ class WebAuthnManageController extends Controller abort_if(! $request->user()->renameCredential($credential, $validated['name']), 404); return response()->json([ - 'name' => $validated['name'], - ], 200); + 'name' => $validated['name'], + ], 200); } - /** * Remove the specified credential from storage. - * + * * @param \Illuminate\Http\Request $request * @param string|array $credential - * * @return \Illuminate\Http\JsonResponse */ public function delete(Request $request, $credential) @@ -71,4 +67,4 @@ class WebAuthnManageController extends Controller return response()->json(null, 204); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/WebAuthnRecoveryController.php b/app/Http/Controllers/Auth/WebAuthnRecoveryController.php index 8f2ccad2..79f0eaa8 100644 --- a/app/Http/Controllers/Auth/WebAuthnRecoveryController.php +++ b/app/Http/Controllers/Auth/WebAuthnRecoveryController.php @@ -2,22 +2,21 @@ namespace App\Http\Controllers\Auth; -use App\Http\Controllers\Controller; -use App\Http\Requests\WebauthnRecoveryRequest; use App\Extensions\WebauthnCredentialBroker; use App\Facades\Settings; +use App\Http\Controllers\Controller; +use App\Http\Requests\WebauthnRecoveryRequest; use Illuminate\Auth\AuthenticationException; +use Illuminate\Foundation\Auth\ResetsPasswords; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Auth; -use Illuminate\Foundation\Auth\ResetsPasswords; use Illuminate\Support\Facades\Password; -use Illuminate\Support\Facades\App; +use Illuminate\Validation\ValidationException; class WebAuthnRecoveryController extends Controller { - use ResetsPasswords; + use ResetsPasswords; /** * Let the user regain access to his account using email+password by resetting @@ -25,8 +24,8 @@ class WebAuthnRecoveryController extends Controller * * @param \App\Http\Requests\WebauthnRecoveryRequest $request * @param \App\Extensions\WebauthnCredentialBroker $broker - * * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse + * * @throws \Illuminate\Validation\ValidationException */ public function recover(WebauthnRecoveryRequest $request, WebauthnCredentialBroker $broker) @@ -54,66 +53,57 @@ class WebAuthnRecoveryController extends Controller $user->flushCredentials(); } Settings::delete('useWebauthnOnly'); + } else { + throw new AuthenticationException(); } - else throw new AuthenticationException(); } ); - + return $response === Password::PASSWORD_RESET ? $this->sendRecoveryResponse($request, $response) : $this->sendRecoveryFailedResponse($request, $response); - } - /** * Check if the user has set to revoke all credentials. * * @param \App\Http\Requests\WebauthnRecoveryRequest $request - * * @return bool|mixed */ - protected function shouldRevokeAllCredentials(WebauthnRecoveryRequest $request): mixed + protected function shouldRevokeAllCredentials(WebauthnRecoveryRequest $request) : mixed { return filter_var($request->header('WebAuthn-Unique'), FILTER_VALIDATE_BOOLEAN) ?: $request->input('revokeAll', true); } - /** * Get the response for a successful account recovery. * * @param \Illuminate\Http\Request $request * @param string $response - * * @return \Illuminate\Http\JsonResponse - * */ - protected function sendRecoveryResponse(Request $request, string $response): JsonResponse + protected function sendRecoveryResponse(Request $request, string $response) : JsonResponse { return response()->json(['message' => __('auth.webauthn.webauthn_login_disabled')]); } - /** * Get the response for a failed account recovery. * * @param \Illuminate\Http\Request $request * @param string $response - * * @return \Illuminate\Http\JsonResponse + * * @throws \Illuminate\Validation\ValidationException - * */ - protected function sendRecoveryFailedResponse(Request $request, string $response): JsonResponse + protected function sendRecoveryFailedResponse(Request $request, string $response) : JsonResponse { switch ($response) { case Password::INVALID_TOKEN: throw ValidationException::withMessages(['token' => [__('auth.webauthn.invalid_reset_token')]]); - default: throw ValidationException::withMessages(['email' => [trans($response)]]); } - } } diff --git a/app/Http/Controllers/Auth/WebAuthnRegisterController.php b/app/Http/Controllers/Auth/WebAuthnRegisterController.php index 3ef32b42..16109f4a 100644 --- a/app/Http/Controllers/Auth/WebAuthnRegisterController.php +++ b/app/Http/Controllers/Auth/WebAuthnRegisterController.php @@ -17,13 +17,13 @@ class WebAuthnRegisterController extends Controller * @param \Laragear\WebAuthn\Http\Requests\AttestationRequest $request * @return \Illuminate\Contracts\Support\Responsable */ - public function options(AttestationRequest $request): Responsable + public function options(AttestationRequest $request) : Responsable { switch (env('WEBAUTHN_USER_VERIFICATION')) { case WebAuthn::USER_VERIFICATION_DISCOURAGED: $request = $request->fastRegistration(); // Makes the authenticator to only check for user presence on registration break; - case WebAuthn::USER_VERIFICATION_REQUIRED: + case WebAuthn::USER_VERIFICATION_REQUIRED: $request = $request->secureRegistration(); // Makes the authenticator to always verify the user thoroughly on registration break; } @@ -34,17 +34,16 @@ class WebAuthnRegisterController extends Controller ->toCreate(); } - /** * Registers a device for further WebAuthn authentication. * * @param \Laragear\WebAuthn\Http\Requests\AttestedRequest $request * @return \Illuminate\Http\Response */ - public function register(AttestedRequest $request): Response + public function register(AttestedRequest $request) : Response { $request->save(); return response()->noContent(); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 03e02a23..a0a2a8a3 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -2,10 +2,10 @@ namespace App\Http\Controllers; -use Illuminate\Foundation\Bus\DispatchesJobs; -use Illuminate\Routing\Controller as BaseController; -use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; +use Illuminate\Foundation\Bus\DispatchesJobs; +use Illuminate\Foundation\Validation\ValidatesRequests; +use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { diff --git a/app/Http/Controllers/SinglePageController.php b/app/Http/Controllers/SinglePageController.php index 08412b02..8e60eebc 100644 --- a/app/Http/Controllers/SinglePageController.php +++ b/app/Http/Controllers/SinglePageController.php @@ -2,16 +2,15 @@ namespace App\Http\Controllers; +use App\Events\ScanForNewReleaseCalled; use App\Facades\Settings; use Illuminate\Support\Facades\App; -use App\Events\ScanForNewReleaseCalled; class SinglePageController extends Controller { - - /** * return the main view + * * @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory */ public function index() @@ -20,14 +19,14 @@ class SinglePageController extends Controller return view('landing')->with([ 'appSettings' => Settings::all()->toJson(), - 'appConfig' => collect([ - 'proxyAuth' => config("auth.defaults.guard") === 'reverse-proxy-guard' ? true : false, - 'proxyLogoutUrl' => config("2fauth.config.proxyLogoutUrl") ? config("2fauth.config.proxyLogoutUrl") : false, + 'appConfig' => collect([ + 'proxyAuth' => config('auth.defaults.guard') === 'reverse-proxy-guard' ? true : false, + 'proxyLogoutUrl' => config('2fauth.config.proxyLogoutUrl') ? config('2fauth.config.proxyLogoutUrl') : false, ])->toJson(), - 'lang' => App::currentLocale(), - 'isDemoApp' => config("2fauth.config.isDemoApp") ? 'true' : 'false', - 'isTestingApp' => config("2fauth.config.isTestingApp") ? 'true' : 'false', - 'locales' => collect(config("2fauth.locales"))->toJson() /** @phpstan-ignore-line */ + 'lang' => App::currentLocale(), + 'isDemoApp' => config('2fauth.config.isDemoApp') ? 'true' : 'false', + 'isTestingApp' => config('2fauth.config.isTestingApp') ? 'true' : 'false', + 'locales' => collect(config('2fauth.locales'))->toJson(), /** @phpstan-ignore-line */ ]); } } diff --git a/app/Http/Controllers/SystemController.php b/app/Http/Controllers/SystemController.php index b12559ec..3ede122e 100644 --- a/app/Http/Controllers/SystemController.php +++ b/app/Http/Controllers/SystemController.php @@ -2,9 +2,8 @@ namespace App\Http\Controllers; -use App\Services\ReleaseRadarService; -use App\Http\Controllers\Controller; use App\Facades\Settings; +use App\Services\ReleaseRadarService; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; @@ -12,35 +11,35 @@ class SystemController extends Controller { /** * Get detailed information about the current installation - * + * * @return \Illuminate\Http\JsonResponse */ public function infos(Request $request) { - $infos = array(); - $infos['Date'] = date(DATE_RFC2822); - $infos['userAgent'] = $request->header('user-agent'); + $infos = []; + $infos['Date'] = date(DATE_RFC2822); + $infos['userAgent'] = $request->header('user-agent'); // App info - $infos['Version'] = config('2fauth.version'); - $infos['Environment'] = config('app.env'); - $infos['Debug'] = var_export(config('app.debug'), true); - $infos['Cache driver'] = config('cache.default'); - $infos['Log channel'] = config('logging.default'); - $infos['Log level'] = env('LOG_LEVEL'); - $infos['DB driver'] = DB::getDriverName(); + $infos['Version'] = config('2fauth.version'); + $infos['Environment'] = config('app.env'); + $infos['Debug'] = var_export(config('app.debug'), true); + $infos['Cache driver'] = config('cache.default'); + $infos['Log channel'] = config('logging.default'); + $infos['Log level'] = env('LOG_LEVEL'); + $infos['DB driver'] = DB::getDriverName(); // PHP info - $infos['PHP version'] = PHP_VERSION; - $infos['Operating system'] = PHP_OS; - $infos['interface'] = PHP_SAPI; + $infos['PHP version'] = PHP_VERSION; + $infos['Operating system'] = PHP_OS; + $infos['interface'] = PHP_SAPI; // Auth info if ($request->user()) { - $infos['Auth guard'] = config('auth.defaults.guard'); + $infos['Auth guard'] = config('auth.defaults.guard'); if ($infos['Auth guard'] === 'reverse-proxy-guard') { - $infos['Auth proxy header for user'] = config('auth.auth_proxy_headers.user'); + $infos['Auth proxy header for user'] = config('auth.auth_proxy_headers.user'); $infos['Auth proxy header for email'] = config('auth.auth_proxy_headers.email'); } $infos['webauthn user verification'] = config('larapass.login_verify'); - $infos['Trusted proxies'] = config('2fauth.trustedProxies') ?: 'none'; + $infos['Trusted proxies'] = config('2fauth.trustedProxies') ?: 'none'; } // User info if ($request->user()) { @@ -50,10 +49,9 @@ class SystemController extends Controller return response()->json($infos); } - /** * Get latest release - * + * * @return \Illuminate\Http\JsonResponse */ public function latestRelease(Request $request, ReleaseRadarService $releaseRadar) diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index a576431b..1929abaa 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -71,13 +71,13 @@ class Kernel extends HttpKernel * @var array */ protected $routeMiddleware = [ - 'auth' => \App\Http\Middleware\Authenticate::class, - 'guest' => \App\Http\Middleware\RejectIfAuthenticated::class, - 'SkipIfAuthenticated' => \App\Http\Middleware\SkipIfAuthenticated::class, - 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, - 'rejectIfDemoMode' => \App\Http\Middleware\RejectIfDemoMode::class, + 'auth' => \App\Http\Middleware\Authenticate::class, + 'guest' => \App\Http\Middleware\RejectIfAuthenticated::class, + 'SkipIfAuthenticated' => \App\Http\Middleware\SkipIfAuthenticated::class, + 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, + 'rejectIfDemoMode' => \App\Http\Middleware\RejectIfDemoMode::class, 'rejectIfReverseProxy' => \App\Http\Middleware\RejectIfReverseProxy::class, - 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, + 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, // 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, // 'signed' => \App\Http\Middleware\ValidateSignature::class, ]; diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index c104ac79..2cf0f778 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -20,9 +20,8 @@ class Authenticate extends Middleware if (empty($guards)) { // Will retreive the default guard $guards = [null]; - } - else { - // We replace routes guard by the reverse proxy guard if necessary + } else { + // We replace routes guard by the reverse proxy guard if necessary $proxyGuard = 'reverse-proxy-guard'; if (config('auth.defaults.guard') === $proxyGuard) { @@ -33,11 +32,11 @@ class Authenticate extends Middleware foreach ($guards as $guard) { if ($this->auth->guard($guard)->check()) { $this->auth->shouldUse($guard); + return; } } $this->unauthenticated($request, $guards); } - -} \ No newline at end of file +} diff --git a/app/Http/Middleware/CustomCreateFreshApiToken.php b/app/Http/Middleware/CustomCreateFreshApiToken.php index 2a80f624..7b540fa8 100644 --- a/app/Http/Middleware/CustomCreateFreshApiToken.php +++ b/app/Http/Middleware/CustomCreateFreshApiToken.php @@ -6,7 +6,6 @@ use Laravel\Passport\Http\Middleware\CreateFreshApiToken as CreateFreshApiToken; class CustomCreateFreshApiToken extends CreateFreshApiToken { - /** * Determine if the request should receive a fresh token. * @@ -15,6 +14,6 @@ class CustomCreateFreshApiToken extends CreateFreshApiToken */ protected function requestShouldReceiveFreshToken($request) { - return !is_null($request->user($this->guard)); + return ! is_null($request->user($this->guard)); } -} \ No newline at end of file +} diff --git a/app/Http/Middleware/ForceJsonResponse.php b/app/Http/Middleware/ForceJsonResponse.php index b05538eb..9f6fdb0d 100644 --- a/app/Http/Middleware/ForceJsonResponse.php +++ b/app/Http/Middleware/ForceJsonResponse.php @@ -16,7 +16,7 @@ class ForceJsonResponse public function handle($request, Closure $next) { $request->headers->set('Accept', 'application/json'); - + return $next($request); } -} \ No newline at end of file +} diff --git a/app/Http/Middleware/KickOutInactiveUser.php b/app/Http/Middleware/KickOutInactiveUser.php index 6588cb86..f402e63b 100644 --- a/app/Http/Middleware/KickOutInactiveUser.php +++ b/app/Http/Middleware/KickOutInactiveUser.php @@ -2,12 +2,12 @@ namespace App\Http\Middleware; -use Closure; +use App\Facades\Settings; use Carbon\Carbon; +use Closure; use Illuminate\Http\Response; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Log; -use App\Facades\Settings; class KickOutInactiveUser { @@ -16,7 +16,7 @@ class KickOutInactiveUser * * @param \Illuminate\Http\Request $request * @param \Closure $next - * @param string $guards + * @param string $guards * @return mixed */ public function handle($request, Closure $next, ...$guards) @@ -28,9 +28,9 @@ class KickOutInactiveUser if (Auth::guest() || $request->bearerToken() || config('auth.defaults.guard') === 'reverse-proxy-guard') { return $next($request); } - - $user = Auth::user(); - $now = Carbon::now(); + + $user = Auth::user(); + $now = Carbon::now(); $inactiveFor = $now->diffInSeconds(Carbon::parse($user->last_seen_at)); // Fetch all setting values @@ -38,18 +38,17 @@ class KickOutInactiveUser // If user has been inactive longer than the allowed inactivity period if ($kickUserAfterXSecond > 0 && $inactiveFor > $kickUserAfterXSecond) { - $user->last_seen_at = $now->format('Y-m-d H:i:s'); $user->save(); - + Log::info('Inactive user detected, authentication rejected'); if (method_exists('Illuminate\Support\Facades\Auth', 'logout')) { Auth::logout(); } - + return response()->json(['message' => 'inactivity detected'], Response::HTTP_I_AM_A_TEAPOT); } return $next($request); } -} \ No newline at end of file +} diff --git a/app/Http/Middleware/LogUserLastSeen.php b/app/Http/Middleware/LogUserLastSeen.php index 21d49358..3abf4aed 100644 --- a/app/Http/Middleware/LogUserLastSeen.php +++ b/app/Http/Middleware/LogUserLastSeen.php @@ -2,8 +2,8 @@ namespace App\Http\Middleware; -use Closure; use Carbon\Carbon; +use Closure; use Illuminate\Support\Facades\Auth; class LogUserLastSeen @@ -13,7 +13,7 @@ class LogUserLastSeen * * @param \Illuminate\Http\Request $request * @param \Closure $next - * @param string $guards + * @param string $guards * @return mixed */ public function handle($request, Closure $next, ...$guards) @@ -25,7 +25,7 @@ class LogUserLastSeen // - Guest // - User authenticated against a bearer token // - User authenticated via a reverse-proxy - if (Auth::guard($guard)->check() && !$request->bearerToken() && config('auth.defaults.guard') !== 'reverse-proxy-guard') { + if (Auth::guard($guard)->check() && ! $request->bearerToken() && config('auth.defaults.guard') !== 'reverse-proxy-guard') { Auth::guard($guard)->user()->last_seen_at = Carbon::now()->format('Y-m-d H:i:s'); Auth::guard($guard)->user()->save(); break; diff --git a/app/Http/Middleware/PreventRequestsDuringMaintenance.php b/app/Http/Middleware/PreventRequestsDuringMaintenance.php index 2edcdfea..e4956d0b 100644 --- a/app/Http/Middleware/PreventRequestsDuringMaintenance.php +++ b/app/Http/Middleware/PreventRequestsDuringMaintenance.php @@ -14,4 +14,4 @@ class PreventRequestsDuringMaintenance extends Middleware protected $except = [ // ]; -} \ No newline at end of file +} diff --git a/app/Http/Middleware/RejectIfAuthenticated.php b/app/Http/Middleware/RejectIfAuthenticated.php index 882badab..e59ea62d 100644 --- a/app/Http/Middleware/RejectIfAuthenticated.php +++ b/app/Http/Middleware/RejectIfAuthenticated.php @@ -22,7 +22,7 @@ class RejectIfAuthenticated foreach ($guards as $guard) { if (Auth::guard($guard)->check()) { - return response()->json(['message' => __('auth.already_authenticated')], 400); + return response()->json(['message' => __('auth.already_authenticated')], 400); } } diff --git a/app/Http/Middleware/RejectIfDemoMode.php b/app/Http/Middleware/RejectIfDemoMode.php index 4a1c2e3a..dd576329 100644 --- a/app/Http/Middleware/RejectIfDemoMode.php +++ b/app/Http/Middleware/RejectIfDemoMode.php @@ -17,8 +17,7 @@ class RejectIfDemoMode */ public function handle($request, Closure $next) { - - if( config('2fauth.config.isDemoApp') ) { + if (config('2fauth.config.isDemoApp')) { Log::info('Cannot request this action in Demo mode'); return response()->json(['message' => __('auth.forms.disabled_in_demo')], Response::HTTP_UNAUTHORIZED); diff --git a/app/Http/Middleware/RejectIfReverseProxy.php b/app/Http/Middleware/RejectIfReverseProxy.php index dc091c73..73a107fa 100644 --- a/app/Http/Middleware/RejectIfReverseProxy.php +++ b/app/Http/Middleware/RejectIfReverseProxy.php @@ -20,7 +20,8 @@ class RejectIfReverseProxy Log::info('Cannot request this action in Demo mode'); return response()->json([ - 'message' => __('errors.unsupported_with_reverseproxy')], 400); + 'message' => __('errors.unsupported_with_reverseproxy'), + ], 400); } return $next($request); diff --git a/app/Http/Middleware/SetLanguage.php b/app/Http/Middleware/SetLanguage.php index 4db2634b..47624d30 100644 --- a/app/Http/Middleware/SetLanguage.php +++ b/app/Http/Middleware/SetLanguage.php @@ -2,9 +2,9 @@ namespace App\Http\Middleware; +use App\Facades\Settings; use Closure; use Illuminate\Support\Facades\App; -use App\Facades\Settings; class SetLanguage { @@ -26,16 +26,17 @@ class SetLanguage // FI: Settings::get() always returns a fallback value $lang = Settings::get('lang'); - if($lang === 'browser') { - $lang = config('app.fallback_locale'); - $accepted = str_replace(' ', '', $request->header("Accept-Language")); + if ($lang === 'browser') { + $lang = config('app.fallback_locale'); + $accepted = str_replace(' ', '', $request->header('Accept-Language')); if ($accepted && $accepted !== '*') { $prefLocales = array_reduce( array_diff(explode(',', $accepted), ['*']), - function ($res, $el) { - list($l, $q) = array_merge(explode(';q=', $el), [1]); - $res[$l] = (float) $q; + function ($res, $el) { + [$l, $q] = array_merge(explode(';q=', $el), [1]); + $res[$l] = (float) $q; + return $res; }, [] diff --git a/app/Http/Middleware/SkipIfAuthenticated.php b/app/Http/Middleware/SkipIfAuthenticated.php index df172b0e..9f75d785 100644 --- a/app/Http/Middleware/SkipIfAuthenticated.php +++ b/app/Http/Middleware/SkipIfAuthenticated.php @@ -26,7 +26,7 @@ class SkipIfAuthenticated return response()->json([ 'message' => 'authenticated', - 'name' => $user + 'name' => $user, ], 200); } } diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 4f42db96..9e702260 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -19,8 +19,7 @@ class TrustProxies extends Middleware * * @var int */ - protected $headers = - Request::HEADER_X_FORWARDED_FOR | + protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | @@ -33,4 +32,4 @@ class TrustProxies extends Middleware { $this->proxies = (string) config('2fauth.config.trustedProxies'); } -} \ No newline at end of file +} diff --git a/app/Http/Requests/LoginRequest.php b/app/Http/Requests/LoginRequest.php index 54af7a2e..54a49f4a 100644 --- a/app/Http/Requests/LoginRequest.php +++ b/app/Http/Requests/LoginRequest.php @@ -2,10 +2,7 @@ namespace App\Http\Requests; -use Illuminate\Support\Facades\DB; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Validation\Rule; - class LoginRequest extends FormRequest { @@ -30,7 +27,7 @@ class LoginRequest extends FormRequest 'email' => [ 'required', 'email', - new \App\Rules\CaseInsensitiveEmailExists + new \App\Rules\CaseInsensitiveEmailExists, ], 'password' => 'required|string', ]; diff --git a/app/Http/Requests/UserDeleteRequest.php b/app/Http/Requests/UserDeleteRequest.php index d6326bbe..8aa9956d 100644 --- a/app/Http/Requests/UserDeleteRequest.php +++ b/app/Http/Requests/UserDeleteRequest.php @@ -5,7 +5,6 @@ namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; - class UserDeleteRequest extends FormRequest { /** diff --git a/app/Http/Requests/UserPatchPwdRequest.php b/app/Http/Requests/UserPatchPwdRequest.php index 59cbd3f1..dd3df1aa 100644 --- a/app/Http/Requests/UserPatchPwdRequest.php +++ b/app/Http/Requests/UserPatchPwdRequest.php @@ -26,7 +26,7 @@ class UserPatchPwdRequest extends FormRequest { return [ 'currentPassword' => 'required', - 'password' => 'required|confirmed|string|min:8', + 'password' => 'required|confirmed|string|min:8', ]; } -} \ No newline at end of file +} diff --git a/app/Http/Requests/UserStoreRequest.php b/app/Http/Requests/UserStoreRequest.php index 8974b66c..7c8f5f4f 100644 --- a/app/Http/Requests/UserStoreRequest.php +++ b/app/Http/Requests/UserStoreRequest.php @@ -24,9 +24,9 @@ class UserStoreRequest extends FormRequest public function rules() { return [ - 'name' => [new \App\Rules\FirstUser, 'required', 'string', 'max:255'], - 'email' => 'required|string|email|max:255', - 'password' => 'required|string|min:8|confirmed', + 'name' => [new \App\Rules\FirstUser, 'required', 'string', 'max:255'], + 'email' => 'required|string|email|max:255', + 'password' => 'required|string|min:8|confirmed', ]; } -} \ No newline at end of file +} diff --git a/app/Http/Requests/UserUpdateRequest.php b/app/Http/Requests/UserUpdateRequest.php index 1fa41546..b3562d00 100644 --- a/app/Http/Requests/UserUpdateRequest.php +++ b/app/Http/Requests/UserUpdateRequest.php @@ -25,9 +25,9 @@ class UserUpdateRequest extends FormRequest public function rules() { return [ - 'name' => 'required|string|max:255', - 'email' => 'required|string|email|max:255', + 'name' => 'required|string|max:255', + 'email' => 'required|string|email|max:255', 'password' => 'required', ]; } -} \ No newline at end of file +} diff --git a/app/Http/Requests/WebauthnDeviceLostRequest.php b/app/Http/Requests/WebauthnDeviceLostRequest.php index e8bcb090..3def47aa 100644 --- a/app/Http/Requests/WebauthnDeviceLostRequest.php +++ b/app/Http/Requests/WebauthnDeviceLostRequest.php @@ -3,7 +3,6 @@ namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Auth; class WebauthnDeviceLostRequest extends FormRequest { @@ -28,7 +27,7 @@ class WebauthnDeviceLostRequest extends FormRequest 'email' => [ 'required', 'email', - new \App\Rules\CaseInsensitiveEmailExists + new \App\Rules\CaseInsensitiveEmailExists, ], ]; } diff --git a/app/Http/Requests/WebauthnRecoveryRequest.php b/app/Http/Requests/WebauthnRecoveryRequest.php index e2d04dd9..7a043c8e 100644 --- a/app/Http/Requests/WebauthnRecoveryRequest.php +++ b/app/Http/Requests/WebauthnRecoveryRequest.php @@ -3,7 +3,6 @@ namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Auth; class WebauthnRecoveryRequest extends FormRequest { @@ -25,8 +24,8 @@ class WebauthnRecoveryRequest extends FormRequest public function rules() { return [ - 'token' => 'required', - 'email' => 'required|email', + 'token' => 'required', + 'email' => 'required|email', 'password' => 'required', ]; } diff --git a/app/Http/Requests/WebauthnRenameRequest.php b/app/Http/Requests/WebauthnRenameRequest.php index a59c3256..d2c11ccd 100644 --- a/app/Http/Requests/WebauthnRenameRequest.php +++ b/app/Http/Requests/WebauthnRenameRequest.php @@ -28,4 +28,4 @@ class WebauthnRenameRequest extends FormRequest 'name' => 'required|string', ]; } -} \ No newline at end of file +} diff --git a/app/Listeners/CleanIconStorage.php b/app/Listeners/CleanIconStorage.php index 86e736db..bcaaee4e 100644 --- a/app/Listeners/CleanIconStorage.php +++ b/app/Listeners/CleanIconStorage.php @@ -29,4 +29,4 @@ class CleanIconStorage Storage::disk('icons')->delete($event->twofaccount->icon ?? []); Log::info(sprintf('Icon cleaned for deleted TwoFAccount #%d', $event->twofaccount->id)); } -} \ No newline at end of file +} diff --git a/app/Listeners/DissociateTwofaccountFromGroup.php b/app/Listeners/DissociateTwofaccountFromGroup.php index 884b56f2..a9ab9d9b 100644 --- a/app/Listeners/DissociateTwofaccountFromGroup.php +++ b/app/Listeners/DissociateTwofaccountFromGroup.php @@ -2,8 +2,8 @@ namespace App\Listeners; -use App\Models\TwoFAccount; use App\Events\GroupDeleting; +use App\Models\TwoFAccount; use Illuminate\Support\Facades\Log; class DissociateTwofaccountFromGroup @@ -28,9 +28,9 @@ class DissociateTwofaccountFromGroup { TwoFAccount::where('group_id', $event->group->id) ->update( - ['group_id' => NULL] + ['group_id' => null] ); - + Log::info(sprintf('TwoFAccounts dissociated from group #%d', $event->group->id)); } } diff --git a/app/Listeners/ReleaseRadar.php b/app/Listeners/ReleaseRadar.php index a4b20f44..8c6ced87 100644 --- a/app/Listeners/ReleaseRadar.php +++ b/app/Listeners/ReleaseRadar.php @@ -4,22 +4,19 @@ namespace App\Listeners; use App\Events\ScanForNewReleaseCalled; use App\Services\ReleaseRadarService; -use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Log; class ReleaseRadar { /** - * @var ReleaseRadarService $releaseRadar + * @var ReleaseRadarService */ protected $releaseRadar; - /** * Create the event listener. - * - * @param \App\Services\ReleaseRadarService $releaseRadar * + * @param \App\Services\ReleaseRadarService $releaseRadar * @return void */ public function __construct(ReleaseRadarService $releaseRadar) @@ -27,7 +24,6 @@ class ReleaseRadar $this->releaseRadar = $releaseRadar; } - /** * Handle the event. * @@ -39,4 +35,4 @@ class ReleaseRadar $this->releaseRadar->scheduledScan(); Log::info('Scheduled release scan complete'); } -} \ No newline at end of file +} diff --git a/app/Models/Dto/HotpDto.php b/app/Models/Dto/HotpDto.php index 32e92bb9..d49885d1 100644 --- a/app/Models/Dto/HotpDto.php +++ b/app/Models/Dto/HotpDto.php @@ -6,4 +6,4 @@ class HotpDto extends OtpDto { /* @var integer */ public int $counter; -} \ No newline at end of file +} diff --git a/app/Models/Dto/OtpDto.php b/app/Models/Dto/OtpDto.php index 6c1745a3..f5628735 100644 --- a/app/Models/Dto/OtpDto.php +++ b/app/Models/Dto/OtpDto.php @@ -9,4 +9,4 @@ class OtpDto /* @var integer */ public string $otp_type; -} \ No newline at end of file +} diff --git a/app/Models/Dto/TotpDto.php b/app/Models/Dto/TotpDto.php index 377bb322..3300dd8d 100644 --- a/app/Models/Dto/TotpDto.php +++ b/app/Models/Dto/TotpDto.php @@ -9,4 +9,4 @@ class TotpDto extends OtpDto /* @var integer */ public int $period; -} \ No newline at end of file +} diff --git a/app/Models/Group.php b/app/Models/Group.php index 153e36c6..d40b7399 100644 --- a/app/Models/Group.php +++ b/app/Models/Group.php @@ -3,16 +3,15 @@ namespace App\Models; use App\Events\GroupDeleting; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Log; -use Illuminate\Database\Eloquent\Factories\HasFactory; /** * @property int $twofaccounts_count */ class Group extends Model { - use HasFactory; /** @@ -22,7 +21,6 @@ class Group extends Model */ protected $fillable = ['name']; - /** * The accessors to append to the model's array form. * @@ -30,7 +28,6 @@ class Group extends Model */ protected $appends = []; - /** * The attributes that should be hidden for arrays. * @@ -38,7 +35,6 @@ class Group extends Model */ protected $hidden = ['created_at', 'updated_at']; - /** * The attributes that should be cast. * @@ -48,7 +44,6 @@ class Group extends Model 'twofaccounts_count' => 'integer', ]; - /** * The event map for the model. * @@ -58,7 +53,6 @@ class Group extends Model 'deleting' => GroupDeleting::class, ]; - /** * Override The "booting" method of the model * @@ -75,10 +69,9 @@ class Group extends Model }); } - /** * Get the TwoFAccounts of the group. - * + * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function twofaccounts() diff --git a/app/Models/Option.php b/app/Models/Option.php index 2d335f78..ed3e70fe 100644 --- a/app/Models/Option.php +++ b/app/Models/Option.php @@ -4,7 +4,6 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; - class Option extends Model { /** @@ -17,7 +16,6 @@ class Option extends Model 'value', ]; - /** * Indicates if the model should be timestamped. * @@ -25,12 +23,10 @@ class Option extends Model */ public $timestamps = false; - /** * Casts. * * @var array */ protected $casts = []; - -} \ No newline at end of file +} diff --git a/app/Models/Traits/WebAuthnManageCredentials.php b/app/Models/Traits/WebAuthnManageCredentials.php index dcd51815..0507f9a7 100644 --- a/app/Models/Traits/WebAuthnManageCredentials.php +++ b/app/Models/Traits/WebAuthnManageCredentials.php @@ -2,9 +2,9 @@ namespace App\Models\Traits; -use Illuminate\Support\Str; use App\Notifications\WebauthnRecoveryNotification; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Support\Str; /** * @see \App\Models\WebAuthnAuthenticatable @@ -17,38 +17,36 @@ trait WebAuthnManageCredentials * * @return string */ - public function userHandle(): string + public function userHandle() : string { // Laragear\WebAuthn uses Ramsey\Uuid\Uuid::fromString()->getHex()->toString() // to obtain a UUID v4 with dashes removed and uses it as user_id (aka userHandle) // see https://github.com/ramsey/uuid/blob/4.x/src/Uuid.php#L379 // and Laragear\WebAuthn\Assertion\Validator\Pipes\CheckCredentialIsForUser::validateId() - + return $this->webAuthnCredentials()->value('user_id') ?? str_replace('-', '', Str::uuid()->toString()); } - /** * Saves a new alias for a given WebAuthn credential. * - * @param string $id - * @param string $alias + * @param string $id + * @param string $alias * @return bool */ - public function renameCredential(string $id, string $alias): bool + public function renameCredential(string $id, string $alias) : bool { return boolval($this->webAuthnCredentials()->whereKey($id)->update(['alias' => $alias])); } - /** * Removes one or more credentials previously registered. * * @param string|array $id * @return void */ - public function flushCredential($id): void + public function flushCredential($id) : void { if (! $this->relationLoaded('webAuthnCredentials')) { $this->webAuthnCredentials()->whereKey($id)->delete(); @@ -63,15 +61,13 @@ trait WebAuthnManageCredentials } } - /** * Sends a webauthn recovery email to the user. * * @param string $token - * * @return void */ - public function sendWebauthnRecoveryNotification(string $token): void + public function sendWebauthnRecoveryNotification(string $token) : void { // $accountRecoveryNotification = new WebauthnRecoveryNotification($token); // $accountRecoveryNotification->toMailUsing(null); @@ -92,6 +88,5 @@ trait WebAuthnManageCredentials // }); $this->notify(new WebauthnRecoveryNotification($token)); - } } diff --git a/app/Models/TwoFAccount.php b/app/Models/TwoFAccount.php index 1ed2d566..aa17756e 100644 --- a/app/Models/TwoFAccount.php +++ b/app/Models/TwoFAccount.php @@ -2,55 +2,62 @@ namespace App\Models; -use Exception; -use App\Services\LogoService; -use App\Facades\Settings; -use App\Models\Dto\TotpDto; -use App\Models\Dto\HotpDto; use App\Events\TwoFAccountDeleted; -use App\Exceptions\InvalidSecretException; use App\Exceptions\InvalidOtpParameterException; -use App\Exceptions\UnsupportedOtpTypeException; +use App\Exceptions\InvalidSecretException; use App\Exceptions\UndecipherableException; -use Illuminate\Validation\ValidationException; -use Spatie\EloquentSortable\Sortable; -use Spatie\EloquentSortable\SortableTrait; -use OTPHP\TOTP; -use OTPHP\HOTP; -use OTPHP\Factory; -use SteamTotp\SteamTotp; +use App\Exceptions\UnsupportedOtpTypeException; +use App\Facades\Settings; +use App\Helpers\Helpers; +use App\Models\Dto\HotpDto; +use App\Models\Dto\TotpDto; +use App\Services\LogoService; +use Exception; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; -use Illuminate\Support\Str; use Illuminate\Support\Arr; +use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Crypt; +use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; -use Illuminate\Database\Eloquent\Factories\HasFactory; +use Illuminate\Validation\ValidationException; +use OTPHP\Factory; +use OTPHP\HOTP; +use OTPHP\TOTP; use ParagonIE\ConstantTime\Base32; -use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Http; -use App\Helpers\Helpers; +use Spatie\EloquentSortable\Sortable; +use Spatie\EloquentSortable\SortableTrait; +use SteamTotp\SteamTotp; class TwoFAccount extends Model implements Sortable { - use SortableTrait, HasFactory; - const TOTP = 'totp'; - const HOTP = 'hotp'; + const TOTP = 'totp'; + + const HOTP = 'hotp'; + const STEAM_TOTP = 'steamtotp'; - const SHA1 = 'sha1'; - const MD5 = 'md5'; - const SHA256 = 'sha256'; - const SHA512 = 'sha512'; - + const SHA1 = 'sha1'; + + const MD5 = 'md5'; + + const SHA256 = 'sha256'; + + const SHA512 = 'sha512'; + const DEFAULT_PERIOD = 30; + const DEFAULT_COUNTER = 0; + const DEFAULT_DIGITS = 6; + const DEFAULT_ALGORITHM = self::SHA1; const DUPLICATE_ID = -1; + const FAKE_ID = -2; private const IMAGELINK_STORAGE_PATH = 'imagesLink/'; @@ -80,7 +87,6 @@ class TwoFAccount extends Model implements Sortable // 'icon' ]; - /** * The table associated with the model. * @@ -88,26 +94,23 @@ class TwoFAccount extends Model implements Sortable */ protected $table = 'twofaccounts'; - /** * The accessors to append to the model's array form. * * @var array */ public $appends = []; - - + /** - * The model's default values for attributes. - * - * @var array - */ + * The model's default values for attributes. + * + * @var array + */ protected $attributes = [ - 'digits' => 6, + 'digits' => 6, 'algorithm' => self::SHA1, ]; - /** * The attributes that should be hidden for arrays. * @@ -115,7 +118,6 @@ class TwoFAccount extends Model implements Sortable */ protected $hidden = []; - /** * The attributes that should be cast. * @@ -123,7 +125,6 @@ class TwoFAccount extends Model implements Sortable */ protected $casts = []; - /** * The event map for the model. * @@ -133,7 +134,6 @@ class TwoFAccount extends Model implements Sortable 'deleted' => TwoFAccountDeleted::class, ]; - /** * Override The "booting" method of the model * @@ -144,9 +144,15 @@ class TwoFAccount extends Model implements Sortable parent::boot(); static::saving(function (TwoFAccount $twofaccount) { - if (!$twofaccount->legacy_uri) $twofaccount->legacy_uri = $twofaccount->getURI(); - if ($twofaccount->otp_type == TwoFAccount::TOTP && !$twofaccount->period) $twofaccount->period = TwoFAccount::DEFAULT_PERIOD; - if ($twofaccount->otp_type == TwoFAccount::HOTP && !$twofaccount->counter) $twofaccount->counter = TwoFAccount::DEFAULT_COUNTER; + if (! $twofaccount->legacy_uri) { + $twofaccount->legacy_uri = $twofaccount->getURI(); + } + if ($twofaccount->otp_type == TwoFAccount::TOTP && ! $twofaccount->period) { + $twofaccount->period = TwoFAccount::DEFAULT_PERIOD; + } + if ($twofaccount->otp_type == TwoFAccount::HOTP && ! $twofaccount->counter) { + $twofaccount->counter = TwoFAccount::DEFAULT_COUNTER; + } }); // static::deleted(function ($model) { @@ -154,18 +160,16 @@ class TwoFAccount extends Model implements Sortable // }); } - /** * Settings for @spatie/eloquent-sortable package * * @var array */ public $sortable = [ - 'order_column_name' => 'order_column', + 'order_column_name' => 'order_column', 'sort_when_creating' => true, ]; - /** * The OTP generator. * Instanciated as null to keep the model light @@ -174,7 +178,6 @@ class TwoFAccount extends Model implements Sortable */ protected $generator = null; - /** * Get legacy_uri attribute * @@ -183,9 +186,9 @@ class TwoFAccount extends Model implements Sortable */ public function getLegacyUriAttribute($value) { - return $this->decryptOrReturn($value); } + /** * Set legacy_uri attribute * @@ -198,7 +201,6 @@ class TwoFAccount extends Model implements Sortable $this->attributes['legacy_uri'] = $this->encryptOrReturn($value); } - /** * Get account attribute * @@ -207,13 +209,13 @@ class TwoFAccount extends Model implements Sortable */ public function getAccountAttribute($value) { - return $this->decryptOrReturn($value); } + /** * Set account attribute * - * @param string $value + * @param string $value * @return void */ public function setAccountAttribute($value) @@ -222,7 +224,6 @@ class TwoFAccount extends Model implements Sortable $this->attributes['account'] = $this->encryptOrReturn($value); } - /** * Get secret attribute * @@ -231,13 +232,13 @@ class TwoFAccount extends Model implements Sortable */ public function getSecretAttribute($value) { - return $this->decryptOrReturn($value); } + /** * Set secret attribute * - * @param string $value + * @param string $value * @return void */ public function setSecretAttribute($value) @@ -246,47 +247,43 @@ class TwoFAccount extends Model implements Sortable $this->attributes['secret'] = $this->encryptOrReturn($value); } - /** * Set digits attribute * - * @param string $value + * @param string $value * @return void */ public function setDigitsAttribute($value) { - $this->attributes['digits'] = !$value ? 6 : $value; + $this->attributes['digits'] = ! $value ? 6 : $value; } - /** * Set algorithm attribute * - * @param string $value + * @param string $value * @return void */ public function setAlgorithmAttribute($value) { - $this->attributes['algorithm'] = !$value ? self::SHA1 : strtolower($value); + $this->attributes['algorithm'] = ! $value ? self::SHA1 : strtolower($value); } - /** * Set period attribute * - * @param string $value + * @param string $value * @return void */ public function setPeriodAttribute($value) { - $this->attributes['period'] = !$value && $this->otp_type === self::TOTP ? self::DEFAULT_PERIOD : $value; + $this->attributes['period'] = ! $value && $this->otp_type === self::TOTP ? self::DEFAULT_PERIOD : $value; } - /** * Set counter attribute * - * @param string $value + * @param string $value * @return void */ public function setCounterAttribute($value) @@ -294,19 +291,19 @@ class TwoFAccount extends Model implements Sortable $this->attributes['counter'] = blank($value) && $this->otp_type === self::HOTP ? self::DEFAULT_COUNTER : $value; } - /** * Returns a One-Time Password with its parameters - * + * + * @return TotpDto|HotpDto + * * @throws InvalidSecretException The secret is not a valid base32 encoded string * @throws UndecipherableException The secret cannot be deciphered * @throws UnsupportedOtpTypeException The defined OTP type is not supported * @throws InvalidOtpParameterException One OTP parameter is invalid - * @return TotpDto|HotpDto */ public function getOTP() { - Log::info(sprintf('OTP requested for TwoFAccount (%s)', $this->id ? 'id:'.$this->id: 'preview')); + Log::info(sprintf('OTP requested for TwoFAccount (%s)', $this->id ? 'id:' . $this->id : 'preview')); // Early exit if the model has an undecipherable secret if (strtolower($this->secret) === __('errors.indecipherable')) { @@ -316,38 +313,33 @@ class TwoFAccount extends Model implements Sortable } $this->initGenerator(); - - try { - if ( $this->otp_type === self::HOTP ) { - $OtpDto = new HotpDto(); - $OtpDto->otp_type = $this->otp_type; - $counter = $this->generator->getParameter('counter'); - $OtpDto->password = $this->generator->at($counter); - $OtpDto->counter = $this->counter = $counter + 1; + try { + if ($this->otp_type === self::HOTP) { + $OtpDto = new HotpDto(); + $OtpDto->otp_type = $this->otp_type; + $counter = $this->generator->getParameter('counter'); + $OtpDto->password = $this->generator->at($counter); + $OtpDto->counter = $this->counter = $counter + 1; // The updated HOTP counter must be saved to db for persisted account only if ($this->id) { $this->save(); } - } - else { - - $OtpDto = new TotpDto(); - $OtpDto->otp_type = $this->otp_type; - $OtpDto->generated_at = time(); - $OtpDto->password = $this->otp_type === self::TOTP + } else { + $OtpDto = new TotpDto(); + $OtpDto->otp_type = $this->otp_type; + $OtpDto->generated_at = time(); + $OtpDto->password = $this->otp_type === self::TOTP ? $this->generator->at($OtpDto->generated_at) : SteamTotp::getAuthCode(base64_encode(Base32::decodeUpper($this->secret))); - $OtpDto->period = $this->period; + $OtpDto->period = $this->period; } - Log::info(sprintf('New OTP generated for TwoFAccount (%s)', $this->id ? 'id:'.$this->id: 'preview')); - - return $OtpDto; + Log::info(sprintf('New OTP generated for TwoFAccount (%s)', $this->id ? 'id:' . $this->id : 'preview')); - } - catch (\Exception|\Throwable $ex) { + return $OtpDto; + } catch (\Exception|\Throwable $ex) { Log::error('An error occured, OTP generation aborted'); // Currently a secret issue is the only possible exception thrown by OTPHP for this stack // so it is Ok to send the corresponding 2FAuth exception. @@ -356,52 +348,50 @@ class TwoFAccount extends Model implements Sortable } } - /** * Fill the model using an array of OTP parameters. * Missing parameters will be set with default values - * + * * @return $this */ public function fillWithOtpParameters(array $parameters, bool $skipIconFetching = false) { - $this->otp_type = strtolower(Arr::get($parameters, 'otp_type')); - $this->account = Arr::get($parameters, 'account'); - $this->service = Arr::get($parameters, 'service'); - $this->icon = Arr::get($parameters, 'icon'); - $this->secret = Arr::get($parameters, 'secret'); - $this->algorithm = strtolower(Arr::get($parameters, 'algorithm', self::SHA1)); - $this->digits = Arr::get($parameters, 'digits', self::DEFAULT_DIGITS); - $this->period = Arr::get($parameters, 'period', $this->otp_type == self::TOTP ? self::DEFAULT_PERIOD : null); - $this->counter = Arr::get($parameters, 'counter', $this->otp_type == self::HOTP ? self::DEFAULT_COUNTER : null); + $this->otp_type = strtolower(Arr::get($parameters, 'otp_type')); + $this->account = Arr::get($parameters, 'account'); + $this->service = Arr::get($parameters, 'service'); + $this->icon = Arr::get($parameters, 'icon'); + $this->secret = Arr::get($parameters, 'secret'); + $this->algorithm = strtolower(Arr::get($parameters, 'algorithm', self::SHA1)); + $this->digits = Arr::get($parameters, 'digits', self::DEFAULT_DIGITS); + $this->period = Arr::get($parameters, 'period', $this->otp_type == self::TOTP ? self::DEFAULT_PERIOD : null); + $this->counter = Arr::get($parameters, 'counter', $this->otp_type == self::HOTP ? self::DEFAULT_COUNTER : null); $this->initGenerator(); // The generator could have been initialized without a secret, in that case it generates one on the fly. // The secret attribute has thus to be updated $this->secret = $this->secret ?: $this->generator->getSecret(); - + if ($this->otp_type === self::STEAM_TOTP || strtolower($this->service) === 'steam') { $this->enforceAsSteam(); } - if (!$this->icon && $skipIconFetching) { + if (! $this->icon && $skipIconFetching) { $this->icon = $this->getDefaultIcon(); } - if (!$this->icon && Settings::get('getOfficialIcons') && !$skipIconFetching) { + if (! $this->icon && Settings::get('getOfficialIcons') && ! $skipIconFetching) { $this->icon = $this->getDefaultIcon(); - } + } Log::info(sprintf('TwoFAccount filled with OTP parameters')); return $this; } - /** * Fill the model by parsing an otpauth URI - * + * * @return $this */ public function fillWithURI(string $uri, bool $isSteamTotp = false, bool $skipIconFetching = false) @@ -409,33 +399,32 @@ class TwoFAccount extends Model implements Sortable // First we instanciate the OTP generator try { $this->generator = Factory::loadFromProvisioningUri($uri); - } - catch (\Assert\AssertionFailedException|\Assert\InvalidArgumentException|\Exception|\Throwable $ex) { + } catch (\Assert\AssertionFailedException|\Assert\InvalidArgumentException|\Exception|\Throwable $ex) { throw ValidationException::withMessages([ - 'uri' => __('validation.custom.uri.regex', ['attribute' => 'uri']) + 'uri' => __('validation.custom.uri.regex', ['attribute' => 'uri']), ]); } // As loadFromProvisioningUri() accept URI without label (nor account nor service) we check // that the account is set - if ( ! $this->generator->getLabel() ) { + if (! $this->generator->getLabel()) { Log::error('URI passed to fillWithURI() must contain a label'); throw ValidationException::withMessages([ - 'label' => __('validation.custom.label.required') + 'label' => __('validation.custom.label.required'), ]); } - $this->otp_type = $this->getGeneratorOtpType(); - $this->account = $this->generator->getLabel(); - $this->secret = $this->generator->getSecret(); - $this->service = $this->generator->getIssuer(); - $this->algorithm = $this->generator->getDigest(); - $this->digits = $this->generator->getDigits(); - $this->period = $this->generator->hasParameter('period') ? $this->generator->getParameter('period') : null; - $this->counter = $this->generator->hasParameter('counter') ? $this->generator->getParameter('counter') : null; - $this->legacy_uri = $uri; - + $this->otp_type = $this->getGeneratorOtpType(); + $this->account = $this->generator->getLabel(); + $this->secret = $this->generator->getSecret(); + $this->service = $this->generator->getIssuer(); + $this->algorithm = $this->generator->getDigest(); + $this->digits = $this->generator->getDigits(); + $this->period = $this->generator->hasParameter('period') ? $this->generator->getParameter('period') : null; + $this->counter = $this->generator->hasParameter('counter') ? $this->generator->getParameter('counter') : null; + $this->legacy_uri = $uri; + if ($isSteamTotp || strtolower($this->service) === 'steam') { $this->enforceAsSteam(); } @@ -443,16 +432,15 @@ class TwoFAccount extends Model implements Sortable $this->icon = $this->storeImageAsIcon($this->generator->getParameter('image')); } - if (!$this->icon && Settings::get('getOfficialIcons') && !$skipIconFetching) { + if (! $this->icon && Settings::get('getOfficialIcons') && ! $skipIconFetching) { $this->icon = $this->getDefaultIcon(); - } + } Log::info(sprintf('TwoFAccount filled with an URI')); return $this; } - /** * Sets model attributes to STEAM values */ @@ -462,14 +450,13 @@ class TwoFAccount extends Model implements Sortable $this->digits = 5; $this->algorithm = self::SHA1; $this->period = 30; - + Log::info(sprintf('TwoFAccount configured as Steam account')); } - /** * Returns the OTP type of the instanciated OTP generator - * + * * @return mixed */ private function getGeneratorOtpType() @@ -477,7 +464,6 @@ class TwoFAccount extends Model implements Sortable return Arr::get($this->generatorClassMap, get_class($this->generator)); } - /** * Returns an otpauth URI built with model attribute values */ @@ -488,9 +474,9 @@ class TwoFAccount extends Model implements Sortable return $this->generator->getProvisioningUri(); } - /** * Instanciates the OTP generator with model attribute values + * * @throws UnsupportedOtpTypeException The defined OTP type is not supported * @throws InvalidOtpParameterException One OTP parameter is invalid */ @@ -519,77 +505,76 @@ class TwoFAccount extends Model implements Sortable $this->digits ?: self::DEFAULT_DIGITS ); break; - + default: throw new UnsupportedOtpTypeException(); } - if ($this->service) $this->generator->setIssuer($this->service); - if ($this->account) $this->generator->setLabel($this->account); - } - catch (UnsupportedOtpTypeException $exception) { + if ($this->service) { + $this->generator->setIssuer($this->service); + } + if ($this->account) { + $this->generator->setLabel($this->account); + } + } catch (UnsupportedOtpTypeException $exception) { Log::error(sprintf('%s is not an OTP type supported by the current generator', $this->otp_type)); throw $exception; - } - catch (\Exception|\Throwable $exception) { + } catch (\Exception|\Throwable $exception) { throw new InvalidOtpParameterException($exception->getMessage()); } } /** * Gets the image resource pointed by the image url and store it as an icon - * + * * @return string|null The filename of the stored icon or null if the operation fails */ private function storeImageAsIcon(string $url) { try { - $path_parts = pathinfo($url); - $newFilename = Helpers::getUniqueFilename($path_parts['extension']); //Str::random(40).'.'.$path_parts['extension']; - $imageFile = self::IMAGELINK_STORAGE_PATH . $newFilename; + $path_parts = pathinfo($url); + $newFilename = Helpers::getUniqueFilename($path_parts['extension']); + $imageFile = self::IMAGELINK_STORAGE_PATH . $newFilename; try { $response = Http::retry(3, 100)->get($url); - + if ($response->successful()) { Storage::disk('imagesLink')->put($newFilename, $response->body()); } - } - catch (\Exception $exception) { + } catch (\Exception $exception) { Log::error(sprintf('Cannot fetch imageLink at "%s"', $url)); } - if ( in_array(Storage::mimeType($imageFile), ['image/png', 'image/jpeg', 'image/webp', 'image/bmp']) - && getimagesize(storage_path() . '/app/' . $imageFile) ) - { + if (in_array(Storage::mimeType($imageFile), ['image/png', 'image/jpeg', 'image/webp', 'image/bmp']) + && getimagesize(storage_path() . '/app/' . $imageFile)) { // Should be a valid image, we move it to the icons disk if (Storage::disk('icons')->put($newFilename, Storage::disk('imagesLink')->get($newFilename))) { Storage::disk('imagesLink')->delete($newFilename); } - + Log::info(sprintf('Icon file %s stored', $newFilename)); - } - else { + } else { // @codeCoverageIgnoreStart Storage::disk('imagesLink')->delete($newFilename); throw new \Exception('Unsupported mimeType or missing image on storage'); // @codeCoverageIgnoreEnd } - + return $newFilename; } // @codeCoverageIgnoreStart catch (\Exception|\Throwable $ex) { Log::error(sprintf('Icon storage failed: %s', $ex->getMessage())); + return null; } // @codeCoverageIgnoreEnd } - /** * Fetch a logo in the tfa directory and store it as a new stand alone icon - * + * * @return string|null The icon */ private function getDefaultIcon() @@ -599,28 +584,23 @@ class TwoFAccount extends Model implements Sortable return Settings::get('getOfficialIcons') ? $logoService->getIcon($this->service) : null; } - /** * Returns an acceptable value */ private function decryptOrReturn(mixed $value) : mixed { // Decipher when needed - if ( Settings::get('useEncryption') && $value ) - { + if (Settings::get('useEncryption') && $value) { try { return Crypt::decryptString($value); - } - catch (Exception $ex) { + } catch (Exception $ex) { return __('errors.indecipherable'); } - } - else { + } else { return $value; } } - /** * Encrypt a value */ @@ -629,5 +609,4 @@ class TwoFAccount extends Model implements Sortable // should be replaced by laravel 8 attribute encryption casting return Settings::get('useEncryption') ? Crypt::encryptString($value) : $value; } - -} \ No newline at end of file +} diff --git a/app/Models/User.php b/app/Models/User.php index 0540452a..aa82c1bb 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,14 +2,14 @@ namespace App\Models; -use Illuminate\Auth\Notifications\ResetPassword; -use Illuminate\Notifications\Notifiable; -use Illuminate\Foundation\Auth\User as Authenticatable; -use Laravel\Passport\HasApiTokens; -use Illuminate\Support\Facades\Log; -use Illuminate\Database\Eloquent\Factories\HasFactory; -use Laragear\WebAuthn\WebAuthnAuthentication; use App\Models\Traits\WebAuthnManageCredentials; +use Illuminate\Auth\Notifications\ResetPassword; +use Illuminate\Database\Eloquent\Factories\HasFactory; +use Illuminate\Foundation\Auth\User as Authenticatable; +use Illuminate\Notifications\Notifiable; +use Illuminate\Support\Facades\Log; +use Laragear\WebAuthn\WebAuthnAuthentication; +use Laravel\Passport\HasApiTokens; class User extends Authenticatable implements WebAuthnAuthenticatable { @@ -53,27 +53,27 @@ class User extends Authenticatable implements WebAuthnAuthenticatable public function sendPasswordResetNotification($token) { $this->notify(new ResetPassword($token)); - + Log::info('Password reset token sent'); } /** * set Email attribute - * @param string $value + * + * @param string $value */ public function setEmailAttribute($value) : void { $this->attributes['email'] = strtolower($value); } - /** * Returns an WebAuthnAuthenticatable user from a given Credential ID. * * @param string $id * @return WebAuthnAuthenticatable|null */ - public static function getFromCredentialId(string $id): ?WebAuthnAuthenticatable + public static function getFromCredentialId(string $id) : ?WebAuthnAuthenticatable { return static::whereHas( 'webauthnCredentials', diff --git a/app/Models/WebAuthnAuthenticatable.php b/app/Models/WebAuthnAuthenticatable.php index f1d84a90..72f0f9ce 100644 --- a/app/Models/WebAuthnAuthenticatable.php +++ b/app/Models/WebAuthnAuthenticatable.php @@ -11,18 +11,16 @@ interface WebAuthnAuthenticatable extends Authenticatable * * @return string */ - public function userHandle(): string; - + public function userHandle() : string; /** * Saves a new alias for a given WebAuthn credential. * - * @param string $id - * @param string $alias + * @param string $id + * @param string $alias * @return bool */ - public function renameCredential(string $id, string $alias): bool; - + public function renameCredential(string $id, string $alias) : bool; /** * Removes one or more credentials previously registered. @@ -30,14 +28,13 @@ interface WebAuthnAuthenticatable extends Authenticatable * @param string|array $id * @return void */ - public function flushCredential($id): void; + public function flushCredential($id) : void; - /** * Sends a webauthn recovery email to the user. * * @param string $token * @return void */ - public function sendWebauthnRecoveryNotification(string $token): void; + public function sendWebauthnRecoveryNotification(string $token) : void; } diff --git a/app/Notifications/WebauthnRecoveryNotification.php b/app/Notifications/WebauthnRecoveryNotification.php index 9d239107..77a1883d 100644 --- a/app/Notifications/WebauthnRecoveryNotification.php +++ b/app/Notifications/WebauthnRecoveryNotification.php @@ -66,16 +66,16 @@ class WebauthnRecoveryNotification extends Notification // if (static::$createUrlCallback) { // $url = call_user_func(static::$createUrlCallback, $notifiable, $this->token); // } else { - $url = url( - route( - 'webauthn.recover', - [ - 'token' => $this->token, - 'email' => $notifiable->getEmailForPasswordReset(), - ], - false - ) - ); + $url = url( + route( + 'webauthn.recover', + [ + 'token' => $this->token, + 'email' => $notifiable->getEmailForPasswordReset(), + ], + false + ) + ); // } return (new MailMessage) diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index abda0e95..631a2af7 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,15 +2,14 @@ namespace App\Providers; +use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; -use Illuminate\Http\Resources\Json\JsonResource; use Laravel\Passport\Console\ClientCommand; use Laravel\Passport\Console\InstallCommand; use Laravel\Passport\Console\KeysCommand; - class AppServiceProvider extends ServiceProvider { /** diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 60d11dbb..c3a5b83a 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -2,16 +2,15 @@ namespace App\Providers; +use App\Extensions\RemoteUserProvider; +use App\Extensions\WebauthnCredentialBroker; +use App\Facades\Settings; +use App\Services\Auth\ReverseProxyGuard; +use Illuminate\Auth\Passwords\DatabaseTokenRepository; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Auth; -use App\Services\Auth\ReverseProxyGuard; -use App\Extensions\RemoteUserProvider; -use App\Facades\Settings; -use Illuminate\Support\Facades\Config; -use RuntimeException; -use App\Extensions\WebauthnCredentialBroker; -use Illuminate\Auth\Passwords\DatabaseTokenRepository; use Illuminate\Support\Str; +use RuntimeException; class AuthServiceProvider extends ServiceProvider { @@ -24,20 +23,19 @@ class AuthServiceProvider extends ServiceProvider // 'App\Models\Model' => 'App\Policies\ModelPolicy', ]; - /** * Register the service provider. * * @return void + * * @throws \Illuminate\Contracts\Container\BindingResolutionException */ - public function register(): void + public function register() : void { - $this->app->singleton( WebauthnCredentialBroker::class, static function ($app) { - if (!$config = $app['config']['auth.passwords.webauthn']) { + if (! $config = $app['config']['auth.passwords.webauthn']) { throw new RuntimeException('You must set the [webauthn] key broker in [auth] config.'); } @@ -62,7 +60,6 @@ class AuthServiceProvider extends ServiceProvider ); } - /** * Register any authentication / authorization services. * @@ -75,18 +72,17 @@ class AuthServiceProvider extends ServiceProvider // Register a custom provider for reverse-proxy authentication Auth::provider('remote-user', function ($app, array $config) { // Return an instance of Illuminate\Contracts\Auth\UserProvider... - + return new RemoteUserProvider; }); // Register a custom driver for reverse-proxy authentication - Auth::extend('reverse-proxy', function ($app, string $name, array $config) { + Auth::extend('reverse-proxy', function ($app, string $name, array $config) { // Return an instance of Illuminate\Contracts\Auth\Guard... return new ReverseProxyGuard(Auth::createUserProvider($config['provider'])); }); - // Previously we were using a custom user provider derived from the Larapass user provider // in order to honor the "useWebauthnOnly" user option. // Since Laragear\WebAuthn now replaces DarkGhostHunter\Larapass, the new approach is @@ -94,7 +90,7 @@ class AuthServiceProvider extends ServiceProvider // with a custom closure that uses the "useWebauthnOnly" user option Auth::provider( 'eloquent-webauthn', - static function (\Illuminate\Contracts\Foundation\Application $app, array $config): \Laragear\WebAuthn\Auth\WebAuthnUserProvider { + static function (\Illuminate\Contracts\Foundation\Application $app, array $config) : \Laragear\WebAuthn\Auth\WebAuthnUserProvider { return new \Laragear\WebAuthn\Auth\WebAuthnUserProvider( $app->make('hash'), $config['model'], @@ -104,11 +100,10 @@ class AuthServiceProvider extends ServiceProvider } ); - // Normally we should set the Passport routes here using Passport::routes(). // If so the passport routes would be set for both 'web' and 'api' middlewares without // possibility to exclude the web middleware (we can only pass additional middlewares to Passport::routes()) - // + // // The problem is that 2Fauth front-end uses the Laravel FreshApiToken to consum its API as a first party app. // So we have a laravel_token cookie added to each response to perform the authentication. // diff --git a/app/Providers/BroadcastServiceProvider.php b/app/Providers/BroadcastServiceProvider.php index 445733ad..33197f53 100644 --- a/app/Providers/BroadcastServiceProvider.php +++ b/app/Providers/BroadcastServiceProvider.php @@ -2,8 +2,8 @@ namespace App\Providers; -use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Broadcast; +use Illuminate\Support\ServiceProvider; class BroadcastServiceProvider extends ServiceProvider { diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 84d5e786..84ae555e 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -3,11 +3,11 @@ namespace App\Providers; use App\Events\GroupDeleting; -use App\Events\TwoFAccountDeleted; use App\Events\ScanForNewReleaseCalled; -use App\Listeners\ReleaseRadar; +use App\Events\TwoFAccountDeleted; use App\Listeners\CleanIconStorage; use App\Listeners\DissociateTwofaccountFromGroup; +use App\Listeners\ReleaseRadar; use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Listeners\SendEmailVerificationNotification; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; diff --git a/app/Providers/MigrationServiceProvider.php b/app/Providers/MigrationServiceProvider.php index caf133de..37aff68f 100644 --- a/app/Providers/MigrationServiceProvider.php +++ b/app/Providers/MigrationServiceProvider.php @@ -4,8 +4,8 @@ namespace App\Providers; use App\Factories\MigratorFactory; use App\Factories\MigratorFactoryInterface; -use App\Services\Migrators\GoogleAuthMigrator; use App\Services\Migrators\AegisMigrator; +use App\Services\Migrators\GoogleAuthMigrator; use App\Services\Migrators\PlainTextMigrator; use App\Services\Migrators\TwoFASMigrator; use Illuminate\Support\ServiceProvider; @@ -20,7 +20,7 @@ class MigrationServiceProvider extends ServiceProvider public function register() { $this->app->bind(MigratorFactoryInterface::class, MigratorFactory::class); - + $this->app->singleton(GoogleAuthMigrator::class, function () { return new GoogleAuthMigrator(); }); diff --git a/app/Providers/TwoFAuthServiceProvider.php b/app/Providers/TwoFAuthServiceProvider.php index 862be3ed..3322c184 100644 --- a/app/Providers/TwoFAuthServiceProvider.php +++ b/app/Providers/TwoFAuthServiceProvider.php @@ -2,13 +2,13 @@ namespace App\Providers; -use App\Services\LogoService; -use App\Services\SettingService; -use App\Services\ReleaseRadarService; -use App\Services\TwoFAccountService; use App\Factories\MigratorFactoryInterface; -use Illuminate\Support\ServiceProvider; +use App\Services\LogoService; +use App\Services\ReleaseRadarService; +use App\Services\SettingService; +use App\Services\TwoFAccountService; use Illuminate\Contracts\Support\DeferrableProvider; +use Illuminate\Support\ServiceProvider; class TwoFAuthServiceProvider extends ServiceProvider implements DeferrableProvider { @@ -44,8 +44,7 @@ class TwoFAuthServiceProvider extends ServiceProvider implements DeferrableProvi public function boot() { // - } - + } /** * Get the services provided by the provider. diff --git a/app/Rules/CaseInsensitiveEmailExists.php b/app/Rules/CaseInsensitiveEmailExists.php index c88e7fea..df15137b 100644 --- a/app/Rules/CaseInsensitiveEmailExists.php +++ b/app/Rules/CaseInsensitiveEmailExists.php @@ -30,12 +30,14 @@ class CaseInsensitiveEmailExists implements Rule ->whereRaw('email = \'' . strtolower($value) . '\'' . ('sqlite' === config('database.default') ? ' COLLATE NOCASE' : '')) ->first(); - return !$user ? false : true; + return ! $user ? false : true; } /** * Get the validation error message. + * * @codeCoverageIgnore + * * @return array|string */ public function message() diff --git a/app/Services/Auth/ReverseProxyGuard.php b/app/Services/Auth/ReverseProxyGuard.php index 6d2bbea2..1f2dbab2 100644 --- a/app/Services/Auth/ReverseProxyGuard.php +++ b/app/Services/Auth/ReverseProxyGuard.php @@ -5,9 +5,9 @@ namespace App\Services\Auth; +use Illuminate\Auth\GuardHelpers; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\UserProvider; -use Illuminate\Auth\GuardHelpers; use Illuminate\Support\Facades\Log; class ReverseProxyGuard implements Guard @@ -24,7 +24,7 @@ class ReverseProxyGuard implements Guard /** * Create a new authentication guard. * - * @param \Illuminate\Contracts\Auth\UserProvider $provider + * @param \Illuminate\Contracts\Auth\UserProvider $provider * @return void */ public function __construct(UserProvider $provider) @@ -33,7 +33,7 @@ class ReverseProxyGuard implements Guard } /** - * @inheritDoc + * {@inheritDoc} */ public function user() { @@ -47,17 +47,17 @@ class ReverseProxyGuard implements Guard // Get the user identifier from $_SERVER or apache filtered headers $remoteUserHeader = config('auth.auth_proxy_headers.user'); $remoteUserHeader = $remoteUserHeader ?: 'REMOTE_USER'; - $identifier = array(); + $identifier = []; try { $identifier['user'] = request()->server($remoteUserHeader) ?? apache_request_headers()[$remoteUserHeader] ?? null; - } - catch (\Throwable $e) { + } catch (\Throwable $e) { $identifier['user'] = null; } - if (!$identifier['user'] || is_array($identifier['user'])) { + if (! $identifier['user'] || is_array($identifier['user'])) { Log::error(sprintf('Proxy remote-user header "%s" is empty or missing.', $remoteUserHeader)); + return $this->user = null; } @@ -66,9 +66,8 @@ class ReverseProxyGuard implements Guard if ($remoteEmailHeader) { try { - $remoteEmail = (string)(request()->server($remoteEmailHeader) ?? apache_request_headers()[$remoteEmailHeader] ?? null); - } - catch (\Throwable $e) { + $remoteEmail = (string) (request()->server($remoteEmailHeader) ?? apache_request_headers()[$remoteEmailHeader] ?? null); + } catch (\Throwable $e) { $remoteEmail = null; } @@ -85,7 +84,7 @@ class ReverseProxyGuard implements Guard * * @param array $credentials * @return bool - * + * * @codeCoverageIgnore */ public function validate(array $credentials = []) diff --git a/app/Services/GroupService.php b/app/Services/GroupService.php index d1f29776..7a2980bb 100644 --- a/app/Services/GroupService.php +++ b/app/Services/GroupService.php @@ -2,18 +2,17 @@ namespace App\Services; +use App\Facades\Settings; use App\Models\Group; use App\Models\TwoFAccount; -use App\Facades\Settings; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\Log; -use Illuminate\Support\Facades\App; class GroupService { /** * Returns all existing groups - * + * * @return Collection */ public static function getAll() : Collection @@ -23,26 +22,25 @@ class GroupService // // This pseudo group contains all twofaccounts regardless // of the user created group they belong to. - + // Get the user created groups $groups = Group::withCount('twofaccounts')->get(); // Create the pseudo group $allGroup = new Group([ - 'name' => __('commons.all') + 'name' => __('commons.all'), ]); - $allGroup->id = 0; + $allGroup->id = 0; $allGroup->twofaccounts_count = TwoFAccount::count(); return $groups->prepend($allGroup); } - /** * Creates a group - * - * @param array $data + * + * @param array $data * @return \App\Models\Group The created group */ public static function create(array $data) : Group @@ -58,12 +56,11 @@ class GroupService return $group; } - /** * Updates a group using a list of parameters - * - * @param \App\Models\Group $group The group - * @param array $data The parameters + * + * @param \App\Models\Group $group The group + * @param array $data The parameters * @return \App\Models\Group The updated group */ public static function update(Group $group, array $data) : Group @@ -77,11 +74,10 @@ class GroupService return $group; } - /** * Deletes one or more groups - * - * @param int|array $ids group ids to delete + * + * @param int|array $ids group ids to delete * @return int The number of deleted */ public static function delete($ids) : int @@ -112,25 +108,24 @@ class GroupService return $deleted; } - /** * Assign one or more accounts to a group - * - * @param array|int $ids accounts ids to assign - * @param \App\Models\Group $group The target group + * + * @param array|int $ids accounts ids to assign + * @param \App\Models\Group $group The target group * @return void */ public static function assign($ids, Group $group = null) : void { - if (!$group) { + if (! $group) { $group = self::defaultGroup(); } if ($group) { // saveMany() expect an iterable so we pass an array to // find() to always obtain a list of TwoFAccount - if (!is_array($ids)) { - $ids = array($ids); + if (! is_array($ids)) { + $ids = [$ids]; } $twofaccounts = TwoFAccount::find($ids); @@ -138,15 +133,15 @@ class GroupService $group->loadCount('twofaccounts'); Log::info(sprintf('Twofaccounts #%s assigned to groups %s', implode(',#', $ids), var_export($group->name, true))); + } else { + Log::info('Cannot find a group to assign the TwoFAccounts to'); } - else Log::info('Cannot find a group to assign the TwoFAccounts to'); } - /** * Finds twofaccounts assigned to the group - * - * @param \App\Models\Group $group The group + * + * @param \App\Models\Group $group The group * @return Collection The assigned accounts */ public static function getAccounts(Group $group) : Collection @@ -156,10 +151,9 @@ class GroupService return $twofaccounts; } - /** * Determines the destination group - * + * * @return \App\Models\Group|null The group or null if it does not exist */ private static function defaultGroup() @@ -168,4 +162,4 @@ class GroupService return Group::find($id); } -} \ No newline at end of file +} diff --git a/app/Services/LogoService.php b/app/Services/LogoService.php index 25ccfe11..8ba8a475 100644 --- a/app/Services/LogoService.php +++ b/app/Services/LogoService.php @@ -4,8 +4,8 @@ namespace App\Services; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; class LogoService @@ -25,17 +25,15 @@ class LogoService */ const TFA_URL = 'https://2fa.directory/api/v3/tfa.json'; - public function __construct() { $this->setTfaCollection(); } - /** * Fetch a logo for the given service and save it as an icon - * - * @param string $serviceName Name of the service to fetch a logo for + * + * @param string $serviceName Name of the service to fetch a logo for * @return string|null The icon filename or null if no logo has been found */ public function getIcon($serviceName) @@ -43,35 +41,35 @@ class LogoService $logoFilename = $this->getLogo(strval($serviceName)); if ($logoFilename) { - $iconFilename = Str::random(40).'.svg'; - return $this->copyToIcons($logoFilename, $iconFilename) ? $iconFilename : null; - } - else return null; - } + $iconFilename = Str::random(40) . '.svg'; + return $this->copyToIcons($logoFilename, $iconFilename) ? $iconFilename : null; + } else { + return null; + } + } /** * Return the logo's filename for a given service - * - * @param string $serviceName Name of the service to fetch a logo for + * + * @param string $serviceName Name of the service to fetch a logo for * @return string|null The logo filename or null if no logo has been found */ protected function getLogo($serviceName) { - $domain = $this->tfas->get($this->cleanDomain(strval($serviceName))); - $logoFilename = $domain.'.svg'; + $domain = $this->tfas->get($this->cleanDomain(strval($serviceName))); + $logoFilename = $domain . '.svg'; - if ($domain && !Storage::disk('logos')->exists($logoFilename)) { + if ($domain && ! Storage::disk('logos')->exists($logoFilename)) { $this->fetchLogo($logoFilename); } return Storage::disk('logos')->exists($logoFilename) ? $logoFilename : null; } - /** * Build and set the TFA directoy collection - * + * * @return void */ protected function setTfaCollection() : void @@ -82,7 +80,7 @@ class LogoService $this->cacheTfaDirectorySource(); } } else { - $this->cacheTfaDirectorySource(); + $this->cacheTfaDirectorySource(); } $this->tfas = Storage::disk('logos')->exists(self::TFA_JSON) @@ -90,10 +88,9 @@ class LogoService : collect([]); } - /** * Fetch and cache fresh TFA.Directory data using the https://2fa.directory API - * + * * @return void */ protected function cacheTfaDirectorySource() : void @@ -104,50 +101,44 @@ class LogoService $coll = collect(json_decode(htmlspecialchars_decode($response->body()), true)) /** @phpstan-ignore-line */ ->mapWithKeys(function ($item, $key) { return [ - strtolower(head($item)) => $item[1]["domain"] + strtolower(head($item)) => $item[1]['domain'], ]; }); Storage::disk('logos')->put(self::TFA_JSON, $coll->toJson()) ? Log::info('Fresh tfa.json saved to logos dir') : Log::notice('Cannot save tfa.json to logos dir'); - - } - catch (\Exception $e) { + } catch (\Exception $e) { Log::error('Caching of tfa.json failed'); } - } - /** * Fetch and cache a logo from 2fa.Directory repository - * - * @param string $logoFile Logo filename to fetch + * + * @param string $logoFile Logo filename to fetch * @return void */ protected function fetchLogo(string $logoFile) : void { try { $response = Http::retry(3, 100) - ->get('https://raw.githubusercontent.com/2factorauth/twofactorauth/master/img/'.$logoFile[0].'/'.$logoFile); - + ->get('https://raw.githubusercontent.com/2factorauth/twofactorauth/master/img/' . $logoFile[0] . '/' . $logoFile); + if ($response->successful()) { Storage::disk('logos')->put($logoFile, $response->body()) ? Log::info(sprintf('Logo "%s" saved to logos dir.', $logoFile)) : Log::notice(sprintf('Cannot save logo "%s" to logos dir', $logoFile)); } - } - catch (\Exception $exception) { + } catch (\Exception $exception) { Log::error(sprintf('Fetching of logo "%s" failed.', $logoFile)); } } - /** * Prepare and make some replacement to optimize logo fetching - * - * @param string $domain + * + * @param string $domain * @return string Optimized domain name */ protected function cleanDomain(string $domain) : string @@ -155,16 +146,15 @@ class LogoService return strtolower(str_replace(['+'], ['plus'], $domain)); } - /** * Copy a logo file to the icons disk with a new name - * - * @param string $logoFilename - * @param string $iconFilename + * + * @param string $logoFilename + * @param string $iconFilename * @return bool Weither the copy succed or not */ protected function copyToIcons($logoFilename, $iconFilename) : bool { return Storage::disk('icons')->put($iconFilename, Storage::disk('logos')->get($logoFilename)); } -} \ No newline at end of file +} diff --git a/app/Services/Migrators/AegisMigrator.php b/app/Services/Migrators/AegisMigrator.php index 76fb5346..66b30189 100644 --- a/app/Services/Migrators/AegisMigrator.php +++ b/app/Services/Migrators/AegisMigrator.php @@ -2,15 +2,14 @@ namespace App\Services\Migrators; -use App\Services\Migrators\Migrator; -use Illuminate\Support\Collection; -use App\Models\TwoFAccount; -use Illuminate\Support\Facades\Log; -use Illuminate\Support\Arr; use App\Exceptions\InvalidMigrationDataException; -use Illuminate\Support\Facades\Storage; -use App\Helpers\Helpers; use App\Facades\TwoFAccounts; +use App\Helpers\Helpers; +use App\Models\TwoFAccount; +use Illuminate\Support\Arr; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Storage; class AegisMigrator extends Migrator { @@ -33,7 +32,6 @@ class AegisMigrator extends Migrator // } // } - /** * Convert migration data to a TwoFAccounts collection. * @@ -49,19 +47,18 @@ class AegisMigrator extends Migrator throw new InvalidMigrationDataException('Aegis'); } - $twofaccounts = array(); + $twofaccounts = []; foreach ($json['db']['entries'] as $key => $otp_parameters) { - - $parameters = array(); - $parameters['otp_type'] = $otp_parameters['type'] == 'steam' ? TwoFAccount::STEAM_TOTP : $otp_parameters['type']; - $parameters['service'] = $otp_parameters['issuer']; - $parameters['account'] = $otp_parameters['name']; - $parameters['secret'] = $this->padToValidBase32Secret($otp_parameters['info']['secret']); - $parameters['algorithm'] = $otp_parameters['info']['algo']; - $parameters['digits'] = $otp_parameters['info']['digits']; - $parameters['counter'] = $otp_parameters['info']['counter'] ?? null; - $parameters['period'] = $otp_parameters['info']['period'] ?? null; + $parameters = []; + $parameters['otp_type'] = $otp_parameters['type'] == 'steam' ? TwoFAccount::STEAM_TOTP : $otp_parameters['type']; + $parameters['service'] = $otp_parameters['issuer']; + $parameters['account'] = $otp_parameters['name']; + $parameters['secret'] = $this->padToValidBase32Secret($otp_parameters['info']['secret']); + $parameters['algorithm'] = $otp_parameters['info']['algo']; + $parameters['digits'] = $otp_parameters['info']['digits']; + $parameters['counter'] = $otp_parameters['info']['counter'] ?? null; + $parameters['period'] = $otp_parameters['info']['period'] ?? null; try { // Aegis supports 3 image extensions for icons @@ -80,7 +77,7 @@ class AegisMigrator extends Migrator case 'image/jpeg': $extension = 'jpg'; break; - + default: throw new \Exception(); } @@ -92,29 +89,26 @@ class AegisMigrator extends Migrator Log::info(sprintf('Image %s successfully stored for import', $filename)); } } - } - catch (\Exception) { + } catch (\Exception) { // we do nothing } try { - $twofaccounts[$key] = new TwoFAccount; - $twofaccounts[$key]->fillWithOtpParameters($parameters); - } - catch (\Exception $exception) { - + $twofaccounts[$key] = new TwoFAccount; + $twofaccounts[$key]->fillWithOtpParameters($parameters); + } catch (\Exception $exception) { Log::error(sprintf('Cannot instanciate a TwoFAccount object with OTP parameters from imported item #%s', $key)); Log::error($exception->getMessage()); // The token failed to generate a valid account so we create a fake account to be returned. - $fakeAccount = new TwoFAccount(); - $fakeAccount->id = TwoFAccount::FAKE_ID; - $fakeAccount->otp_type = $otp_parameters['type'] ?? TwoFAccount::TOTP; + $fakeAccount = new TwoFAccount(); + $fakeAccount->id = TwoFAccount::FAKE_ID; + $fakeAccount->otp_type = $otp_parameters['type'] ?? TwoFAccount::TOTP; // Only basic fields are filled to limit the risk of another exception. - $fakeAccount->account = $otp_parameters['name'] ?? __('twofaccounts.import.invalid_account'); - $fakeAccount->service = $otp_parameters['issuer'] ?? __('twofaccounts.import.invalid_service'); + $fakeAccount->account = $otp_parameters['name'] ?? __('twofaccounts.import.invalid_account'); + $fakeAccount->service = $otp_parameters['issuer'] ?? __('twofaccounts.import.invalid_service'); // The secret field is used to pass the error, not very clean but will do the job for now. - $fakeAccount->secret = $exception->getMessage(); + $fakeAccount->secret = $exception->getMessage(); $twofaccounts[$key] = $fakeAccount; } diff --git a/app/Services/Migrators/GoogleAuthMigrator.php b/app/Services/Migrators/GoogleAuthMigrator.php index 2907afcf..a69e3272 100644 --- a/app/Services/Migrators/GoogleAuthMigrator.php +++ b/app/Services/Migrators/GoogleAuthMigrator.php @@ -2,26 +2,24 @@ namespace App\Services\Migrators; -use Exception; +use App\Exceptions\InvalidMigrationDataException; use App\Models\TwoFAccount; -use App\Services\Migrators\Migrator; -use Illuminate\Support\Collection; -use ParagonIE\ConstantTime\Base32; use App\Protobuf\GAuthValueMapping; use App\Protobuf\GoogleAuth\Payload; -use App\Protobuf\GoogleAuth\Payload\OtpType; use App\Protobuf\GoogleAuth\Payload\Algorithm; use App\Protobuf\GoogleAuth\Payload\DigitCount; -use App\Exceptions\InvalidMigrationDataException; +use App\Protobuf\GoogleAuth\Payload\OtpType; +use Exception; +use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; +use ParagonIE\ConstantTime\Base32; class GoogleAuthMigrator extends Migrator { - /** * Convert Google Authenticator migration URI to a set of TwoFAccount objects. - * + * * @param mixed $migrationPayload migration uri provided by Google Authenticator export feature * @return \Illuminate\Support\Collection The converted accounts */ @@ -29,49 +27,45 @@ class GoogleAuthMigrator extends Migrator { try { $migrationData = base64_decode(urldecode(Str::replace('otpauth-migration://offline?data=', '', $migrationPayload))); - $protobuf = new Payload(); + $protobuf = new Payload(); $protobuf->mergeFromString($migrationData); $otpParameters = $protobuf->getOtpParameters(); - } - catch (Exception $ex) { - Log::error("Protobuf failed to get OTP parameters from provided migration URI"); + } catch (Exception $ex) { + Log::error('Protobuf failed to get OTP parameters from provided migration URI'); Log::error($ex->getMessage()); throw new InvalidMigrationDataException('Google Authenticator'); } - $twofaccounts = array(); - - foreach ($otpParameters->getIterator() as $key => $otp_parameters) { + $twofaccounts = []; - try { - $parameters = array(); - $parameters['otp_type'] = GAuthValueMapping::OTP_TYPE[OtpType::name($otp_parameters->getType())]; - $parameters['service'] = $otp_parameters->getIssuer(); - $parameters['account'] = str_replace($parameters['service'].':', '', $otp_parameters->getName()); - $parameters['secret'] = Base32::encodeUpper($otp_parameters->getSecret()); - $parameters['algorithm'] = GAuthValueMapping::ALGORITHM[Algorithm::name($otp_parameters->getAlgorithm())]; - $parameters['digits'] = GAuthValueMapping::DIGIT_COUNT[DigitCount::name($otp_parameters->getDigits())]; - $parameters['counter'] = $parameters['otp_type'] === TwoFAccount::HOTP ? $otp_parameters->getCounter() : null; - $parameters['period'] = $parameters['otp_type'] === TwoFAccount::TOTP ? $otp_parameters->getPeriod() : null; + foreach ($otpParameters->getIterator() as $key => $otp_parameters) { + try { + $parameters = []; + $parameters['otp_type'] = GAuthValueMapping::OTP_TYPE[OtpType::name($otp_parameters->getType())]; + $parameters['service'] = $otp_parameters->getIssuer(); + $parameters['account'] = str_replace($parameters['service'] . ':', '', $otp_parameters->getName()); + $parameters['secret'] = Base32::encodeUpper($otp_parameters->getSecret()); + $parameters['algorithm'] = GAuthValueMapping::ALGORITHM[Algorithm::name($otp_parameters->getAlgorithm())]; + $parameters['digits'] = GAuthValueMapping::DIGIT_COUNT[DigitCount::name($otp_parameters->getDigits())]; + $parameters['counter'] = $parameters['otp_type'] === TwoFAccount::HOTP ? $otp_parameters->getCounter() : null; + $parameters['period'] = $parameters['otp_type'] === TwoFAccount::TOTP ? $otp_parameters->getPeriod() : null; $twofaccounts[$key] = new TwoFAccount; $twofaccounts[$key]->fillWithOtpParameters($parameters); - } - catch (Exception $exception) { - + } catch (Exception $exception) { Log::error(sprintf('Cannot instanciate a TwoFAccount object with OTP parameters from imported item #%s', $key)); Log::error($exception->getMessage()); // The token failed to generate a valid account so we create a fake account to be returned. - $fakeAccount = new TwoFAccount(); - $fakeAccount->id = -2; - $fakeAccount->otp_type = $fakeAccount::TOTP; + $fakeAccount = new TwoFAccount(); + $fakeAccount->id = -2; + $fakeAccount->otp_type = $fakeAccount::TOTP; // Only basic fields are filled to limit the risk of another exception. - $fakeAccount->account = $otp_parameters->getName() ?? __('twofaccounts.import.invalid_account'); - $fakeAccount->service = $otp_parameters->getIssuer() ?? __('twofaccounts.import.invalid_service'); + $fakeAccount->account = $otp_parameters->getName() ?? __('twofaccounts.import.invalid_account'); + $fakeAccount->service = $otp_parameters->getIssuer() ?? __('twofaccounts.import.invalid_service'); // The secret field is used to pass the error, not very clean but will do the job for now. - $fakeAccount->secret = $exception->getMessage(); + $fakeAccount->secret = $exception->getMessage(); $twofaccounts[$key] = $fakeAccount; } diff --git a/app/Services/Migrators/Migrator.php b/app/Services/Migrators/Migrator.php index c98feff6..d9bf38ae 100644 --- a/app/Services/Migrators/Migrator.php +++ b/app/Services/Migrators/Migrator.php @@ -14,16 +14,14 @@ abstract class Migrator */ abstract public function migrate(mixed $migrationPayload) : Collection; - /** * Pad a string to 8 chars min - * - * @param string $string + * + * @param string $string * @return string The padded string */ protected function padToValidBase32Secret(string $string) { return str_pad($string, 8, '='); } - } diff --git a/app/Services/Migrators/PlainTextMigrator.php b/app/Services/Migrators/PlainTextMigrator.php index 14bd627b..86a34ff7 100644 --- a/app/Services/Migrators/PlainTextMigrator.php +++ b/app/Services/Migrators/PlainTextMigrator.php @@ -2,17 +2,15 @@ namespace App\Services\Migrators; -use App\Services\Migrators\Migrator; -use Illuminate\Support\Collection; -use App\Models\TwoFAccount; -use Illuminate\Support\Facades\Log; -use Illuminate\Support\Arr; -use Illuminate\Support\Str; use App\Exceptions\InvalidMigrationDataException; +use App\Models\TwoFAccount; +use Illuminate\Support\Arr; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Str; class PlainTextMigrator extends Migrator { - /** * Convert migration data to a TwoFAccounts collection. * @@ -32,25 +30,22 @@ class PlainTextMigrator extends Migrator } foreach ($otpauthURIs as $key => $uri) { - try { - $twofaccounts[$key] = new TwoFAccount; - $twofaccounts[$key]->fillWithURI($uri); - } - catch (\Exception $exception) { - + $twofaccounts[$key] = new TwoFAccount; + $twofaccounts[$key]->fillWithURI($uri); + } catch (\Exception $exception) { Log::error(sprintf('Cannot instanciate a TwoFAccount object with OTP parameters from imported item #%s', $key)); Log::error($exception->getMessage()); // The token failed to generate a valid account so we create a fake account to be returned. - $fakeAccount = new TwoFAccount(); - $fakeAccount->id = -2; - $fakeAccount->otp_type = substr($uri, 10, 4); + $fakeAccount = new TwoFAccount(); + $fakeAccount->id = -2; + $fakeAccount->otp_type = substr($uri, 10, 4); // Only basic fields are filled to limit the risk of another exception. - $fakeAccount->account = __('twofaccounts.import.invalid_account'); - $fakeAccount->service = filter_input(INPUT_GET, 'issuer', FILTER_SANITIZE_ENCODED) ?? __('twofaccounts.import.invalid_service'); + $fakeAccount->account = __('twofaccounts.import.invalid_account'); + $fakeAccount->service = filter_input(INPUT_GET, 'issuer', FILTER_SANITIZE_ENCODED) ?? __('twofaccounts.import.invalid_service'); // The secret field is used to pass the error, not very clean but will do the job for now. - $fakeAccount->secret = $exception->getMessage(); + $fakeAccount->secret = $exception->getMessage(); $twofaccounts[$key] = $fakeAccount; } diff --git a/app/Services/Migrators/TwoFASMigrator.php b/app/Services/Migrators/TwoFASMigrator.php index 526c0312..506fa0ac 100644 --- a/app/Services/Migrators/TwoFASMigrator.php +++ b/app/Services/Migrators/TwoFASMigrator.php @@ -2,12 +2,11 @@ namespace App\Services\Migrators; -use App\Services\Migrators\Migrator; -use Illuminate\Support\Collection; -use App\Models\TwoFAccount; -use Illuminate\Support\Facades\Log; -use Illuminate\Support\Arr; use App\Exceptions\InvalidMigrationDataException; +use App\Models\TwoFAccount; +use Illuminate\Support\Arr; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; class TwoFASMigrator extends Migrator { @@ -65,7 +64,6 @@ class TwoFASMigrator extends Migrator // "appVersionName": "3.20.1" // } - /** * Convert migration data to a TwoFAccounts collection. * @@ -80,39 +78,36 @@ class TwoFASMigrator extends Migrator Log::error('Aegis JSON migration data cannot be read'); throw new InvalidMigrationDataException('2FAS Auth'); } - - $twofaccounts = array(); + + $twofaccounts = []; foreach ($json['services'] as $key => $otp_parameters) { - - $parameters = array(); - $parameters['otp_type'] = $otp_parameters['otp']['tokenType']; - $parameters['service'] = $otp_parameters['name']; - $parameters['account'] = $otp_parameters['otp']['account'] ?? $parameters['service']; - $parameters['secret'] = $this->padToValidBase32Secret($otp_parameters['secret']); - $parameters['algorithm'] = $otp_parameters['otp']['algorithm']; - $parameters['digits'] = $otp_parameters['otp']['digits']; - $parameters['counter'] = $otp_parameters['otp']['counter'] ?? null; - $parameters['period'] = $otp_parameters['otp']['period'] ?? null; + $parameters = []; + $parameters['otp_type'] = $otp_parameters['otp']['tokenType']; + $parameters['service'] = $otp_parameters['name']; + $parameters['account'] = $otp_parameters['otp']['account'] ?? $parameters['service']; + $parameters['secret'] = $this->padToValidBase32Secret($otp_parameters['secret']); + $parameters['algorithm'] = $otp_parameters['otp']['algorithm']; + $parameters['digits'] = $otp_parameters['otp']['digits']; + $parameters['counter'] = $otp_parameters['otp']['counter'] ?? null; + $parameters['period'] = $otp_parameters['otp']['period'] ?? null; try { - $twofaccounts[$key] = new TwoFAccount; - $twofaccounts[$key]->fillWithOtpParameters($parameters); - } - catch (\Exception $exception) { - + $twofaccounts[$key] = new TwoFAccount; + $twofaccounts[$key]->fillWithOtpParameters($parameters); + } catch (\Exception $exception) { Log::error(sprintf('Cannot instanciate a TwoFAccount object with 2FAS imported item #%s', $key)); Log::error($exception->getMessage()); // The token failed to generate a valid account so we create a fake account to be returned. - $fakeAccount = new TwoFAccount(); - $fakeAccount->id = TwoFAccount::FAKE_ID; - $fakeAccount->otp_type = $otp_parameters['otp']['tokenType'] ?? TwoFAccount::TOTP; + $fakeAccount = new TwoFAccount(); + $fakeAccount->id = TwoFAccount::FAKE_ID; + $fakeAccount->otp_type = $otp_parameters['otp']['tokenType'] ?? TwoFAccount::TOTP; // Only basic fields are filled to limit the risk of another exception. - $fakeAccount->account = $otp_parameters['otp']['account'] ?? __('twofaccounts.import.invalid_account'); - $fakeAccount->service = $otp_parameters['name'] ?? __('twofaccounts.import.invalid_service'); + $fakeAccount->account = $otp_parameters['otp']['account'] ?? __('twofaccounts.import.invalid_account'); + $fakeAccount->service = $otp_parameters['name'] ?? __('twofaccounts.import.invalid_service'); // The secret field is used to pass the error, not very clean but will do the job for now. - $fakeAccount->secret = $exception->getMessage(); + $fakeAccount->secret = $exception->getMessage(); $twofaccounts[$key] = $fakeAccount; } diff --git a/app/Services/QrCodeService.php b/app/Services/QrCodeService.php index dcb445c9..8fda565a 100644 --- a/app/Services/QrCodeService.php +++ b/app/Services/QrCodeService.php @@ -2,18 +2,18 @@ namespace App\Services; -use Zxing\QrReader; +use chillerlan\QRCode\QRCode; +use chillerlan\QRCode\QROptions; use Illuminate\Support\Facades\Log; -use chillerlan\QRCode\{QRCode, QROptions}; +use Zxing\QrReader; class QrCodeService { /** * Encode a string into a QR code image - * - * @param string $data The string to encode - * - * @return mixed + * + * @param string $data The string to encode + * @return mixed */ public static function encode(string $data) { @@ -29,24 +29,23 @@ class QrCodeService return $qrcode->render($data); } - /** * Decode an uploaded QR code image - * - * @param \Illuminate\Http\UploadedFile $file + * + * @param \Illuminate\Http\UploadedFile $file * @return string */ public static function decode(\Illuminate\Http\UploadedFile $file) { $qrcode = new QrReader($file->get(), QrReader::SOURCE_TYPE_BLOB); - $data = urldecode($qrcode->text()); + $data = urldecode($qrcode->text()); - if(!$data) { + if (! $data) { throw new \App\Exceptions\InvalidQrCodeException; } - + Log::info('QR code decoded'); return $data; } -} \ No newline at end of file +} diff --git a/app/Services/ReleaseRadarService.php b/app/Services/ReleaseRadarService.php index 2de66fb8..af54a6ea 100644 --- a/app/Services/ReleaseRadarService.php +++ b/app/Services/ReleaseRadarService.php @@ -11,7 +11,7 @@ class ReleaseRadarService { /** * Run a scheduled release scan - * + * * @return void */ public function scheduledScan() : void @@ -21,10 +21,9 @@ class ReleaseRadarService } } - /** * Run a manual release scan - * + * * @return false|string False if no new release, the new release number otherwise */ public function manualScan() : false|string @@ -34,22 +33,20 @@ class ReleaseRadarService /** * Run a release scan - * + * * @return false|string False if no new release, the new release number otherwise */ protected function newRelease() : false|string { - if ($latestReleaseData = json_decode($this->getLatestReleaseData())) - { - $githubVersion = Helpers::cleanVersionNumber($latestReleaseData->tag_name); + if ($latestReleaseData = json_decode($this->getLatestReleaseData())) { + $githubVersion = Helpers::cleanVersionNumber($latestReleaseData->tag_name); $installedVersion = Helpers::cleanVersionNumber(config('2fauth.version')); if ($githubVersion > $installedVersion && $latestReleaseData->prerelease == false && $latestReleaseData->draft == false) { Settings::set('latestRelease', $latestReleaseData->tag_name); - + return $latestReleaseData->tag_name; - } - else { + } else { Settings::delete('latestRelease'); } @@ -59,10 +56,9 @@ class ReleaseRadarService return false; } - /** * Fetch releases on Github - * + * * @return string|null */ protected function getLatestReleaseData() : string|null @@ -70,15 +66,14 @@ class ReleaseRadarService try { $response = Http::retry(3, 100) ->get(config('2fauth.latestReleaseUrl')); - + if ($response->successful()) { return $response->body(); } - } - catch (\Exception $exception) { + } catch (\Exception $exception) { Log::error('cannot reach latestReleaseUrl endpoint'); } return null; } -} \ No newline at end of file +} diff --git a/app/Services/SettingService.php b/app/Services/SettingService.php index 89e5dd72..58952298 100644 --- a/app/Services/SettingService.php +++ b/app/Services/SettingService.php @@ -2,28 +2,26 @@ namespace App\Services; -use Throwable; -use Exception; +use App\Exceptions\DbEncryptionException; use App\Models\Option; +use Exception; use Illuminate\Support\Arr; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\App; +use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; -use Illuminate\Support\Facades\Crypt; -use Illuminate\Support\Facades\App; -use App\Exceptions\DbEncryptionException; +use Throwable; class SettingService { - /** * All user settings - * + * * @var Collection */ private Collection $settings; - /** * Constructor */ @@ -32,11 +30,10 @@ class SettingService self::build(); } - /** * Get a setting * - * @param string $setting A single setting name + * @param string $setting A single setting name * @return mixed string|int|boolean|null */ public function get($setting) @@ -44,10 +41,9 @@ class SettingService return $this->settings->get($setting); } - /** * Get all settings - * + * * @return Collection the Settings collection */ public function all() : Collection @@ -55,20 +51,18 @@ class SettingService return $this->settings; } - /** * Set a setting * - * @param string|array $setting A single setting name or an associative array of name:value settings - * @param string|int|boolean|null $value The value for single setting + * @param string|array $setting A single setting name or an associative array of name:value settings + * @param string|int|bool|null $value The value for single setting */ public function set($setting, $value = null) : void { $settings = is_array($setting) ? $setting : [$setting => $value]; foreach ($settings as $setting => $value) { - if( $setting === 'useEncryption') - { + if ($setting === 'useEncryption') { $this->setEncryptionTo($value); } @@ -83,11 +77,10 @@ class SettingService self::build(); } - /** * Delete a setting * - * @param string $name The setting name + * @param string $name The setting name */ public function delete(string $name) : void { @@ -95,7 +88,6 @@ class SettingService Log::info(sprintf('Setting %s deleted', var_export($name, true))); } - /** * Determine if the given setting has been customized by the user * @@ -107,10 +99,9 @@ class SettingService return DB::table('options')->where('key', $key)->exists(); } - /** * Set the settings collection - * + * * @return void */ private function build() @@ -123,19 +114,17 @@ class SettingService // Merge 2fauth/app config values as fallback values $settings = collect(config('2fauth.options'))->merge($userOptions); /** @phpstan-ignore-line */ - - if(!Arr::has($settings, 'lang')) { + if (! Arr::has($settings, 'lang')) { $settings['lang'] = 'browser'; } $this->settings = $settings; } - /** * Replaces boolean by a patterned string as appstrack/laravel-options package does not support var type - * - * @param mixed $value + * + * @param mixed $value * @return string */ private function replaceBoolean(mixed $value) @@ -143,33 +132,30 @@ class SettingService return is_bool($value) ? '{{' . $value . '}}' : $value; } - /** * Replaces patterned string that represent booleans with real booleans - * - * @param mixed $value + * + * @param mixed $value * @return mixed */ private function restoreType(mixed $value) { $value = is_numeric($value) ? (int) $value : $value; - if( $value === '{{}}' ) { + if ($value === '{{}}') { return false; - } - else if( $value === '{{1}}' ) { + } elseif ($value === '{{1}}') { return true; - } - else { + } else { return $value; } } - /** * Enable or Disable encryption of 2FAccounts sensible data - * + * * @return void + * * @throws DbEncryptionException Something failed, everything have been rolled back */ private function setEncryptionTo(bool $state) : void @@ -177,39 +163,37 @@ class SettingService // We don't want the records to be encrypted/decrypted multiple successive times $isInUse = $this->get('useEncryption'); - if ($isInUse === !$state) { + if ($isInUse === ! $state) { if ($this->updateRecords($state)) { if ($state) { Log::notice('Sensible data are now encrypted'); + } else { + Log::notice('Sensible data are now decrypted'); } - else Log::notice('Sensible data are now decrypted'); - } - else { + } else { Log::warning('Some data cannot be encrypted/decrypted, the useEncryption setting remain unchanged'); throw new DbEncryptionException($state === true ? __('errors.error_during_encryption') : __('errors.error_during_decryption')); } } } - /** * Encrypt/Decrypt accounts in database - * - * @param boolean $encrypted Whether the record should be encrypted or not - * @return boolean Whether the operation completed successfully + * + * @param bool $encrypted Whether the record should be encrypted or not + * @return bool Whether the operation completed successfully */ private function updateRecords(bool $encrypted) : bool - { - $success = true; + { + $success = true; $twofaccounts = DB::table('twofaccounts')->get(); - $twofaccounts->each(function ($item, $key) use(&$success, $encrypted) { + $twofaccounts->each(function ($item, $key) use (&$success, $encrypted) { try { - $item->legacy_uri = $encrypted ? Crypt::encryptString($item->legacy_uri) : Crypt::decryptString($item->legacy_uri); - $item->account = $encrypted ? Crypt::encryptString($item->account) : Crypt::decryptString($item->account); - $item->secret = $encrypted ? Crypt::encryptString($item->secret) : Crypt::decryptString($item->secret); - } - catch (Exception $ex) { + $item->legacy_uri = $encrypted ? Crypt::encryptString($item->legacy_uri) : Crypt::decryptString($item->legacy_uri); + $item->account = $encrypted ? Crypt::encryptString($item->account) : Crypt::decryptString($item->account); + $item->secret = $encrypted ? Crypt::encryptString($item->secret) : Crypt::decryptString($item->secret); + } catch (Exception $ex) { $success = false; // Exit the each iteration return false; @@ -228,20 +212,23 @@ class SettingService ->update([ 'legacy_uri' => $item->legacy_uri, 'account' => $item->account, - 'secret' => $item->secret + 'secret' => $item->secret, ]); }); DB::commit(); + return true; } // @codeCoverageIgnoreStart catch (Throwable $ex) { DB::rollBack(); + return false; } // @codeCoverageIgnoreEnd + } else { + return false; } - else return false; } -} \ No newline at end of file +} diff --git a/app/Services/TwoFAccountService.php b/app/Services/TwoFAccountService.php index d711c296..6b3886b1 100644 --- a/app/Services/TwoFAccountService.php +++ b/app/Services/TwoFAccountService.php @@ -2,19 +2,18 @@ namespace App\Services; -use App\Models\TwoFAccount; use App\Factories\MigratorFactoryInterface; -use Illuminate\Support\Facades\Log; +use App\Models\TwoFAccount; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; class TwoFAccountService { /** - * @var MigratorFactoryInterface $migratorFactory The Migration service + * @var MigratorFactoryInterface The Migration service */ protected $migratorFactory; - /** * Constructor */ @@ -23,11 +22,10 @@ class TwoFAccountService $this->migratorFactory = $migratorFactory; } - /** * Withdraw one or more twofaccounts from their group - * - * @param int|array|string $ids twofaccount ids to free + * + * @param int|array|string $ids twofaccount ids to free */ public static function withdraw($ids) : void { @@ -40,32 +38,30 @@ class TwoFAccountService TwoFAccount::whereIn('id', $ids) ->update( - ['group_id' => NULL] + ['group_id' => null] ); - + Log::info(sprintf('TwoFAccounts #%s withdrawn', implode(',#', $ids))); } - /** * Convert a migration payload to a set of TwoFAccount objects - * - * @param string $migrationPayload Migration payload from 2FA apps export feature + * + * @param string $migrationPayload Migration payload from 2FA apps export feature * @return \Illuminate\Support\Collection The converted accounts */ public function migrate(string $migrationPayload) : Collection { - $migrator = $this->migratorFactory->create($migrationPayload); + $migrator = $this->migratorFactory->create($migrationPayload); $twofaccounts = $migrator->migrate($migrationPayload); return self::markAsDuplicate($twofaccounts); } - /** * Delete one or more twofaccounts - * - * @param int|array|string $ids twofaccount ids to delete + * + * @param int|array|string $ids twofaccount ids to delete * @return int The number of deleted */ public static function delete($ids) : int @@ -73,17 +69,16 @@ class TwoFAccountService // $ids as string could be a comma-separated list of ids // so in this case we explode the string to an array $ids = self::commaSeparatedToArray($ids); - Log::info(sprintf('Deletion of TwoFAccounts #%s requested', is_array($ids) ? implode(',#', $ids) : $ids )); + Log::info(sprintf('Deletion of TwoFAccounts #%s requested', is_array($ids) ? implode(',#', $ids) : $ids)); $deleted = TwoFAccount::destroy($ids); return $deleted; } - /** * Return the given collection with items marked as Duplicates (using id=-1) if a similar record exists in database - * - * @param \Illuminate\Support\Collection $twofaccounts + * + * @param \Illuminate\Support\Collection $twofaccounts * @return \Illuminate\Support\Collection */ private static function markAsDuplicate(Collection $twofaccounts) : Collection @@ -108,22 +103,20 @@ class TwoFAccountService return $twofaccounts; } - /** * Explode a comma separated list of IDs to an array of IDs - * - * @param int|array|string $ids + * + * @param int|array|string $ids */ private static function commaSeparatedToArray($ids) : mixed { - if(is_string($ids)) - { + if (is_string($ids)) { $regex = "/^\d+(,{1}\d+)*$/"; if (preg_match($regex, $ids)) { $ids = explode(',', $ids); } } - + return $ids; } -} \ No newline at end of file +} diff --git a/pint.json b/pint.json index 661e522c..41f1c628 100644 --- a/pint.json +++ b/pint.json @@ -1,3 +1,26 @@ { - "preset": "laravel" + "preset": "laravel", + "exclude": [ + "app/Protobuf", + "bootstrap", + "config", + "database", + "public", + "resources" + ], + "rules": { + "binary_operator_spaces": { + "default": "single_space", + "operators": { + "=>": "align_single_space_minimal", + "=": "align_single_space_minimal" + } + }, + "concat_space": { + "spacing": "one" + }, + "return_type_declaration": { + "space_before": "one" + } + } } \ No newline at end of file diff --git a/tests/Api/v1/Controllers/Auth/UserControllerTest.php b/tests/Api/v1/Controllers/Auth/UserControllerTest.php index 4b735c22..6abaab92 100644 --- a/tests/Api/v1/Controllers/Auth/UserControllerTest.php +++ b/tests/Api/v1/Controllers/Auth/UserControllerTest.php @@ -9,21 +9,19 @@ class UserControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; - /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ @@ -39,7 +37,6 @@ class UserControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -48,11 +45,10 @@ class UserControllerTest extends FeatureTestCase $response = $this->json('GET', '/api/v1/user/name') ->assertOk() ->assertExactJson([ - 'name' => $this->user->name, + 'name' => $this->user->name, ]); } - /** * @test */ @@ -69,5 +65,4 @@ class UserControllerTest extends FeatureTestCase 'email' => $this->user->email, ]); } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Controllers/GroupControllerTest.php b/tests/Api/v1/Controllers/GroupControllerTest.php index bb3edfb1..eb0926d4 100644 --- a/tests/Api/v1/Controllers/GroupControllerTest.php +++ b/tests/Api/v1/Controllers/GroupControllerTest.php @@ -2,11 +2,10 @@ namespace Tests\Api\v1\Controllers; -use App\Models\User; use App\Models\Group; -use Tests\FeatureTestCase; use App\Models\TwoFAccount; - +use App\Models\User; +use Tests\FeatureTestCase; /** * @covers \App\Api\v1\Controllers\GroupController @@ -16,21 +15,19 @@ class GroupControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; - /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ @@ -47,16 +44,15 @@ class GroupControllerTest extends FeatureTestCase 'id', 'name', 'twofaccounts_count', - ] + ], ]) ->assertJsonFragment([ - 'id' => 0, - 'name' => 'All', + 'id' => 0, + 'name' => 'All', 'twofaccounts_count' => 0, ]); } - /** * @test */ @@ -68,12 +64,11 @@ class GroupControllerTest extends FeatureTestCase ]) ->assertCreated() ->assertJsonFragment([ - 'name' => 'My second group', + 'name' => 'My second group', 'twofaccounts_count' => 0, ]); } - /** * @test */ @@ -86,7 +81,6 @@ class GroupControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ @@ -100,12 +94,11 @@ class GroupControllerTest extends FeatureTestCase ->json('GET', '/api/v1/groups/' . $group->id) ->assertOk() ->assertJsonFragment([ - 'name' => 'My group', + 'name' => 'My group', 'twofaccounts_count' => 0, ]); } - /** * @test */ @@ -115,11 +108,10 @@ class GroupControllerTest extends FeatureTestCase ->json('GET', '/api/v1/groups/1000') ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ @@ -133,12 +125,11 @@ class GroupControllerTest extends FeatureTestCase ]) ->assertOk() ->assertJsonFragment([ - 'name' => 'name updated', + 'name' => 'name updated', 'twofaccounts_count' => 0, ]); } - /** * @test */ @@ -150,11 +141,10 @@ class GroupControllerTest extends FeatureTestCase ]) ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ @@ -169,13 +159,12 @@ class GroupControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ public function test_assign_accounts_returns_updated_group_resource() { - $group = Group::factory()->create(); + $group = Group::factory()->create(); $accounts = TwoFAccount::factory()->count(2)->create(); $response = $this->actingAs($this->user, 'api-guard') @@ -184,13 +173,12 @@ class GroupControllerTest extends FeatureTestCase ]) ->assertOk() ->assertExactJson([ - 'id' => $group->id, - 'name' => $group->name, + 'id' => $group->id, + 'name' => $group->name, 'twofaccounts_count' => 2, ]); } - /** * @test */ @@ -204,17 +192,16 @@ class GroupControllerTest extends FeatureTestCase ]) ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ public function test_assign_invalid_accounts_returns_validation_error() { - $group = Group::factory()->create(); + $group = Group::factory()->create(); $accounts = TwoFAccount::factory()->count(2)->create(); $response = $this->actingAs($this->user, 'api-guard') @@ -224,13 +211,12 @@ class GroupControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ public function test_get_assigned_accounts_returns_twofaccounts_collection() { - $group = Group::factory()->create(); + $group = Group::factory()->create(); $accounts = TwoFAccount::factory()->count(2)->create(); $assign = $this->actingAs($this->user, 'api-guard') @@ -252,18 +238,17 @@ class GroupControllerTest extends FeatureTestCase 'digits', 'algorithm', 'period', - 'counter' - ] + 'counter', + ], ]); } - /** * @test */ public function test_get_assigned_accounts_returns_twofaccounts_collection_with_secret() { - $group = Group::factory()->create(); + $group = Group::factory()->create(); $accounts = TwoFAccount::factory()->count(2)->create(); $assign = $this->actingAs($this->user, 'api-guard') @@ -286,12 +271,11 @@ class GroupControllerTest extends FeatureTestCase 'digits', 'algorithm', 'period', - 'counter' - ] + 'counter', + ], ]); } - /** * @test */ @@ -301,11 +285,10 @@ class GroupControllerTest extends FeatureTestCase ->json('GET', '/api/v1/groups/1000/twofaccounts') ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * test Group deletion via API * @@ -320,7 +303,6 @@ class GroupControllerTest extends FeatureTestCase ->assertNoContent(); } - /** * test Group deletion via API * @@ -332,7 +314,7 @@ class GroupControllerTest extends FeatureTestCase ->json('DELETE', '/api/v1/groups/1000') ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } } diff --git a/tests/Api/v1/Controllers/IconControllerTest.php b/tests/Api/v1/Controllers/IconControllerTest.php index eef1f391..29222750 100644 --- a/tests/Api/v1/Controllers/IconControllerTest.php +++ b/tests/Api/v1/Controllers/IconControllerTest.php @@ -2,21 +2,17 @@ namespace Tests\Api\v1\Controllers; -use Illuminate\Http\UploadedFile; use Illuminate\Foundation\Testing\WithoutMiddleware; +use Illuminate\Http\UploadedFile; use Tests\FeatureTestCase; -use App\Models\TwoFAccount; - /** * @covers \App\Api\v1\Controllers\IconController */ class IconControllerTest extends FeatureTestCase { - use WithoutMiddleware; - /** * @test */ @@ -25,27 +21,25 @@ class IconControllerTest extends FeatureTestCase $file = UploadedFile::fake()->image('testIcon.jpg'); $response = $this->json('POST', '/api/v1/icons', [ - 'icon' => $file, - ]) + 'icon' => $file, + ]) ->assertCreated() ->assertJsonStructure([ - 'filename' + 'filename', ]); } - /** * @test */ public function test_upload_with_invalid_data_returns_validation_error() { $response = $this->json('POST', '/api/v1/icons', [ - 'icon' => null, - ]) + 'icon' => null, + ]) ->assertStatus(422); } - /** * @test */ @@ -55,7 +49,6 @@ class IconControllerTest extends FeatureTestCase ->assertNoContent(204); } - /** * @test */ @@ -63,7 +56,5 @@ class IconControllerTest extends FeatureTestCase { $response = $this->json('DELETE', '/api/v1/icons/null') ->assertNoContent(204); - } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Controllers/QrCodeControllerTest.php b/tests/Api/v1/Controllers/QrCodeControllerTest.php index 3ddb534d..80f55c55 100644 --- a/tests/Api/v1/Controllers/QrCodeControllerTest.php +++ b/tests/Api/v1/Controllers/QrCodeControllerTest.php @@ -2,48 +2,44 @@ namespace Tests\Api\v1\Controllers; -use App\Models\User; -use Tests\FeatureTestCase; use App\Models\TwoFAccount; +use App\Models\User; use Tests\Classes\LocalFile; - +use Tests\FeatureTestCase; /** * @covers \App\Api\v1\Controllers\QrCodeController */ class QrCodeControllerTest extends FeatureTestCase { - /** * @var \App\Models\User - */ + */ protected $user; - /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ public function test_show_qrcode_returns_base64_image() { $twofaccount = TwoFAccount::factory()->create([ - 'otp_type' => 'totp', - 'account' => 'account', - 'service' => 'service', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, + 'otp_type' => 'totp', + 'account' => 'account', + 'service' => 'service', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, 'legacy_uri' => 'otpauth://hotp/service:account?secret=A4GRFHZVRBGY7UIW&issuer=service', ]); @@ -53,11 +49,10 @@ class QrCodeControllerTest extends FeatureTestCase 'qrcode', ]) ->assertOk(); - + $this->assertStringStartsWith('data:image/png;base64', $response->getData()->qrcode); } - /** * @test */ @@ -67,11 +62,10 @@ class QrCodeControllerTest extends FeatureTestCase ->json('GET', '/api/v1/twofaccounts/1000/qrcode') ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ @@ -82,8 +76,8 @@ class QrCodeControllerTest extends FeatureTestCase $response = $this->withHeaders(['Content-Type' => 'multipart/form-data']) ->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/qrcode/decode', [ - 'qrcode' => $file, - 'inputFormat' => 'fileUpload' + 'qrcode' => $file, + 'inputFormat' => 'fileUpload', ]) ->assertOk() ->assertExactJson([ @@ -91,7 +85,6 @@ class QrCodeControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -104,7 +97,6 @@ class QrCodeControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ @@ -115,12 +107,12 @@ class QrCodeControllerTest extends FeatureTestCase $response = $this->withHeaders(['Content-Type' => 'multipart/form-data']) ->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/qrcode/decode', [ - 'qrcode' => $file, - 'inputFormat' => 'fileUpload' + 'qrcode' => $file, + 'inputFormat' => 'fileUpload', ]) ->assertStatus(400) ->assertJsonStructure([ 'message', ]); } -} \ No newline at end of file +} diff --git a/tests/Api/v1/Controllers/SettingControllerTest.php b/tests/Api/v1/Controllers/SettingControllerTest.php index 4eeb61d2..57f95542 100644 --- a/tests/Api/v1/Controllers/SettingControllerTest.php +++ b/tests/Api/v1/Controllers/SettingControllerTest.php @@ -2,10 +2,9 @@ namespace Tests\Api\v1\Controllers; +use App\Facades\Settings; use App\Models\User; use Tests\FeatureTestCase; -use App\Facades\Settings; - /** * @covers \App\Api\v1\Controllers\SettingController @@ -14,31 +13,36 @@ class SettingControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; private const SETTING_JSON_STRUCTURE = [ 'key', - 'value' + 'value', ]; + private const TWOFAUTH_NATIVE_SETTING = 'showTokenAsDot'; + private const TWOFAUTH_NATIVE_SETTING_DEFAULT_VALUE = false; + private const TWOFAUTH_NATIVE_SETTING_CHANGED_VALUE = true; + private const USER_DEFINED_SETTING = 'mySetting'; + private const USER_DEFINED_SETTING_VALUE = 'mySetting'; + private const USER_DEFINED_SETTING_CHANGED_VALUE = 'mySetting'; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ @@ -48,11 +52,10 @@ class SettingControllerTest extends FeatureTestCase ->json('GET', '/api/v1/settings') ->assertOk() ->assertJsonStructure([ - '*' => self::SETTING_JSON_STRUCTURE + '*' => self::SETTING_JSON_STRUCTURE, ]); } - /** * @test */ @@ -62,12 +65,11 @@ class SettingControllerTest extends FeatureTestCase ->json('GET', '/api/v1/settings/' . self::TWOFAUTH_NATIVE_SETTING) ->assertOk() ->assertExactJson([ - 'key' => self::TWOFAUTH_NATIVE_SETTING, + 'key' => self::TWOFAUTH_NATIVE_SETTING, 'value' => self::TWOFAUTH_NATIVE_SETTING_DEFAULT_VALUE, ]); } - /** * @test */ @@ -79,12 +81,11 @@ class SettingControllerTest extends FeatureTestCase ->json('GET', '/api/v1/settings/' . self::TWOFAUTH_NATIVE_SETTING) ->assertOk() ->assertExactJson([ - 'key' => self::TWOFAUTH_NATIVE_SETTING, + 'key' => self::TWOFAUTH_NATIVE_SETTING, 'value' => self::TWOFAUTH_NATIVE_SETTING_CHANGED_VALUE, ]); } - /** * @test */ @@ -96,12 +97,11 @@ class SettingControllerTest extends FeatureTestCase ->json('GET', '/api/v1/settings/' . self::USER_DEFINED_SETTING) ->assertOk() ->assertExactJson([ - 'key' => self::USER_DEFINED_SETTING, + 'key' => self::USER_DEFINED_SETTING, 'value' => self::USER_DEFINED_SETTING_VALUE, ]); } - /** * @test */ @@ -112,7 +112,6 @@ class SettingControllerTest extends FeatureTestCase ->assertNotFound(); } - /** * @test */ @@ -120,17 +119,16 @@ class SettingControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/settings', [ - 'key' => self::USER_DEFINED_SETTING, + 'key' => self::USER_DEFINED_SETTING, 'value' => self::USER_DEFINED_SETTING_VALUE, ]) ->assertCreated() ->assertExactJson([ - 'key' => self::USER_DEFINED_SETTING, + 'key' => self::USER_DEFINED_SETTING, 'value' => self::USER_DEFINED_SETTING_VALUE, ]); } - /** * @test */ @@ -138,13 +136,12 @@ class SettingControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/settings', [ - 'key' => null, + 'key' => null, 'value' => null, ]) ->assertStatus(422); } - /** * @test */ @@ -154,13 +151,12 @@ class SettingControllerTest extends FeatureTestCase $response = $this->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/settings', [ - 'key' => self::USER_DEFINED_SETTING, + 'key' => self::USER_DEFINED_SETTING, 'value' => self::USER_DEFINED_SETTING_VALUE, ]) ->assertStatus(422); } - /** * @test */ @@ -172,12 +168,11 @@ class SettingControllerTest extends FeatureTestCase ]) ->assertOk() ->assertExactJson([ - 'key' => self::TWOFAUTH_NATIVE_SETTING, + 'key' => self::TWOFAUTH_NATIVE_SETTING, 'value' => self::TWOFAUTH_NATIVE_SETTING_CHANGED_VALUE, ]); } - /** * @test */ @@ -191,12 +186,11 @@ class SettingControllerTest extends FeatureTestCase ]) ->assertOk() ->assertExactJson([ - 'key' => self::USER_DEFINED_SETTING, + 'key' => self::USER_DEFINED_SETTING, 'value' => self::USER_DEFINED_SETTING_CHANGED_VALUE, ]); } - /** * @test */ @@ -208,12 +202,11 @@ class SettingControllerTest extends FeatureTestCase ]) ->assertOk() ->assertExactJson([ - 'key' => self::USER_DEFINED_SETTING, + 'key' => self::USER_DEFINED_SETTING, 'value' => self::USER_DEFINED_SETTING_CHANGED_VALUE, ]); } - /** * @test */ @@ -226,7 +219,6 @@ class SettingControllerTest extends FeatureTestCase ->assertNoContent(); } - /** * @test */ @@ -241,7 +233,6 @@ class SettingControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -251,6 +242,4 @@ class SettingControllerTest extends FeatureTestCase ->json('DELETE', '/api/v1/settings/' . self::USER_DEFINED_SETTING) ->assertNotFound(); } - - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Controllers/TwoFAccountControllerTest.php b/tests/Api/v1/Controllers/TwoFAccountControllerTest.php index 1933a65e..fb28fa51 100644 --- a/tests/Api/v1/Controllers/TwoFAccountControllerTest.php +++ b/tests/Api/v1/Controllers/TwoFAccountControllerTest.php @@ -2,16 +2,15 @@ namespace Tests\Api\v1\Controllers; -use App\Models\User; -use App\Models\Group; use App\Facades\Settings; -use Tests\FeatureTestCase; -use Tests\Classes\OtpTestData; +use App\Models\Group; use App\Models\TwoFAccount; +use App\Models\User; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; use Tests\Classes\LocalFile; - +use Tests\Classes\OtpTestData; +use Tests\FeatureTestCase; /** * @covers \App\Api\v1\Controllers\TwoFAccountController @@ -22,16 +21,14 @@ class TwoFAccountControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; /** * @var \App\Models\Group - */ + */ protected $group; - - private const VALID_RESOURCE_STRUCTURE_WITHOUT_SECRET = [ 'id', 'group_id', @@ -42,8 +39,9 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits', 'algorithm', 'period', - 'counter' + 'counter', ]; + private const VALID_RESOURCE_STRUCTURE_WITH_SECRET = [ 'id', 'group_id', @@ -55,19 +53,22 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits', 'algorithm', 'period', - 'counter' + 'counter', ]; + private const VALID_OTP_RESOURCE_STRUCTURE_FOR_TOTP = [ 'generated_at', 'otp_type', 'password', 'period', ]; + private const VALID_OTP_RESOURCE_STRUCTURE_FOR_HOTP = [ 'otp_type', 'password', 'counter', ]; + private const JSON_FRAGMENTS_FOR_CUSTOM_TOTP = [ 'service' => OtpTestData::SERVICE, 'account' => OtpTestData::ACCOUNT, @@ -78,6 +79,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'period' => OtpTestData::PERIOD_CUSTOM, 'counter' => null, ]; + private const JSON_FRAGMENTS_FOR_DEFAULT_TOTP = [ 'service' => null, 'account' => OtpTestData::ACCOUNT, @@ -88,6 +90,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'period' => OtpTestData::PERIOD_DEFAULT, 'counter' => null, ]; + private const JSON_FRAGMENTS_FOR_CUSTOM_HOTP = [ 'service' => OtpTestData::SERVICE, 'account' => OtpTestData::ACCOUNT, @@ -98,8 +101,9 @@ class TwoFAccountControllerTest extends FeatureTestCase 'period' => null, 'counter' => OtpTestData::COUNTER_CUSTOM, ]; + private const JSON_FRAGMENTS_FOR_DEFAULT_HOTP = [ - 'service' => null, + 'service' => null, 'account' => OtpTestData::ACCOUNT, 'otp_type' => 'hotp', 'secret' => OtpTestData::SECRET, @@ -108,28 +112,27 @@ class TwoFAccountControllerTest extends FeatureTestCase 'period' => null, 'counter' => OtpTestData::COUNTER_DEFAULT, ]; - private const ARRAY_OF_INVALID_PARAMETERS = [ - 'account' => null, - 'otp_type' => 'totp', - 'secret' => OtpTestData::SECRET, - ]; + private const ARRAY_OF_INVALID_PARAMETERS = [ + 'account' => null, + 'otp_type' => 'totp', + 'secret' => OtpTestData::SECRET, + ]; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); - $this->user = User::factory()->create(); + $this->user = User::factory()->create(); $this->group = Group::factory()->create(); } - /** * @test - * + * * @dataProvider indexUrlParameterProvider */ public function test_index_returns_twofaccount_collection($urlParameter, $expected) @@ -137,33 +140,31 @@ class TwoFAccountControllerTest extends FeatureTestCase TwoFAccount::factory()->count(3)->create(); $response = $this->actingAs($this->user, 'api-guard') - ->json('GET', '/api/v1/twofaccounts'.$urlParameter) + ->json('GET', '/api/v1/twofaccounts' . $urlParameter) ->assertOk() ->assertJsonCount(3, $key = null) ->assertJsonStructure([ - '*' => $expected + '*' => $expected, ]); } - /** * Provide data for index tests */ public function indexUrlParameterProvider() { return [ - 'VALID_RESOURCE_STRUCTURE_WITHOUT_SECRET' => [ + 'VALID_RESOURCE_STRUCTURE_WITHOUT_SECRET' => [ '', - self::VALID_RESOURCE_STRUCTURE_WITHOUT_SECRET + self::VALID_RESOURCE_STRUCTURE_WITHOUT_SECRET, ], - 'VALID_RESOURCE_STRUCTURE_WITH_SECRET' => [ + 'VALID_RESOURCE_STRUCTURE_WITH_SECRET' => [ '?withSecret=1', - self::VALID_RESOURCE_STRUCTURE_WITH_SECRET + self::VALID_RESOURCE_STRUCTURE_WITH_SECRET, ], ]; } - /** * @test */ @@ -177,7 +178,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_RESOURCE_STRUCTURE_WITH_SECRET); } - /** * @test */ @@ -191,7 +191,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_RESOURCE_STRUCTURE_WITHOUT_SECRET); } - /** * @test */ @@ -217,7 +216,6 @@ class TwoFAccountControllerTest extends FeatureTestCase // ]); // } - /** * @test */ @@ -227,11 +225,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ->json('GET', '/api/v1/twofaccounts/1000') ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @dataProvider accountCreationProvider * @test @@ -248,7 +245,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonFragment($expected); } - /** * @dataProvider accountCreationProvider * @test @@ -265,57 +261,55 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonFragment($expected); } - /** * Provide data for TwoFAccount store tests */ public function accountCreationProvider() { return [ - 'TOTP_FULL_CUSTOM_URI' => [ + 'TOTP_FULL_CUSTOM_URI' => [ [ 'uri' => OtpTestData::TOTP_FULL_CUSTOM_URI, ], - self::JSON_FRAGMENTS_FOR_CUSTOM_TOTP + self::JSON_FRAGMENTS_FOR_CUSTOM_TOTP, ], - 'TOTP_SHORT_URI' => [ + 'TOTP_SHORT_URI' => [ [ 'uri' => OtpTestData::TOTP_SHORT_URI, ], - self::JSON_FRAGMENTS_FOR_DEFAULT_TOTP + self::JSON_FRAGMENTS_FOR_DEFAULT_TOTP, ], - 'ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_TOTP' => [ + 'ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_TOTP' => [ OtpTestData::ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_TOTP, - self::JSON_FRAGMENTS_FOR_CUSTOM_TOTP + self::JSON_FRAGMENTS_FOR_CUSTOM_TOTP, ], - 'ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_TOTP' => [ + 'ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_TOTP' => [ OtpTestData::ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_TOTP, - self::JSON_FRAGMENTS_FOR_DEFAULT_TOTP + self::JSON_FRAGMENTS_FOR_DEFAULT_TOTP, ], - 'HOTP_FULL_CUSTOM_URI' => [ + 'HOTP_FULL_CUSTOM_URI' => [ [ 'uri' => OtpTestData::HOTP_FULL_CUSTOM_URI, ], - self::JSON_FRAGMENTS_FOR_CUSTOM_HOTP + self::JSON_FRAGMENTS_FOR_CUSTOM_HOTP, ], - 'HOTP_SHORT_URI' => [ + 'HOTP_SHORT_URI' => [ [ 'uri' => OtpTestData::HOTP_SHORT_URI, ], - self::JSON_FRAGMENTS_FOR_DEFAULT_HOTP + self::JSON_FRAGMENTS_FOR_DEFAULT_HOTP, ], - 'ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_HOTP' => [ + 'ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_HOTP' => [ OtpTestData::ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_HOTP, - self::JSON_FRAGMENTS_FOR_CUSTOM_HOTP + self::JSON_FRAGMENTS_FOR_CUSTOM_HOTP, ], - 'ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_HOTP' => [ + 'ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_HOTP' => [ OtpTestData::ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_HOTP, - self::JSON_FRAGMENTS_FOR_DEFAULT_HOTP + self::JSON_FRAGMENTS_FOR_DEFAULT_HOTP, ], ]; } - /** * @test */ @@ -328,7 +322,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ @@ -342,11 +335,10 @@ class TwoFAccountControllerTest extends FeatureTestCase 'uri' => OtpTestData::TOTP_SHORT_URI, ]) ->assertJsonFragment([ - 'group_id' => $this->group->id + 'group_id' => $this->group->id, ]); } - /** * @test */ @@ -362,11 +354,10 @@ class TwoFAccountControllerTest extends FeatureTestCase 'uri' => OtpTestData::TOTP_SHORT_URI, ]) ->assertJsonFragment([ - 'group_id' => $this->group->id + 'group_id' => $this->group->id, ]); } - /** * @test */ @@ -380,11 +371,10 @@ class TwoFAccountControllerTest extends FeatureTestCase 'uri' => OtpTestData::TOTP_SHORT_URI, ]) ->assertJsonFragment([ - 'group_id' => null + 'group_id' => null, ]); } - /** * @test */ @@ -398,11 +388,10 @@ class TwoFAccountControllerTest extends FeatureTestCase 'uri' => OtpTestData::TOTP_SHORT_URI, ]) ->assertJsonFragment([ - 'group_id' => null + 'group_id' => null, ]); } - /** * @test */ @@ -416,7 +405,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonFragment(self::JSON_FRAGMENTS_FOR_CUSTOM_TOTP); } - /** * @test */ @@ -430,7 +418,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonFragment(self::JSON_FRAGMENTS_FOR_CUSTOM_HOTP); } - /** * @test */ @@ -441,7 +428,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertNotFound(); } - /** * @test */ @@ -454,7 +440,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ @@ -462,7 +447,7 @@ class TwoFAccountControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/twofaccounts/migration', [ - 'payload' => OtpTestData::GOOGLE_AUTH_MIGRATION_URI, + 'payload' => OtpTestData::GOOGLE_AUTH_MIGRATION_URI, 'withSecret' => 1, ]) ->assertOk() @@ -476,7 +461,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_DEFAULT, 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null + 'counter' => null, ]) ->assertJsonFragment([ 'id' => 0, @@ -487,11 +472,10 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_DEFAULT, 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null + 'counter' => null, ]); } - /** * @test */ @@ -504,22 +488,21 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ public function test_import_gauth_payload_with_duplicates_returns_negative_ids() { $twofaccount = TwoFAccount::factory()->create([ - 'otp_type' => 'totp', - 'account' => OtpTestData::ACCOUNT, - 'service' => OtpTestData::SERVICE, - 'secret' => OtpTestData::SECRET, - 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, - 'digits' => OtpTestData::DIGITS_DEFAULT, - 'period' => OtpTestData::PERIOD_DEFAULT, + 'otp_type' => 'totp', + 'account' => OtpTestData::ACCOUNT, + 'service' => OtpTestData::SERVICE, + 'secret' => OtpTestData::SECRET, + 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, + 'digits' => OtpTestData::DIGITS_DEFAULT, + 'period' => OtpTestData::PERIOD_DEFAULT, 'legacy_uri' => OtpTestData::TOTP_SHORT_URI, - 'icon' => '', + 'icon' => '', ]); $response = $this->actingAs($this->user, 'api-guard') @@ -528,13 +511,12 @@ class TwoFAccountControllerTest extends FeatureTestCase ]) ->assertOk() ->assertJsonFragment([ - 'id' => -1, - 'service' => OtpTestData::SERVICE, - 'account' => OtpTestData::ACCOUNT, + 'id' => -1, + 'service' => OtpTestData::SERVICE, + 'account' => OtpTestData::ACCOUNT, ]); } - /** * @test */ @@ -546,11 +528,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ]) ->assertStatus(400) ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ @@ -561,7 +542,7 @@ class TwoFAccountControllerTest extends FeatureTestCase $response = $this->withHeaders(['Content-Type' => 'multipart/form-data']) ->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/twofaccounts/migration', [ - 'file' => $file, + 'file' => $file, 'withSecret' => 1, ]) ->assertOk() @@ -575,7 +556,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_DEFAULT, 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null + 'counter' => null, ]) ->assertJsonFragment([ 'id' => 0, @@ -586,7 +567,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_CUSTOM, 'algorithm' => OtpTestData::ALGORITHM_CUSTOM, 'period' => OtpTestData::PERIOD_CUSTOM, - 'counter' => null + 'counter' => null, ]) ->assertJsonFragment([ 'id' => 0, @@ -597,7 +578,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_DEFAULT, 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, 'period' => null, - 'counter' => OtpTestData::COUNTER_DEFAULT + 'counter' => OtpTestData::COUNTER_DEFAULT, ]) ->assertJsonFragment([ 'id' => 0, @@ -619,14 +600,13 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_STEAM, 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null + 'counter' => null, ]); } - /** * @test - * + * * @dataProvider invalidAegisJsonFileProvider */ public function test_import_invalid_aegis_json_file_returns_bad_request($file) @@ -639,7 +619,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(400); } - /** * Provide invalid Aegis JSON files for import tests */ @@ -647,18 +626,17 @@ class TwoFAccountControllerTest extends FeatureTestCase { return [ 'validPlainTextFile' => [ - LocalFile::fake()->encryptedAegisJsonFile() + LocalFile::fake()->encryptedAegisJsonFile(), ], 'validPlainTextFileWithNewLines' => [ - LocalFile::fake()->invalidAegisJsonFile() + LocalFile::fake()->invalidAegisJsonFile(), ], ]; } - /** * @test - * + * * @dataProvider validPlainTextFileProvider */ public function test_import_valid_plain_text_file_returns_success($file) @@ -666,7 +644,7 @@ class TwoFAccountControllerTest extends FeatureTestCase $response = $this->withHeaders(['Content-Type' => 'multipart/form-data']) ->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/twofaccounts/migration', [ - 'file' => $file, + 'file' => $file, 'withSecret' => 1, ]) ->assertOk() @@ -680,7 +658,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_CUSTOM, 'algorithm' => OtpTestData::ALGORITHM_CUSTOM, 'period' => OtpTestData::PERIOD_CUSTOM, - 'counter' => null + 'counter' => null, ]) ->assertJsonFragment([ 'id' => 0, @@ -691,7 +669,7 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_CUSTOM, 'algorithm' => OtpTestData::ALGORITHM_CUSTOM, 'period' => null, - 'counter' => OtpTestData::COUNTER_CUSTOM + 'counter' => OtpTestData::COUNTER_CUSTOM, ]) ->assertJsonFragment([ 'id' => 0, @@ -702,11 +680,10 @@ class TwoFAccountControllerTest extends FeatureTestCase 'digits' => OtpTestData::DIGITS_STEAM, 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null + 'counter' => null, ]); } - /** * Provide valid Plain Text files for import tests */ @@ -714,23 +691,21 @@ class TwoFAccountControllerTest extends FeatureTestCase { return [ 'validPlainTextFile' => [ - LocalFile::fake()->validPlainTextFile() + LocalFile::fake()->validPlainTextFile(), ], 'validPlainTextFileWithNewLines' => [ - LocalFile::fake()->validPlainTextFileWithNewLines() + LocalFile::fake()->validPlainTextFileWithNewLines(), ], ]; } - /** * @test - * + * * @dataProvider invalidPlainTextFileProvider */ public function test_import_invalid_plain_text_file_returns_bad_request($file) { - $response = $this->withHeaders(['Content-Type' => 'multipart/form-data']) ->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/twofaccounts/migration', [ @@ -739,7 +714,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(400); } - /** * Provide invalid Plain Text files for import tests */ @@ -747,21 +721,20 @@ class TwoFAccountControllerTest extends FeatureTestCase { return [ 'validPlainTextFile' => [ - LocalFile::fake()->invalidPlainTextFileEmpty() + LocalFile::fake()->invalidPlainTextFileEmpty(), ], 'validPlainTextFileWithNewLines' => [ - LocalFile::fake()->invalidPlainTextFileNoUri() + LocalFile::fake()->invalidPlainTextFileNoUri(), ], 'validPlainTextFileWithNewLines' => [ - LocalFile::fake()->invalidPlainTextFileWithInvalidUri() + LocalFile::fake()->invalidPlainTextFileWithInvalidUri(), ], 'validPlainTextFileWithNewLines' => [ - LocalFile::fake()->invalidPlainTextFileWithInvalidLine() + LocalFile::fake()->invalidPlainTextFileWithInvalidLine(), ], ]; } - /** * @test */ @@ -771,14 +744,13 @@ class TwoFAccountControllerTest extends FeatureTestCase $response = $this->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/twofaccounts/reorder', [ - 'orderedIds' => [3,2,1]]) + 'orderedIds' => [3, 2, 1], ]) ->assertStatus(200) ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ @@ -788,11 +760,10 @@ class TwoFAccountControllerTest extends FeatureTestCase $response = $this->actingAs($this->user, 'api-guard') ->json('POST', '/api/v1/twofaccounts/reorder', [ - 'orderedIds' => '3,2,1']) + 'orderedIds' => '3,2,1', ]) ->assertStatus(422); } - /** * @test */ @@ -806,7 +777,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonFragment(self::JSON_FRAGMENTS_FOR_CUSTOM_TOTP); } - /** * @test */ @@ -819,7 +789,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ @@ -831,26 +800,25 @@ class TwoFAccountControllerTest extends FeatureTestCase ]) ->assertOk() ->assertJsonFragment([ - 'icon' => null + 'icon' => null, ]); } - /** * @test */ public function test_get_otp_using_totp_twofaccount_id_returns_consistent_resource() { $twofaccount = TwoFAccount::factory()->create([ - 'otp_type' => 'totp', - 'account' => OtpTestData::ACCOUNT, - 'service' => OtpTestData::SERVICE, - 'secret' => OtpTestData::SECRET, - 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, - 'digits' => OtpTestData::DIGITS_DEFAULT, - 'period' => OtpTestData::PERIOD_DEFAULT, + 'otp_type' => 'totp', + 'account' => OtpTestData::ACCOUNT, + 'service' => OtpTestData::SERVICE, + 'secret' => OtpTestData::SECRET, + 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, + 'digits' => OtpTestData::DIGITS_DEFAULT, + 'period' => OtpTestData::PERIOD_DEFAULT, 'legacy_uri' => OtpTestData::TOTP_SHORT_URI, - 'icon' => '', + 'icon' => '', ]); $response = $this->actingAs($this->user, 'api-guard') @@ -859,11 +827,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_OTP_RESOURCE_STRUCTURE_FOR_TOTP) ->assertJsonFragment([ 'otp_type' => 'totp', - 'period' => OtpTestData::PERIOD_DEFAULT, + 'period' => OtpTestData::PERIOD_DEFAULT, ]); } - /** * @test */ @@ -877,11 +844,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_OTP_RESOURCE_STRUCTURE_FOR_TOTP) ->assertJsonFragment([ 'otp_type' => 'totp', - 'period' => OtpTestData::PERIOD_CUSTOM, + 'period' => OtpTestData::PERIOD_CUSTOM, ]); } - /** * @test */ @@ -893,26 +859,25 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_OTP_RESOURCE_STRUCTURE_FOR_TOTP) ->assertJsonFragment([ 'otp_type' => 'totp', - 'period' => OtpTestData::PERIOD_CUSTOM, + 'period' => OtpTestData::PERIOD_CUSTOM, ]); } - /** * @test */ public function test_get_otp_using_hotp_twofaccount_id_returns_consistent_resource() { $twofaccount = TwoFAccount::factory()->create([ - 'otp_type' => 'hotp', - 'account' => OtpTestData::ACCOUNT, - 'service' => OtpTestData::SERVICE, - 'secret' => OtpTestData::SECRET, - 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, - 'digits' => OtpTestData::DIGITS_DEFAULT, - 'period' => null, + 'otp_type' => 'hotp', + 'account' => OtpTestData::ACCOUNT, + 'service' => OtpTestData::SERVICE, + 'secret' => OtpTestData::SECRET, + 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, + 'digits' => OtpTestData::DIGITS_DEFAULT, + 'period' => null, 'legacy_uri' => OtpTestData::HOTP_SHORT_URI, - 'icon' => '', + 'icon' => '', ]); $response = $this->actingAs($this->user, 'api-guard') @@ -921,11 +886,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_OTP_RESOURCE_STRUCTURE_FOR_HOTP) ->assertJsonFragment([ 'otp_type' => 'hotp', - 'counter' => OtpTestData::COUNTER_DEFAULT + 1, + 'counter' => OtpTestData::COUNTER_DEFAULT + 1, ]); } - /** * @test */ @@ -939,11 +903,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_OTP_RESOURCE_STRUCTURE_FOR_HOTP) ->assertJsonFragment([ 'otp_type' => 'hotp', - 'counter' => OtpTestData::COUNTER_CUSTOM + 1, + 'counter' => OtpTestData::COUNTER_CUSTOM + 1, ]); } - /** * @test */ @@ -955,11 +918,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertJsonStructure(self::VALID_OTP_RESOURCE_STRUCTURE_FOR_HOTP) ->assertJsonFragment([ 'otp_type' => 'hotp', - 'counter' => OtpTestData::COUNTER_CUSTOM + 1, + 'counter' => OtpTestData::COUNTER_CUSTOM + 1, ]); } - /** * @test */ @@ -977,7 +939,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -1001,7 +962,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -1012,7 +972,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertNotFound(); } - /** * @test */ @@ -1025,7 +984,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ @@ -1036,7 +994,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertStatus(422); } - /** * @test */ @@ -1048,11 +1005,10 @@ class TwoFAccountControllerTest extends FeatureTestCase ->json('GET', '/api/v1/twofaccounts/count') ->assertStatus(200) ->assertExactJson([ - 'count' => 3 + 'count' => 3, ]); } - /** * @test */ @@ -1069,7 +1025,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -1087,7 +1042,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -1100,7 +1054,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertNoContent(); } - /** * @test */ @@ -1113,7 +1066,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertNotFound(); } - /** * @test */ @@ -1127,7 +1079,6 @@ class TwoFAccountControllerTest extends FeatureTestCase ->assertNoContent(); } - /** * @test */ @@ -1144,5 +1095,4 @@ class TwoFAccountControllerTest extends FeatureTestCase 'reason', ]); } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/GroupAssignRequestTest.php b/tests/Api/v1/Requests/GroupAssignRequestTest.php index d7b084ab..79d7ed0a 100644 --- a/tests/Api/v1/Requests/GroupAssignRequestTest.php +++ b/tests/Api/v1/Requests/GroupAssignRequestTest.php @@ -4,13 +4,12 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\GroupAssignRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class GroupAssignRequestTest extends TestCase { - use WithoutMiddleware; /** @@ -23,7 +22,7 @@ class GroupAssignRequestTest extends TestCase ->andReturn(true); $request = new GroupAssignRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class GroupAssignRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new GroupAssignRequest(); + $request = new GroupAssignRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -46,8 +45,8 @@ class GroupAssignRequestTest extends TestCase return [ [[ 'ids' => [ - 1, 2, 3 - ] + 1, 2, 3, + ], ]], ]; } @@ -57,7 +56,7 @@ class GroupAssignRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new GroupAssignRequest(); + $request = new GroupAssignRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -70,22 +69,21 @@ class GroupAssignRequestTest extends TestCase { return [ [[ - 'ids' => null // required + 'ids' => null, // required ]], [[ - 'ids' => '1,2,3' // array + 'ids' => '1,2,3', // array ]], [[ 'ids' => [ - 'a', 'b', 'c' // array of integers - ] + 'a', 'b', 'c', // array of integers + ], ]], [[ 'ids' => [ - true, false // array of integers - ] + true, false, // array of integers + ], ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/GroupStoreRequestTest.php b/tests/Api/v1/Requests/GroupStoreRequestTest.php index c015506d..ac33bc13 100644 --- a/tests/Api/v1/Requests/GroupStoreRequestTest.php +++ b/tests/Api/v1/Requests/GroupStoreRequestTest.php @@ -2,34 +2,30 @@ namespace Tests\Api\v1\Requests; -use App\Models\Group; use App\Api\v1\Requests\GroupStoreRequest; +use App\Models\Group; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\FeatureTestCase; class GroupStoreRequestTest extends FeatureTestCase { - use WithoutMiddleware; - /** - * - */ protected String $uniqueGroupName = 'MyGroup'; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new GroupStoreRequest(); - + $this->assertTrue($request->authorize()); } @@ -38,7 +34,7 @@ class GroupStoreRequestTest extends FeatureTestCase */ public function test_valid_data(array $data) : void { - $request = new GroupStoreRequest(); + $request = new GroupStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -51,7 +47,7 @@ class GroupStoreRequestTest extends FeatureTestCase { return [ [[ - 'name' => 'validWord' + 'name' => 'validWord', ]], ]; } @@ -67,7 +63,7 @@ class GroupStoreRequestTest extends FeatureTestCase $group->save(); - $request = new GroupStoreRequest(); + $request = new GroupStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -80,21 +76,20 @@ class GroupStoreRequestTest extends FeatureTestCase { return [ [[ - 'name' => '' // required + 'name' => '', // required ]], [[ - 'name' => true // string + 'name' => true, // string ]], [[ - 'name' => 8 // string + 'name' => 8, // string ]], [[ - 'name' => 'mmmmmmoooooorrrrrreeeeeeettttttthhhhhhaaaaaaannnnnn32cccccchhhhhaaaaaarrrrrrsssssss' // max:32 + 'name' => 'mmmmmmoooooorrrrrreeeeeeettttttthhhhhhaaaaaaannnnnn32cccccchhhhhaaaaaarrrrrrsssssss', // max:32 ]], [[ - 'name' => $this->uniqueGroupName // unique + 'name' => $this->uniqueGroupName, // unique ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/QrCodeDecodeRequestTest.php b/tests/Api/v1/Requests/QrCodeDecodeRequestTest.php index 5bfd8b07..6c9e3c49 100644 --- a/tests/Api/v1/Requests/QrCodeDecodeRequestTest.php +++ b/tests/Api/v1/Requests/QrCodeDecodeRequestTest.php @@ -4,27 +4,26 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\QrCodeDecodeRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\Classes\LocalFile; use Tests\TestCase; class QrCodeDecodeRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new QrCodeDecodeRequest(); - + $this->assertTrue($request->authorize()); } @@ -33,7 +32,7 @@ class QrCodeDecodeRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new QrCodeDecodeRequest(); + $request = new QrCodeDecodeRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -48,7 +47,7 @@ class QrCodeDecodeRequestTest extends TestCase return [ [[ - 'qrcode' => $file + 'qrcode' => $file, ]], ]; } @@ -58,7 +57,7 @@ class QrCodeDecodeRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new QrCodeDecodeRequest(); + $request = new QrCodeDecodeRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -71,18 +70,17 @@ class QrCodeDecodeRequestTest extends TestCase { return [ [[ - 'qrcode' => null // required + 'qrcode' => null, // required ]], [[ - 'qrcode' => true // image + 'qrcode' => true, // image ]], [[ - 'qrcode' => 8 // image + 'qrcode' => 8, // image ]], [[ - 'qrcode' => 'string' // image + 'qrcode' => 'string', // image ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/SettingStoreRequestTest.php b/tests/Api/v1/Requests/SettingStoreRequestTest.php index fc04535c..b82fda55 100644 --- a/tests/Api/v1/Requests/SettingStoreRequestTest.php +++ b/tests/Api/v1/Requests/SettingStoreRequestTest.php @@ -3,33 +3,29 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\SettingStoreRequest; -use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; -use Illuminate\Support\Facades\Auth; -use Tests\FeatureTestCase; use App\Facades\Settings; +use Illuminate\Foundation\Testing\WithoutMiddleware; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; +use Tests\FeatureTestCase; class SettingStoreRequestTest extends FeatureTestCase { - use WithoutMiddleware; - /** - * - */ protected String $uniqueKey = 'UniqueKey'; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new SettingStoreRequest(); - + $this->assertTrue($request->authorize()); } @@ -38,7 +34,7 @@ class SettingStoreRequestTest extends FeatureTestCase */ public function test_valid_data(array $data) : void { - $request = new SettingStoreRequest(); + $request = new SettingStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -51,16 +47,16 @@ class SettingStoreRequestTest extends FeatureTestCase { return [ [[ - 'key' => 'MyKey', - 'value' => true + 'key' => 'MyKey', + 'value' => true, ]], [[ - 'key' => 'MyKey', - 'value' => 'MyValue' + 'key' => 'MyKey', + 'value' => 'MyValue', ]], [[ - 'key' => 'MyKey', - 'value' => 10 + 'key' => 'MyKey', + 'value' => 10, ]], ]; } @@ -72,7 +68,7 @@ class SettingStoreRequestTest extends FeatureTestCase { Settings::set($this->uniqueKey, 'uniqueValue'); - $request = new SettingStoreRequest(); + $request = new SettingStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -85,26 +81,25 @@ class SettingStoreRequestTest extends FeatureTestCase { return [ [[ - 'key' => null, // required - 'value' => '' + 'key' => null, // required + 'value' => '', ]], [[ - 'key' => 'my-key', // alpha - 'value' => 'MyValue' + 'key' => 'my-key', // alpha + 'value' => 'MyValue', ]], [[ - 'key' => 10, // alpha - 'value' => 'MyValue' + 'key' => 10, // alpha + 'value' => 'MyValue', ]], [[ - 'key' => 'mmmmmmoooooorrrrrreeeeeeettttttthhhhhhaaaaaaannnnnn128cccccchhhhhaaaaaarrrrrraaaaaaaccccccttttttttteeeeeeeeerrrrrrrrsssssss', // max:128 - 'value' => 'MyValue' + 'key' => 'mmmmmmoooooorrrrrreeeeeeettttttthhhhhhaaaaaaannnnnn128cccccchhhhhaaaaaarrrrrraaaaaaaccccccttttttttteeeeeeeeerrrrrrrrsssssss', // max:128 + 'value' => 'MyValue', ]], [[ - 'key' => $this->uniqueKey, // unique - 'value' => 'MyValue' + 'key' => $this->uniqueKey, // unique + 'value' => 'MyValue', ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/SettingUpdateRequestTest.php b/tests/Api/v1/Requests/SettingUpdateRequestTest.php index 20f99471..5221c068 100644 --- a/tests/Api/v1/Requests/SettingUpdateRequestTest.php +++ b/tests/Api/v1/Requests/SettingUpdateRequestTest.php @@ -4,26 +4,25 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\SettingUpdateRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class SettingUpdateRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new SettingUpdateRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class SettingUpdateRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new SettingUpdateRequest(); + $request = new SettingUpdateRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -45,13 +44,13 @@ class SettingUpdateRequestTest extends TestCase { return [ [[ - 'value' => true + 'value' => true, ]], [[ - 'value' => 'MyValue' + 'value' => 'MyValue', ]], [[ - 'value' => 10 + 'value' => 10, ]], ]; } @@ -61,7 +60,7 @@ class SettingUpdateRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new SettingUpdateRequest(); + $request = new SettingUpdateRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -74,12 +73,11 @@ class SettingUpdateRequestTest extends TestCase { return [ [[ - 'value' => '' // required + 'value' => '', // required ]], [[ - 'value' => null // required + 'value' => null, // required ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/TwoFAccountBatchRequestTest.php b/tests/Api/v1/Requests/TwoFAccountBatchRequestTest.php index 8fc57ed7..7b2958e4 100644 --- a/tests/Api/v1/Requests/TwoFAccountBatchRequestTest.php +++ b/tests/Api/v1/Requests/TwoFAccountBatchRequestTest.php @@ -4,26 +4,25 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\TwoFAccountBatchRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class TwoFAccountBatchRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new TwoFAccountBatchRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class TwoFAccountBatchRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new TwoFAccountBatchRequest(); + $request = new TwoFAccountBatchRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -45,10 +44,10 @@ class TwoFAccountBatchRequestTest extends TestCase { return [ [[ - 'ids' => '1' + 'ids' => '1', ]], [[ - 'ids' => '1,2,5' + 'ids' => '1,2,5', ]], ]; } @@ -58,7 +57,7 @@ class TwoFAccountBatchRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new TwoFAccountBatchRequest(); + $request = new TwoFAccountBatchRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -71,42 +70,41 @@ class TwoFAccountBatchRequestTest extends TestCase { return [ [[ - 'ids' => '' // required + 'ids' => '', // required ]], [[ - 'ids' => null // required + 'ids' => null, // required ]], [[ - 'ids' => true // string + 'ids' => true, // string ]], [[ - 'ids' => 10 // string + 'ids' => 10, // string ]], [[ - 'ids' => 'notaCommaSeparatedList' // regex + 'ids' => 'notaCommaSeparatedList', // regex ]], [[ - 'ids' => 'a,b' // regex + 'ids' => 'a,b', // regex ]], [[ - 'ids' => 'a,1' // regex + 'ids' => 'a,1', // regex ]], [[ - 'ids' => ',1,2' // regex + 'ids' => ',1,2', // regex ]], [[ - 'ids' => '1,,2' // regex + 'ids' => '1,,2', // regex ]], [[ - 'ids' => '1,2,' // regex + 'ids' => '1,2,', // regex ]], [[ - 'ids' => ',1,2,' // regex + 'ids' => ',1,2,', // regex ]], [[ - 'ids' => '1;2' // regex + 'ids' => '1;2', // regex ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/TwoFAccountDynamicRequestTest.php b/tests/Api/v1/Requests/TwoFAccountDynamicRequestTest.php index e7ea534f..2be0b529 100644 --- a/tests/Api/v1/Requests/TwoFAccountDynamicRequestTest.php +++ b/tests/Api/v1/Requests/TwoFAccountDynamicRequestTest.php @@ -3,29 +3,27 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\TwoFAccountDynamicRequest; -use App\Api\v1\Requests\TwoFAccountUriRequest; use App\Api\v1\Requests\TwoFAccountStoreRequest; +use App\Api\v1\Requests\TwoFAccountUriRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; use Tests\TestCase; class TwoFAccountDynamicRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new TwoFAccountDynamicRequest(); - + $this->assertTrue($request->authorize()); } @@ -35,7 +33,7 @@ class TwoFAccountDynamicRequestTest extends TestCase public function test_returns_TwoFAccountUriRequest_rules_when_has_uri_input() { $twofaccountUriRequest = new TwoFAccountUriRequest(); - $request = new TwoFAccountDynamicRequest(); + $request = new TwoFAccountDynamicRequest(); $request->merge(['uri' => 'uristring']); $this->assertEquals($twofaccountUriRequest->rules(), $request->rules()); @@ -47,9 +45,8 @@ class TwoFAccountDynamicRequestTest extends TestCase public function test_returns_TwoFAccountStoreRequest_rules_otherwise() { $twofaccountStoreRequest = new TwoFAccountStoreRequest(); - $request = new TwoFAccountDynamicRequest(); + $request = new TwoFAccountDynamicRequest(); $this->assertEquals($twofaccountStoreRequest->rules(), $request->rules()); } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/TwoFAccountImportRequestTest.php b/tests/Api/v1/Requests/TwoFAccountImportRequestTest.php index 05744ab2..07a48e18 100644 --- a/tests/Api/v1/Requests/TwoFAccountImportRequestTest.php +++ b/tests/Api/v1/Requests/TwoFAccountImportRequestTest.php @@ -4,26 +4,25 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\TwoFAccountImportRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class TwoFAccountImportRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new TwoFAccountImportRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class TwoFAccountImportRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new TwoFAccountImportRequest(); + $request = new TwoFAccountImportRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -45,7 +44,7 @@ class TwoFAccountImportRequestTest extends TestCase { return [ [[ - 'payload' => 'otpauth-migration://offline?data=AEoATACEAEYASAA' + 'payload' => 'otpauth-migration://offline?data=AEoATACEAEYASAA', ]], ]; } @@ -55,7 +54,7 @@ class TwoFAccountImportRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new TwoFAccountImportRequest(); + $request = new TwoFAccountImportRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -68,18 +67,17 @@ class TwoFAccountImportRequestTest extends TestCase { return [ [[ - 'payload' => null // required + 'payload' => null, // required ]], [[ - 'payload' => '' // required + 'payload' => '', // required ]], [[ - 'payload' => true // string + 'payload' => true, // string ]], [[ - 'payload' => 8 // string - ]] + 'payload' => 8, // string + ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/TwoFAccountReorderRequestTest.php b/tests/Api/v1/Requests/TwoFAccountReorderRequestTest.php index 9cfe8931..82c967cd 100644 --- a/tests/Api/v1/Requests/TwoFAccountReorderRequestTest.php +++ b/tests/Api/v1/Requests/TwoFAccountReorderRequestTest.php @@ -4,26 +4,25 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\TwoFAccountReorderRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class TwoFAccountReorderRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new TwoFAccountReorderRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class TwoFAccountReorderRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new TwoFAccountReorderRequest(); + $request = new TwoFAccountReorderRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -45,10 +44,10 @@ class TwoFAccountReorderRequestTest extends TestCase { return [ [[ - 'orderedIds' => [1,2,5] + 'orderedIds' => [1, 2, 5], ]], [[ - 'orderedIds' => [5] + 'orderedIds' => [5], ]], ]; } @@ -58,7 +57,7 @@ class TwoFAccountReorderRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new TwoFAccountReorderRequest(); + $request = new TwoFAccountReorderRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -71,21 +70,20 @@ class TwoFAccountReorderRequestTest extends TestCase { return [ [[ - 'orderedIds' => [] // required + 'orderedIds' => [], // required ]], [[ - 'orderedIds' => null // required + 'orderedIds' => null, // required ]], [[ - 'orderedIds' => 0 // array + 'orderedIds' => 0, // array ]], [[ - 'orderedIds' => 'string' // array + 'orderedIds' => 'string', // array ]], [[ - 'orderedIds' => true // array + 'orderedIds' => true, // array ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/TwoFAccountStoreRequestTest.php b/tests/Api/v1/Requests/TwoFAccountStoreRequestTest.php index 0d3002d5..b42898ad 100644 --- a/tests/Api/v1/Requests/TwoFAccountStoreRequestTest.php +++ b/tests/Api/v1/Requests/TwoFAccountStoreRequestTest.php @@ -4,26 +4,25 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\TwoFAccountStoreRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class TwoFAccountStoreRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new TwoFAccountStoreRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class TwoFAccountStoreRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new TwoFAccountStoreRequest(); + $request = new TwoFAccountStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -45,52 +44,52 @@ class TwoFAccountStoreRequestTest extends TestCase { return [ [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => 'icon.png', - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => 'icon.png', + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => 'sha1', - 'period' => 30, + 'period' => 30, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => 'icon.png', - 'otp_type' => 'hotp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 8, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => 'icon.png', + 'otp_type' => 'hotp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 8, 'algorithm' => 'sha1', - 'counter' => 10, + 'counter' => 10, ]], [[ - 'service' => null, - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'hotp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => null, + 'service' => null, + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'hotp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => null, 'algorithm' => null, - 'counter' => null, + 'counter' => null, ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'totp', ]], [[ - 'account' => 'MyAccount', - 'otp_type' => 'totp', + 'account' => 'MyAccount', + 'otp_type' => 'totp', 'algorithm' => 'sha256', ]], [[ - 'account' => 'MyAccount', - 'otp_type' => 'totp', + 'account' => 'MyAccount', + 'otp_type' => 'totp', 'algorithm' => 'sha512', ]], [[ - 'account' => 'MyAccount', - 'otp_type' => 'totp', + 'account' => 'MyAccount', + 'otp_type' => 'totp', 'algorithm' => 'md5', ]], ]; @@ -101,7 +100,7 @@ class TwoFAccountStoreRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new TwoFAccountStoreRequest(); + $request = new TwoFAccountStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -114,58 +113,57 @@ class TwoFAccountStoreRequestTest extends TestCase { return [ [[ - 'account' => 'My:Account', + 'account' => 'My:Account', 'otp_type' => 'totp', ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'Xotp', ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => null, ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'totp', - 'service' => 'My:Service', + 'service' => 'My:Service', ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'totp', - 'secret' => 'notaBase32String', + 'secret' => 'notaBase32String', ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'totp', - 'secret' => 123456, + 'secret' => 123456, ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'totp', - 'digits' => 4, + 'digits' => 4, ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'totp', - 'digits' => 11, + 'digits' => 11, ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'totp', - 'period' => 0, + 'period' => 0, ]], [[ - 'account' => 'MyAccount', + 'account' => 'MyAccount', 'otp_type' => 'hotp', - 'counter' => -1, + 'counter' => -1, ]], [[ - 'account' => 'MyAccount', - 'otp_type' => 'totp', + 'account' => 'MyAccount', + 'otp_type' => 'totp', 'algorithm' => 'shaX', ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/TwoFAccountUpdateRequestTest.php b/tests/Api/v1/Requests/TwoFAccountUpdateRequestTest.php index eb4040af..50ea1e7f 100644 --- a/tests/Api/v1/Requests/TwoFAccountUpdateRequestTest.php +++ b/tests/Api/v1/Requests/TwoFAccountUpdateRequestTest.php @@ -4,26 +4,25 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\TwoFAccountUpdateRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class TwoFAccountUpdateRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new TwoFAccountUpdateRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class TwoFAccountUpdateRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new TwoFAccountUpdateRequest(); + $request = new TwoFAccountUpdateRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -45,35 +44,35 @@ class TwoFAccountUpdateRequestTest extends TestCase { return [ [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => 'icon.png', - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => 'icon.png', + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => 'sha1', - 'period' => 30, + 'period' => 30, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => 'icon.png', - 'otp_type' => 'hotp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 8, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => 'icon.png', + 'otp_type' => 'hotp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 8, 'algorithm' => 'sha1', - 'counter' => 10, + 'counter' => 10, ]], [[ - 'service' => null, - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'hotp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 10, + 'service' => null, + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'hotp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 10, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], ]; } @@ -83,7 +82,7 @@ class TwoFAccountUpdateRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new TwoFAccountUpdateRequest(); + $request = new TwoFAccountUpdateRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -96,127 +95,126 @@ class TwoFAccountUpdateRequestTest extends TestCase { return [ [[ - 'service' => null, - 'account' => 'My:Account', - 'icon' => null, - 'otp_type' => 'hotp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => null, + 'account' => 'My:Account', + 'icon' => null, + 'otp_type' => 'hotp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => 'My:Service', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'hotp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => 'My:Service', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'hotp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => null, - 'account' => 'My:Account', - 'icon' => null, - 'otp_type' => 'Xotp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => null, + 'account' => 'My:Account', + 'icon' => null, + 'otp_type' => 'Xotp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => null, - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'hotp', - 'secret' => 'notaBase32String', - 'digits' => 6, + 'service' => null, + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'hotp', + 'secret' => 'notaBase32String', + 'digits' => 6, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 4, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 4, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 11, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 11, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => 'Xsha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => 'sha1', - 'period' => 0, - 'counter' => 15, + 'period' => 0, + 'counter' => 15, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 4, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 4, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => -1, + 'period' => null, + 'counter' => -1, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => null, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => null, 'algorithm' => 'sha1', - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], [[ - 'service' => 'MyService', - 'account' => 'MyAccount', - 'icon' => null, - 'otp_type' => 'totp', - 'secret' => 'A4GRFHZVRBGY7UIW', - 'digits' => 6, + 'service' => 'MyService', + 'account' => 'MyAccount', + 'icon' => null, + 'otp_type' => 'totp', + 'secret' => 'A4GRFHZVRBGY7UIW', + 'digits' => 6, 'algorithm' => null, - 'period' => null, - 'counter' => 15, + 'period' => null, + 'counter' => 15, ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Api/v1/Requests/TwoFAccountUriRequestTest.php b/tests/Api/v1/Requests/TwoFAccountUriRequestTest.php index dcc582d5..68faa283 100644 --- a/tests/Api/v1/Requests/TwoFAccountUriRequestTest.php +++ b/tests/Api/v1/Requests/TwoFAccountUriRequestTest.php @@ -4,26 +4,25 @@ namespace Tests\Api\v1\Requests; use App\Api\v1\Requests\TwoFAccountUriRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; class TwoFAccountUriRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new TwoFAccountUriRequest(); - + $this->assertTrue($request->authorize()); } @@ -32,7 +31,7 @@ class TwoFAccountUriRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new TwoFAccountUriRequest(); + $request = new TwoFAccountUriRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -44,15 +43,15 @@ class TwoFAccountUriRequestTest extends TestCase public function provideValidData() : array { return [ - [[ - 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test' - ]], - [[ - 'uri' => 'otpauth://hotp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test' - ]], [[ 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', - 'custom_otp' => 'steamtotp' + ]], + [[ + 'uri' => 'otpauth://hotp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', + ]], + [[ + 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', + 'custom_otp' => 'steamtotp', ]], ]; } @@ -62,7 +61,7 @@ class TwoFAccountUriRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new TwoFAccountUriRequest(); + $request = new TwoFAccountUriRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -75,33 +74,32 @@ class TwoFAccountUriRequestTest extends TestCase { return [ [[ - 'uri' => null // required + 'uri' => null, // required ]], [[ - 'uri' => '' // required + 'uri' => '', // required ]], [[ - 'uri' => true // string + 'uri' => true, // string ]], [[ - 'uri' => 8 // string + 'uri' => 8, // string ]], [[ - 'uri' => 'otpXauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test' // regex + 'uri' => 'otpXauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', // regex ]], [[ - 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', - 'custom_otp' => 'notSteam' // not in + 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', + 'custom_otp' => 'notSteam', // not in ]], [[ - 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', - 'custom_otp' => 0 // string + 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', + 'custom_otp' => 0, // string ]], [[ - 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', - 'custom_otp' => true // string + 'uri' => 'otpauth://totp/test@test.com?secret=A4GRFHZVRBGY7UIW&issuer=test', + 'custom_otp' => true, // string ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Classes/LocalFile.php b/tests/Classes/LocalFile.php index 46e7bc59..aba9e7aa 100644 --- a/tests/Classes/LocalFile.php +++ b/tests/Classes/LocalFile.php @@ -6,7 +6,6 @@ use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile; class LocalFile extends SymfonyUploadedFile { - /** * Begin creating a new local file fake. * @@ -16,5 +15,4 @@ class LocalFile extends SymfonyUploadedFile { return new LocalFileFactory; } - } diff --git a/tests/Classes/LocalFileFactory.php b/tests/Classes/LocalFileFactory.php index 4dfa0350..53864e39 100644 --- a/tests/Classes/LocalFileFactory.php +++ b/tests/Classes/LocalFileFactory.php @@ -3,10 +3,9 @@ namespace Tests\Classes; use Illuminate\Http\Testing\File; -use Tests\Classes\OtpTestData; - -class LocalFileFactory { +class LocalFileFactory +{ /** * Create a new local valid qrcode image. * @@ -28,7 +27,6 @@ class LocalFileFactory { })); } - /** * Create a new local invalid qrcode image. * @@ -50,7 +48,6 @@ class LocalFileFactory { })); } - /** * Create a new local valid Aegis JSON file. * @@ -67,7 +64,6 @@ class LocalFileFactory { })); } - /** * Create a new local invalid Aegis JSON file. * @@ -84,7 +80,6 @@ class LocalFileFactory { })); } - /** * Create a new local encrypted Aegis JSON file. * @@ -101,7 +96,6 @@ class LocalFileFactory { })); } - /** * Create a new local valid Plain Text file. * @@ -122,7 +116,6 @@ class LocalFileFactory { })); } - /** * Create a new local valid Plain Text file with new lines. * @@ -147,7 +140,6 @@ class LocalFileFactory { })); } - /** * Create a new local invalid Plain Text file with no URI. * @@ -166,7 +158,6 @@ class LocalFileFactory { })); } - /** * Create a new local invalid Plain Text file with invalid line. * @@ -187,7 +178,6 @@ class LocalFileFactory { })); } - /** * Create a new local invalid Plain Text file with invalid URI. * @@ -208,7 +198,6 @@ class LocalFileFactory { })); } - /** * Create a new local empty Plain Text file. * @@ -224,6 +213,4 @@ class LocalFileFactory { fwrite($temp, ob_get_clean()); })); } - - } diff --git a/tests/Classes/OtpTestData.php b/tests/Classes/OtpTestData.php index 0f62f728..04e3e80d 100644 --- a/tests/Classes/OtpTestData.php +++ b/tests/Classes/OtpTestData.php @@ -5,28 +5,50 @@ namespace Tests\Classes; class OtpTestData { const ACCOUNT = 'account'; + const SERVICE = 'service'; + const STEAM = 'Steam'; + const SECRET = 'A4GRFHVVRBGY7UIW'; + const STEAM_SECRET = 'XJGTDRUUKZH3X7TQN2QZUGCGXZCC5LXE'; + const ALGORITHM_DEFAULT = 'sha1'; + const ALGORITHM_CUSTOM = 'sha256'; + const DIGITS_DEFAULT = 6; + const DIGITS_CUSTOM = 7; + const DIGITS_STEAM = 5; + const PERIOD_DEFAULT = 30; + const PERIOD_CUSTOM = 40; + const COUNTER_DEFAULT = 0; + const COUNTER_CUSTOM = 5; + const IMAGE = 'https%3A%2F%2Fen.opensuse.org%2Fimages%2F4%2F44%2FButton-filled-colour.png'; + const ICON = 'test.png'; - const TOTP_FULL_CUSTOM_URI = 'otpauth://totp/'.self::SERVICE.':'.self::ACCOUNT.'?secret='.self::SECRET.'&issuer='.self::SERVICE.'&digits='.self::DIGITS_CUSTOM.'&period='.self::PERIOD_CUSTOM.'&algorithm='.self::ALGORITHM_CUSTOM.'&image='.self::IMAGE; - const HOTP_FULL_CUSTOM_URI = 'otpauth://hotp/'.self::SERVICE.':'.self::ACCOUNT.'?secret='.self::SECRET.'&issuer='.self::SERVICE.'&digits='.self::DIGITS_CUSTOM.'&counter='.self::COUNTER_CUSTOM.'&algorithm='.self::ALGORITHM_CUSTOM.'&image='.self::IMAGE; - const TOTP_SHORT_URI = 'otpauth://totp/'.self::ACCOUNT.'?secret='.self::SECRET; - const HOTP_SHORT_URI = 'otpauth://hotp/'.self::ACCOUNT.'?secret='.self::SECRET; + + const TOTP_FULL_CUSTOM_URI = 'otpauth://totp/' . self::SERVICE . ':' . self::ACCOUNT . '?secret=' . self::SECRET . '&issuer=' . self::SERVICE . '&digits=' . self::DIGITS_CUSTOM . '&period=' . self::PERIOD_CUSTOM . '&algorithm=' . self::ALGORITHM_CUSTOM . '&image=' . self::IMAGE; + + const HOTP_FULL_CUSTOM_URI = 'otpauth://hotp/' . self::SERVICE . ':' . self::ACCOUNT . '?secret=' . self::SECRET . '&issuer=' . self::SERVICE . '&digits=' . self::DIGITS_CUSTOM . '&counter=' . self::COUNTER_CUSTOM . '&algorithm=' . self::ALGORITHM_CUSTOM . '&image=' . self::IMAGE; + + const TOTP_SHORT_URI = 'otpauth://totp/' . self::ACCOUNT . '?secret=' . self::SECRET; + + const HOTP_SHORT_URI = 'otpauth://hotp/' . self::ACCOUNT . '?secret=' . self::SECRET; + const TOTP_URI_WITH_UNREACHABLE_IMAGE = 'otpauth://totp/service:account?secret=A4GRFHVVRBGY7UIW&image=https%3A%2F%2Fen.opensuse.org%2Fimage.png'; - const INVALID_OTPAUTH_URI = 'otpauth://Xotp/'.self::ACCOUNT.'?secret='.self::SECRET; - const STEAM_TOTP_URI = 'otpauth://totp/'.self::STEAM.':'.self::ACCOUNT.'?secret='.self::STEAM_SECRET.'&issuer='.self::STEAM.'&digits='.self::DIGITS_STEAM.'&period=30&algorithm='.self::ALGORITHM_DEFAULT; + + const INVALID_OTPAUTH_URI = 'otpauth://Xotp/' . self::ACCOUNT . '?secret=' . self::SECRET; + + const STEAM_TOTP_URI = 'otpauth://totp/' . self::STEAM . ':' . self::ACCOUNT . '?secret=' . self::STEAM_SECRET . '&issuer=' . self::STEAM . '&digits=' . self::DIGITS_STEAM . '&period=30&algorithm=' . self::ALGORITHM_DEFAULT; const ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_TOTP = [ 'service' => self::SERVICE, @@ -39,21 +61,25 @@ class OtpTestData 'period' => self::PERIOD_CUSTOM, 'counter' => null, ]; + const ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_TOTP = [ - 'account' => self::ACCOUNT, - 'otp_type' => 'totp', - 'secret' => self::SECRET, + 'account' => self::ACCOUNT, + 'otp_type' => 'totp', + 'secret' => self::SECRET, ]; + const ARRAY_OF_PARAMETERS_FOR_UNSUPPORTED_OTP_TYPE = [ - 'account' => self::ACCOUNT, - 'otp_type' => 'Xotp', - 'secret' => self::SECRET, + 'account' => self::ACCOUNT, + 'otp_type' => 'Xotp', + 'secret' => self::SECRET, ]; + const ARRAY_OF_INVALID_PARAMETERS_FOR_TOTP = [ - 'account' => self::ACCOUNT, - 'otp_type' => 'totp', - 'secret' => 0, + 'account' => self::ACCOUNT, + 'otp_type' => 'totp', + 'secret' => 0, ]; + const ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_HOTP = [ 'service' => self::SERVICE, 'account' => self::ACCOUNT, @@ -65,11 +91,13 @@ class OtpTestData 'period' => null, 'counter' => self::COUNTER_CUSTOM, ]; + const ARRAY_OF_MINIMUM_VALID_PARAMETERS_FOR_HOTP = [ - 'account' => self::ACCOUNT, - 'otp_type' => 'hotp', - 'secret' => self::SECRET, + 'account' => self::ACCOUNT, + 'otp_type' => 'hotp', + 'secret' => self::SECRET, ]; + const ARRAY_OF_FULL_VALID_PARAMETERS_FOR_STEAM_TOTP = [ 'service' => self::STEAM, 'account' => self::ACCOUNT, @@ -82,7 +110,9 @@ class OtpTestData ]; const GOOGLE_AUTH_MIGRATION_URI = 'otpauth-migration://offline?data=CiQKCgcNEp61iE2P0RYSB2FjY291bnQaB3NlcnZpY2UgASgBMAIKLAoKBw0SnrWITY/RFhILYWNjb3VudF9iaXMaC3NlcnZpY2VfYmlzIAEoATACEAEYASAA'; + const INVALID_GOOGLE_AUTH_MIGRATION_URI = 'otpauthmigration://offline?data=CiQKCgcNEp61iE2P0RYSB2FjY291bnQaB3NlcnZpY2UgASgBMAIKLAoKBw0SnrWITY/RFhILYWNjb3VudF9iaXMaC3NlcnZpY2VfYmlzIAEoATACEAEYASAA'; + const GOOGLE_AUTH_MIGRATION_URI_WITH_INVALID_DATA = 'otpauth-migration://offline?data=CiQKCgcNEp61iE2P0RYSB2FjY291bnQaB3NlcnZpY'; const AEGIS_JSON_MIGRATION_PAYLOAD = ' @@ -98,71 +128,71 @@ class OtpTestData { "type": "totp", "uuid": "5be1b189-260d-4fe1-930a-a78cb669dd86", - "name": "'.self::ACCOUNT.'_totp", - "issuer": "'.self::SERVICE.'_totp", + "name": "' . self::ACCOUNT . '_totp", + "issuer": "' . self::SERVICE . '_totp", "note": "", "icon": null, "info": { - "secret": "'.self::SECRET.'", - "algo": "'.self::ALGORITHM_DEFAULT.'", - "digits": '.self::DIGITS_DEFAULT.', - "period": '.self::PERIOD_DEFAULT.' + "secret": "' . self::SECRET . '", + "algo": "' . self::ALGORITHM_DEFAULT . '", + "digits": ' . self::DIGITS_DEFAULT . ', + "period": ' . self::PERIOD_DEFAULT . ' } }, { "type": "totp", "uuid": "fb2ebd05-9d71-4b2e-9d4e-b7f8d2942bfb", - "name": "'.self::ACCOUNT.'_totp_custom", - "issuer": "'.self::SERVICE.'_totp_custom", + "name": "' . self::ACCOUNT . '_totp_custom", + "issuer": "' . self::SERVICE . '_totp_custom", "note": "", "icon": null, "info": { - "secret": "'.self::SECRET.'", - "algo": "'.self::ALGORITHM_CUSTOM.'", - "digits": '.self::DIGITS_CUSTOM.', - "period": '.self::PERIOD_CUSTOM.' + "secret": "' . self::SECRET . '", + "algo": "' . self::ALGORITHM_CUSTOM . '", + "digits": ' . self::DIGITS_CUSTOM . ', + "period": ' . self::PERIOD_CUSTOM . ' } }, { "type": "hotp", "uuid": "90a2af2e-2857-4515-bb18-52c4fa823f6f", - "name": "'.self::ACCOUNT.'_hotp", - "issuer": "'.self::SERVICE.'_hotp", + "name": "' . self::ACCOUNT . '_hotp", + "issuer": "' . self::SERVICE . '_hotp", "note": "", "icon": null, "info": { - "secret": "'.self::SECRET.'", - "algo": "'.self::ALGORITHM_DEFAULT.'", - "digits": '.self::DIGITS_DEFAULT.', - "counter": '.self::COUNTER_DEFAULT.' + "secret": "' . self::SECRET . '", + "algo": "' . self::ALGORITHM_DEFAULT . '", + "digits": ' . self::DIGITS_DEFAULT . ', + "counter": ' . self::COUNTER_DEFAULT . ' } }, { "type": "hotp", "uuid": "e1b3f683-d5fe-4126-b616-8c8abd8ad97c", - "name": "'.self::ACCOUNT.'_hotp_custom", - "issuer": "'.self::SERVICE.'_hotp_custom", + "name": "' . self::ACCOUNT . '_hotp_custom", + "issuer": "' . self::SERVICE . '_hotp_custom", "note": "", "icon": null, "info": { - "secret": "'.self::SECRET.'", - "algo": "'.self::ALGORITHM_CUSTOM.'", - "digits": '.self::DIGITS_CUSTOM.', - "counter": '.self::COUNTER_CUSTOM.' + "secret": "' . self::SECRET . '", + "algo": "' . self::ALGORITHM_CUSTOM . '", + "digits": ' . self::DIGITS_CUSTOM . ', + "counter": ' . self::COUNTER_CUSTOM . ' } }, { "type": "steamtotp", "uuid": "9fb06143-421d-46e1-a7e9-4aafe44b0e72", - "name": "'.self::ACCOUNT.'_steam", - "issuer": "'.self::STEAM.'", + "name": "' . self::ACCOUNT . '_steam", + "issuer": "' . self::STEAM . '", "note": "", "icon": "null", "info": { - "secret": "'.self::STEAM_SECRET.'", - "algo": "'.self::ALGORITHM_DEFAULT.'", - "digits": '.self::DIGITS_STEAM.', - "period": '.self::PERIOD_DEFAULT.' + "secret": "' . self::STEAM_SECRET . '", + "algo": "' . self::ALGORITHM_DEFAULT . '", + "digits": ' . self::DIGITS_STEAM . ', + "period": ' . self::PERIOD_DEFAULT . ' } } ] @@ -182,15 +212,15 @@ class OtpTestData { "type": "totp", "uuid": "5be1b189-260d-4fe1-930a-a78cb669dd86", - "name": "'.self::ACCOUNT.'", - "issuer": "'.self::SERVICE.'", + "name": "' . self::ACCOUNT . '", + "issuer": "' . self::SERVICE . '", "note": "", "icon": null, "info": { - "secret": "'.self::SECRET.'", - "algo": "'.self::ALGORITHM_DEFAULT.'", - "digits": '.self::DIGITS_DEFAULT.', - "period": '.self::PERIOD_DEFAULT.' + "secret": "' . self::SECRET . '", + "algo": "' . self::ALGORITHM_DEFAULT . '", + "digits": ' . self::DIGITS_DEFAULT . ', + "period": ' . self::PERIOD_DEFAULT . ' } } ] @@ -224,5 +254,4 @@ class OtpTestData }, "db": "1rX0ajzsxNbhN2hvnNCMBNooLlzqwz\/LMT3bNEIJjPH+zIvIbA6GVVPHLpna+yvjxLPKVkt1OQig==" }'; - } diff --git a/tests/CreatesApplication.php b/tests/CreatesApplication.php index 547152f6..ab924025 100644 --- a/tests/CreatesApplication.php +++ b/tests/CreatesApplication.php @@ -13,7 +13,7 @@ trait CreatesApplication */ public function createApplication() { - $app = require __DIR__.'/../bootstrap/app.php'; + $app = require __DIR__ . '/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); diff --git a/tests/Feature/Console/CheckDbConnectionTest.php b/tests/Feature/Console/CheckDbConnectionTest.php index 9475c3c9..a243fea6 100644 --- a/tests/Feature/Console/CheckDbConnectionTest.php +++ b/tests/Feature/Console/CheckDbConnectionTest.php @@ -2,18 +2,14 @@ namespace Tests\Feature\Console; -use App\Models\User; -use Tests\FeatureTestCase; -use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\DB; - +use Tests\FeatureTestCase; /** * @covers \App\Console\Commands\CheckDbConnection */ class CheckDbConnectionTest extends FeatureTestCase { - /** * @test */ @@ -33,7 +29,7 @@ class CheckDbConnectionTest extends FeatureTestCase DB::shouldReceive('connection', 'getPDO') ->andThrow(new \Exception()); - $this->artisan('2fauth:check-db-connection') + $this->artisan('2fauth:check-db-connection') ->assertExitCode(0); } -} \ No newline at end of file +} diff --git a/tests/Feature/Console/ResetDemoTest.php b/tests/Feature/Console/ResetDemoTest.php index 743441da..ca7d8edc 100644 --- a/tests/Feature/Console/ResetDemoTest.php +++ b/tests/Feature/Console/ResetDemoTest.php @@ -2,12 +2,11 @@ namespace Tests\Feature\Console; -use Tests\FeatureTestCase; use Illuminate\Support\Facades\Config; +use Tests\FeatureTestCase; class ResetDemoTest extends FeatureTestCase { - /** * @test */ @@ -33,108 +32,106 @@ class ResetDemoTest extends FeatureTestCase $this->assertDatabaseCount('twofaccounts', 9); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'johndoe@facebook.com', - 'service' => 'Facebook', - 'secret' => 'A4GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'facebook.png', + 'otp_type' => 'totp', + 'account' => 'johndoe@facebook.com', + 'service' => 'Facebook', + 'secret' => 'A4GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'facebook.png', 'legacy_uri' => 'otpauth://totp/Facebook:johndoe@facebook.com?secret=A4GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'Twitter', - 'account' => '@john', - 'secret' => 'A2GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'twitter.png', + 'otp_type' => 'totp', + 'service' => 'Twitter', + 'account' => '@john', + 'secret' => 'A2GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'twitter.png', 'legacy_uri' => 'otpauth://totp/Twitter:@john?secret=A2GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'Instagram', - 'account' => '@johndoe', - 'secret' => 'A6GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'instagram.png', + 'otp_type' => 'totp', + 'service' => 'Instagram', + 'account' => '@johndoe', + 'secret' => 'A6GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'instagram.png', 'legacy_uri' => 'otpauth://totp/Instagram:@johndoe?secret=A6GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'LinkedIn', - 'account' => '@johndoe', - 'secret' => 'A7GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'linkedin.png', + 'otp_type' => 'totp', + 'service' => 'LinkedIn', + 'account' => '@johndoe', + 'secret' => 'A7GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'linkedin.png', 'legacy_uri' => 'otpauth://totp/LinkedIn:@johndoe?secret=A7GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'johndoe', - 'service' => 'Amazon', - 'secret' => 'A7GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'amazon.png', + 'otp_type' => 'totp', + 'account' => 'johndoe', + 'service' => 'Amazon', + 'secret' => 'A7GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'amazon.png', 'legacy_uri' => 'otpauth://totp/Amazon:johndoe?secret=A7GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'john.doe@icloud.com', - 'service' => 'Apple', - 'secret' => 'A2GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'apple.png', + 'otp_type' => 'totp', + 'account' => 'john.doe@icloud.com', + 'service' => 'Apple', + 'secret' => 'A2GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'apple.png', 'legacy_uri' => 'otpauth://totp/Apple:john.doe@icloud.com?secret=A2GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'john.doe', - 'service' => 'Dropbox', - 'secret' => 'A3GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'dropbox.png', + 'otp_type' => 'totp', + 'account' => 'john.doe', + 'service' => 'Dropbox', + 'secret' => 'A3GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'dropbox.png', 'legacy_uri' => 'otpauth://totp/Dropbox:john.doe?secret=A3GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => '@john', - 'service' => 'Github', - 'secret' => 'A2GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'github.png', + 'otp_type' => 'totp', + 'account' => '@john', + 'service' => 'Github', + 'secret' => 'A2GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'github.png', 'legacy_uri' => 'otpauth://totp/Github:@john?secret=A2GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'Google', - 'account' => 'john.doe@gmail.com', - 'secret' => 'A5GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'google.png', + 'otp_type' => 'totp', + 'service' => 'Google', + 'account' => 'john.doe@gmail.com', + 'secret' => 'A5GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'google.png', 'legacy_uri' => 'otpauth://totp/Google:john.doe@gmail.com?secret=A5GRFTVVRBGY7UIW', ]); - } - /** * @test */ @@ -148,7 +145,6 @@ class ResetDemoTest extends FeatureTestCase ->assertSuccessful(); } - /** * @test */ @@ -157,9 +153,8 @@ class ResetDemoTest extends FeatureTestCase Config::set('2fauth.config.isDemoApp', true); $this->artisan('2fauth:reset-demo', [ - '--no-confirm' => true - ]) + '--no-confirm' => true, + ]) ->assertSuccessful(); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Console/ResetTestingTest.php b/tests/Feature/Console/ResetTestingTest.php index ac7afbbc..f710968b 100644 --- a/tests/Feature/Console/ResetTestingTest.php +++ b/tests/Feature/Console/ResetTestingTest.php @@ -2,12 +2,11 @@ namespace Tests\Feature\Console; -use Tests\FeatureTestCase; use Illuminate\Support\Facades\Config; +use Tests\FeatureTestCase; class ResetTestingTest extends FeatureTestCase { - /** * @test */ @@ -33,108 +32,106 @@ class ResetTestingTest extends FeatureTestCase $this->assertDatabaseCount('twofaccounts', 9); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'johndoe@facebook.com', - 'service' => 'Facebook', - 'secret' => 'A4GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'facebook.png', + 'otp_type' => 'totp', + 'account' => 'johndoe@facebook.com', + 'service' => 'Facebook', + 'secret' => 'A4GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'facebook.png', 'legacy_uri' => 'otpauth://totp/Facebook:johndoe@facebook.com?secret=A4GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'Twitter', - 'account' => '@john', - 'secret' => 'A2GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'twitter.png', + 'otp_type' => 'totp', + 'service' => 'Twitter', + 'account' => '@john', + 'secret' => 'A2GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'twitter.png', 'legacy_uri' => 'otpauth://totp/Twitter:@john?secret=A2GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'Instagram', - 'account' => '@johndoe', - 'secret' => 'A6GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'instagram.png', + 'otp_type' => 'totp', + 'service' => 'Instagram', + 'account' => '@johndoe', + 'secret' => 'A6GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'instagram.png', 'legacy_uri' => 'otpauth://totp/Instagram:@johndoe?secret=A6GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'LinkedIn', - 'account' => '@johndoe', - 'secret' => 'A7GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'linkedin.png', + 'otp_type' => 'totp', + 'service' => 'LinkedIn', + 'account' => '@johndoe', + 'secret' => 'A7GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'linkedin.png', 'legacy_uri' => 'otpauth://totp/LinkedIn:@johndoe?secret=A7GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'johndoe', - 'service' => 'Amazon', - 'secret' => 'A7GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'amazon.png', + 'otp_type' => 'totp', + 'account' => 'johndoe', + 'service' => 'Amazon', + 'secret' => 'A7GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'amazon.png', 'legacy_uri' => 'otpauth://totp/Amazon:johndoe?secret=A7GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'john.doe@icloud.com', - 'service' => 'Apple', - 'secret' => 'A2GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'apple.png', + 'otp_type' => 'totp', + 'account' => 'john.doe@icloud.com', + 'service' => 'Apple', + 'secret' => 'A2GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'apple.png', 'legacy_uri' => 'otpauth://totp/Apple:john.doe@icloud.com?secret=A2GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => 'john.doe', - 'service' => 'Dropbox', - 'secret' => 'A3GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'dropbox.png', + 'otp_type' => 'totp', + 'account' => 'john.doe', + 'service' => 'Dropbox', + 'secret' => 'A3GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'dropbox.png', 'legacy_uri' => 'otpauth://totp/Dropbox:john.doe?secret=A3GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'account' => '@john', - 'service' => 'Github', - 'secret' => 'A2GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'github.png', + 'otp_type' => 'totp', + 'account' => '@john', + 'service' => 'Github', + 'secret' => 'A2GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'github.png', 'legacy_uri' => 'otpauth://totp/Github:@john?secret=A2GRFTVVRBGY7UIW', ]); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => 'Google', - 'account' => 'john.doe@gmail.com', - 'secret' => 'A5GRFTVVRBGY7UIW', - 'algorithm' => 'sha1', - 'digits' => 6, - 'period' => 30, - 'icon' => 'google.png', + 'otp_type' => 'totp', + 'service' => 'Google', + 'account' => 'john.doe@gmail.com', + 'secret' => 'A5GRFTVVRBGY7UIW', + 'algorithm' => 'sha1', + 'digits' => 6, + 'period' => 30, + 'icon' => 'google.png', 'legacy_uri' => 'otpauth://totp/Google:john.doe@gmail.com?secret=A5GRFTVVRBGY7UIW', ]); - } - /** * @test */ @@ -148,7 +145,6 @@ class ResetTestingTest extends FeatureTestCase ->assertSuccessful(); } - /** * @test */ @@ -159,5 +155,4 @@ class ResetTestingTest extends FeatureTestCase $this->artisan('2fauth:reset-testing --no-confirm') ->assertSuccessful(); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/ForgotPasswordControllerTest.php b/tests/Feature/Http/Auth/ForgotPasswordControllerTest.php index 6f0e021c..bd939432 100644 --- a/tests/Feature/Http/Auth/ForgotPasswordControllerTest.php +++ b/tests/Feature/Http/Auth/ForgotPasswordControllerTest.php @@ -3,9 +3,9 @@ namespace Tests\Feature\Http\Auth; use App\Models\User; -use Illuminate\Support\Facades\Hash; -use Illuminate\Support\Facades\Config; use Illuminate\Auth\Notifications\ResetPassword; +use Illuminate\Support\Facades\Config; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Tests\FeatureTestCase; @@ -22,7 +22,7 @@ class ForgotPasswordControllerTest extends FeatureTestCase public function test_submit_email_password_request_without_email_returns_validation_error() { $response = $this->json('POST', '/user/password/lost', [ - 'email' => '' + 'email' => '', ]); $response->assertStatus(422) @@ -35,7 +35,7 @@ class ForgotPasswordControllerTest extends FeatureTestCase public function test_submit_email_password_request_with_invalid_email_returns_validation_error() { $response = $this->json('POST', '/user/password/lost', [ - 'email' => 'nametest.com' + 'email' => 'nametest.com', ]); $response->assertStatus(422) @@ -48,7 +48,7 @@ class ForgotPasswordControllerTest extends FeatureTestCase public function test_submit_email_password_request_with_unknown_email_returns_validation_error() { $response = $this->json('POST', '/user/password/lost', [ - 'email' => 'name@test.com' + 'email' => 'name@test.com', ]); $response->assertStatus(422) @@ -65,7 +65,7 @@ class ForgotPasswordControllerTest extends FeatureTestCase $this->user = User::factory()->create(); $response = $this->json('POST', '/user/password/lost', [ - 'email' => $this->user->email + 'email' => $this->user->email, ]); $response->assertStatus(200); @@ -86,10 +86,9 @@ class ForgotPasswordControllerTest extends FeatureTestCase Config::set('2fauth.config.isDemoApp', true); $response = $this->json('POST', '/user/password/lost', [ - 'email' => '' + 'email' => '', ]); $response->assertStatus(401); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/LoginTest.php b/tests/Feature/Http/Auth/LoginTest.php index be69d66a..2ad9fc9c 100644 --- a/tests/Feature/Http/Auth/LoginTest.php +++ b/tests/Feature/Http/Auth/LoginTest.php @@ -2,8 +2,8 @@ namespace Tests\Feature\Http\Auth; -use App\Models\User; use App\Facades\Settings; +use App\Models\User; use Tests\FeatureTestCase; class LoginTest extends FeatureTestCase @@ -14,139 +14,134 @@ class LoginTest extends FeatureTestCase protected $user; private const PASSWORD = 'password'; + private const WRONG_PASSWORD = 'wrong_password'; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ public function test_user_login_returns_success() { $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::PASSWORD + 'email' => $this->user->email, + 'password' => self::PASSWORD, ]) ->assertOk() ->assertExactJson([ 'message' => 'authenticated', - 'name' => $this->user->name, + 'name' => $this->user->name, ]); } - /** * @test */ public function test_user_login_already_authenticated_returns_bad_request() { $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::PASSWORD + 'email' => $this->user->email, + 'password' => self::PASSWORD, ]); $response = $this->actingAs($this->user, 'web-guard') ->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::PASSWORD + 'email' => $this->user->email, + 'password' => self::PASSWORD, ]) ->assertStatus(200) ->assertJson([ 'message' => 'authenticated', - 'name' => $this->user->name, + 'name' => $this->user->name, ]); } - /** * @test */ public function test_user_login_with_missing_data_returns_validation_error() { $response = $this->json('POST', '/user/login', [ - 'email' => '', - 'password' => '' + 'email' => '', + 'password' => '', ]) ->assertStatus(422) ->assertJsonValidationErrors([ 'email', - 'password' + 'password', ]); } - /** * @test */ public function test_user_login_with_invalid_credentials_returns_validation_error() { $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::WRONG_PASSWORD + 'email' => $this->user->email, + 'password' => self::WRONG_PASSWORD, ]) ->assertStatus(401) ->assertJson([ - 'message' => 'unauthorised' + 'message' => 'unauthorised', ]); } - /** * @test */ public function test_too_many_login_attempts_with_invalid_credentials_returns_too_many_request_error() { $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::WRONG_PASSWORD + 'email' => $this->user->email, + 'password' => self::WRONG_PASSWORD, ]); $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::WRONG_PASSWORD + 'email' => $this->user->email, + 'password' => self::WRONG_PASSWORD, ]); $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::WRONG_PASSWORD + 'email' => $this->user->email, + 'password' => self::WRONG_PASSWORD, ]); $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::WRONG_PASSWORD + 'email' => $this->user->email, + 'password' => self::WRONG_PASSWORD, ]); $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::WRONG_PASSWORD + 'email' => $this->user->email, + 'password' => self::WRONG_PASSWORD, ]); $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::WRONG_PASSWORD + 'email' => $this->user->email, + 'password' => self::WRONG_PASSWORD, ]); $response->assertStatus(429); } - /** * @test */ public function test_user_logout_returns_validation_success() { $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::PASSWORD + 'email' => $this->user->email, + 'password' => self::PASSWORD, ]); $response = $this->actingAs($this->user, 'web-guard') @@ -157,7 +152,6 @@ class LoginTest extends FeatureTestCase ]); } - /** * @test */ @@ -167,8 +161,8 @@ class LoginTest extends FeatureTestCase Settings::set('kickUserAfter', 1); $response = $this->json('POST', '/user/login', [ - 'email' => $this->user->email, - 'password' => self::PASSWORD + 'email' => $this->user->email, + 'password' => self::PASSWORD, ]); // Ping a protected endpoint to log last_seen_at time @@ -181,5 +175,4 @@ class LoginTest extends FeatureTestCase ->json('GET', '/api/v1/twofaccounts') ->assertStatus(418); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/PasswordControllerTest.php b/tests/Feature/Http/Auth/PasswordControllerTest.php index 79039b6b..76a30b34 100644 --- a/tests/Feature/Http/Auth/PasswordControllerTest.php +++ b/tests/Feature/Http/Auth/PasswordControllerTest.php @@ -9,23 +9,23 @@ class PasswordControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; - private const PASSWORD = 'password'; - private const NEW_PASSWORD = 'newPassword'; + private const PASSWORD = 'password'; + + private const NEW_PASSWORD = 'newPassword'; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ @@ -33,8 +33,8 @@ class PasswordControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'web-guard') ->json('PATCH', '/user/password', [ - 'currentPassword' => self::PASSWORD, - 'password' => self::NEW_PASSWORD, + 'currentPassword' => self::PASSWORD, + 'password' => self::NEW_PASSWORD, 'password_confirmation' => self::NEW_PASSWORD, ]) ->assertOk() @@ -43,7 +43,6 @@ class PasswordControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -51,8 +50,8 @@ class PasswordControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'web-guard') ->json('PATCH', '/user/password', [ - 'currentPassword' => self::NEW_PASSWORD, - 'password' => self::NEW_PASSWORD, + 'currentPassword' => self::NEW_PASSWORD, + 'password' => self::NEW_PASSWORD, 'password_confirmation' => self::NEW_PASSWORD, ]) ->assertStatus(400) @@ -61,7 +60,6 @@ class PasswordControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -69,11 +67,10 @@ class PasswordControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'web-guard') ->json('PATCH', '/user/password', [ - 'currentPassword' => self::PASSWORD, - 'password' => null, + 'currentPassword' => self::PASSWORD, + 'password' => null, 'password_confirmation' => self::NEW_PASSWORD, ]) ->assertStatus(422); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/RegisterControllerTest.php b/tests/Feature/Http/Auth/RegisterControllerTest.php index a8ed3e49..aaf06623 100644 --- a/tests/Feature/Http/Auth/RegisterControllerTest.php +++ b/tests/Feature/Http/Auth/RegisterControllerTest.php @@ -2,25 +2,25 @@ namespace Tests\Feature\Http\Auth; -use \App\Models\User; -use Tests\FeatureTestCase; +use App\Models\User; use Illuminate\Support\Facades\DB; +use Tests\FeatureTestCase; class RegisterControllerTest extends FeatureTestCase { private const USERNAME = 'john doe'; - private const EMAIL = 'johndoe@example.org'; - private const PASSWORD = 'password'; + private const EMAIL = 'johndoe@example.org'; + + private const PASSWORD = 'password'; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); } - /** * @test @@ -30,10 +30,10 @@ class RegisterControllerTest extends FeatureTestCase DB::table('users')->delete(); $response = $this->json('POST', '/user', [ - 'name' => self::USERNAME, - 'email' => self::EMAIL, - 'password' => self::PASSWORD, - 'password_confirmation' => self::PASSWORD, + 'name' => self::USERNAME, + 'email' => self::EMAIL, + 'password' => self::PASSWORD, + 'password_confirmation' => self::PASSWORD, ]) ->assertCreated() ->assertJsonStructure([ @@ -44,7 +44,6 @@ class RegisterControllerTest extends FeatureTestCase 'name' => self::USERNAME, ]); } - /** * @test @@ -55,27 +54,25 @@ class RegisterControllerTest extends FeatureTestCase $user = User::factory()->create(); $response = $this->json('POST', '/user', [ - 'name' => self::USERNAME, - 'email' => self::EMAIL, - 'password' => self::PASSWORD, - 'password_confirmation' => self::PASSWORD, + 'name' => self::USERNAME, + 'email' => self::EMAIL, + 'password' => self::PASSWORD, + 'password_confirmation' => self::PASSWORD, ]) ->assertJsonValidationErrorFor('name'); } - /** * @test */ public function test_register_with_invalid_data_returns_validation_error() { $response = $this->json('POST', '/user', [ - 'name' => null, - 'email' => self::EMAIL, - 'password' => self::PASSWORD, - 'password_confirmation' => self::PASSWORD, - ]) + 'name' => null, + 'email' => self::EMAIL, + 'password' => self::PASSWORD, + 'password_confirmation' => self::PASSWORD, + ]) ->assertStatus(422); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/ResetPasswordControllerTest.php b/tests/Feature/Http/Auth/ResetPasswordControllerTest.php index 671e967b..583bdcb9 100644 --- a/tests/Feature/Http/Auth/ResetPasswordControllerTest.php +++ b/tests/Feature/Http/Auth/ResetPasswordControllerTest.php @@ -4,8 +4,8 @@ namespace Tests\Feature\Http\Auth; use App\Models\User; use Illuminate\Support\Facades\Hash; -use Illuminate\Support\Facades\Password; use Illuminate\Support\Facades\Notification; +use Illuminate\Support\Facades\Password; use Tests\FeatureTestCase; class ResetPasswordControllerTest extends FeatureTestCase @@ -15,17 +15,16 @@ class ResetPasswordControllerTest extends FeatureTestCase */ protected $user; - /** * @test */ public function test_submit_reset_password_without_input_returns_validation_error() { $response = $this->json('POST', '/user/password/reset', [ - 'email' => '', - 'password' => '', + 'email' => '', + 'password' => '', 'password_confirmation' => '', - 'token' => '' + 'token' => '', ]); $response->assertStatus(422) @@ -38,10 +37,10 @@ class ResetPasswordControllerTest extends FeatureTestCase public function test_submit_reset_password_with_invalid_data_returns_validation_error() { $response = $this->json('POST', '/user/password/reset', [ - 'email' => 'qsdqsdqsd', - 'password' => 'foofoofoo', + 'email' => 'qsdqsdqsd', + 'password' => 'foofoofoo', 'password_confirmation' => 'barbarbar', - 'token' => 'token' + 'token' => 'token', ]); $response->assertStatus(422) @@ -54,10 +53,10 @@ class ResetPasswordControllerTest extends FeatureTestCase public function test_submit_reset_password_with_too_short_pwd_returns_validation_error() { $response = $this->json('POST', '/user/password/reset', [ - 'email' => 'foo@bar.com', - 'password' => 'foo', + 'email' => 'foo@bar.com', + 'password' => 'foo', 'password_confirmation' => 'foo', - 'token' => 'token' + 'token' => 'token', ]); $response->assertStatus(422) @@ -72,20 +71,18 @@ class ResetPasswordControllerTest extends FeatureTestCase Notification::fake(); $this->user = User::factory()->create(); - $token = Password::broker()->createToken($this->user); + $token = Password::broker()->createToken($this->user); $response = $this->json('POST', '/user/password/reset', [ - 'email' => $this->user->email, - 'password' => 'newpassword', + 'email' => $this->user->email, + 'password' => 'newpassword', 'password_confirmation' => 'newpassword', - 'token' => $token + 'token' => $token, ]); $this->user->refresh(); $response->assertOk(); $this->assertTrue(Hash::check('newpassword', $this->user->password)); - } - } diff --git a/tests/Feature/Http/Auth/UserControllerTest.php b/tests/Feature/Http/Auth/UserControllerTest.php index db81bf6b..153d62f5 100644 --- a/tests/Feature/Http/Auth/UserControllerTest.php +++ b/tests/Feature/Http/Auth/UserControllerTest.php @@ -2,32 +2,33 @@ namespace Tests\Feature\Http\Auth; -use App\Models\User; use App\Facades\Settings; -use Tests\FeatureTestCase; +use App\Models\User; use Illuminate\Support\Facades\Config; +use Tests\FeatureTestCase; class UserControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; private const NEW_USERNAME = 'Jane DOE'; + private const NEW_EMAIL = 'janedoe@example.org'; - private const PASSWORD = 'password'; + + private const PASSWORD = 'password'; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test @@ -36,18 +37,17 @@ class UserControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'web-guard') ->json('PUT', '/user', [ - 'name' => self::NEW_USERNAME, - 'email' => self::NEW_EMAIL, + 'name' => self::NEW_USERNAME, + 'email' => self::NEW_EMAIL, 'password' => self::PASSWORD, ]) ->assertOk() ->assertExactJson([ - 'name' => self::NEW_USERNAME, + 'name' => self::NEW_USERNAME, 'id' => $this->user->id, 'email' => self::NEW_EMAIL, ]); } - /** * @test @@ -58,18 +58,17 @@ class UserControllerTest extends FeatureTestCase $response = $this->actingAs($this->user, 'web-guard') ->json('PUT', '/user', [ - 'name' => self::NEW_USERNAME, - 'email' => self::NEW_EMAIL, + 'name' => self::NEW_USERNAME, + 'email' => self::NEW_EMAIL, 'password' => self::PASSWORD, ]) ->assertOk() ->assertExactJson([ - 'name' => $this->user->name, + 'name' => $this->user->name, 'id' => $this->user->id, 'email' => $this->user->email, ]); } - /** * @test @@ -78,13 +77,12 @@ class UserControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'web-guard') ->json('PUT', '/user', [ - 'name' => self::NEW_USERNAME, - 'email' => self::NEW_EMAIL, + 'name' => self::NEW_USERNAME, + 'email' => self::NEW_EMAIL, 'password' => 'wrongPassword', ]) ->assertStatus(400); } - /** * @test @@ -93,13 +91,12 @@ class UserControllerTest extends FeatureTestCase { $response = $this->actingAs($this->user, 'web-guard') ->json('PUT', '/user', [ - 'name' => '', - 'email' => '', + 'name' => '', + 'email' => '', 'password' => self::PASSWORD, ]) ->assertStatus(422); } - /** * @test @@ -112,7 +109,6 @@ class UserControllerTest extends FeatureTestCase ]) ->assertNoContent(); } - /** * @test @@ -128,10 +124,9 @@ class UserControllerTest extends FeatureTestCase ]) ->assertUnauthorized() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test @@ -144,5 +139,4 @@ class UserControllerTest extends FeatureTestCase ]) ->assertStatus(400); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/WebAuthnDeviceLostControllerTest.php b/tests/Feature/Http/Auth/WebAuthnDeviceLostControllerTest.php index 618997b7..5e7cd78d 100644 --- a/tests/Feature/Http/Auth/WebAuthnDeviceLostControllerTest.php +++ b/tests/Feature/Http/Auth/WebAuthnDeviceLostControllerTest.php @@ -3,28 +3,26 @@ namespace Tests\Feature\Http\Auth; use App\Models\User; -use Tests\FeatureTestCase; use Illuminate\Support\Facades\Notification; +use Tests\FeatureTestCase; class WebAuthnDeviceLostControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; - /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ @@ -40,11 +38,10 @@ class WebAuthnDeviceLostControllerTest extends FeatureTestCase $response->assertStatus(200) ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ @@ -60,8 +57,7 @@ class WebAuthnDeviceLostControllerTest extends FeatureTestCase $response->assertStatus(422) ->assertJsonValidationErrors([ - 'email' + 'email', ]); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/WebAuthnLoginControllerTest.php b/tests/Feature/Http/Auth/WebAuthnLoginControllerTest.php index 8da0ca5d..81c6b3c9 100644 --- a/tests/Feature/Http/Auth/WebAuthnLoginControllerTest.php +++ b/tests/Feature/Http/Auth/WebAuthnLoginControllerTest.php @@ -3,32 +3,33 @@ namespace Tests\Feature\Http\Auth; use App\Models\User; -use Tests\FeatureTestCase; use Illuminate\Support\Facades\DB; use Laragear\WebAuthn\Http\Requests\AssertedRequest; +use Tests\FeatureTestCase; class WebAuthnLoginControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; const CREDENTIAL_ID = 's06aG41wsIYh5X1YUhB-SlH8y3F2RzdJZVse8iXRXOCd3oqQdEyCOsBawzxrYBtJRQA2azAMEN_q19TUp6iMgg'; + const PUBLIC_KEY = 'eyJpdiI6ImYyUHlJOEJML0pwTXJ2UDkveTQwZFE9PSIsInZhbHVlIjoiQWFSYi9LVEszazlBRUZsWHp0cGNRNktGeEQ3aTBsbU9zZ1g5MEgrWFJJNmgraElsNU9hV0VsRVlWc3NoUVVHUjRRdlcxTS9pVklnOWtVYWY5TFJQTTFhR1Rxb1ZzTFkxTWE4VUVvK1lyU3pYQ1M3VlBMWWxZcDVaYWFnK25iaXVyWGR6ZFRmMFVoSmdPZ3UvSnptbVZER0FYdEEyYmNYcW43RkV5aTVqSjNwZEFsUjhUYSs0YjU2Z2V2bUJXa0E0aVB1VC8xSjdJZ2llRGlHY2RwOGk3MmNPTyt6eDFDWUs1dVBOSWp1ZUFSeUlkclgwRW16RE9sUUpDSWV6Sk50TSIsIm1hYyI6IjI3ODQ5NzcxZGY1MzMwYTNiZjAwZmEwMDJkZjYzMGU4N2UzZjZlOGM0ZWE3NDkyYWMxMThhNmE5NWZiMTVjNGEiLCJ0YWciOiIifQ=='; + const USER_ID = '3b758ac868b74307a7e96e69ae187339'; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); DB::table('users')->delete(); } - /** * @test */ @@ -38,7 +39,7 @@ class WebAuthnLoginControllerTest extends FeatureTestCase $mock = $this->mock(AssertedRequest::class)->makePartial()->shouldIgnoreMissing(); $mock->shouldReceive([ - 'has' => false, + 'has' => false, 'login' => $this->user, ]); @@ -46,7 +47,6 @@ class WebAuthnLoginControllerTest extends FeatureTestCase ->assertNoContent(); } - /** * @test */ @@ -56,7 +56,7 @@ class WebAuthnLoginControllerTest extends FeatureTestCase $mock = $this->mock(AssertedRequest::class)->makePartial()->shouldIgnoreMissing(); $mock->shouldReceive([ - 'has' => false, + 'has' => false, 'login' => null, ]); @@ -64,7 +64,6 @@ class WebAuthnLoginControllerTest extends FeatureTestCase ->assertNoContent(422); } - /** * @test */ @@ -78,9 +77,9 @@ class WebAuthnLoginControllerTest extends FeatureTestCase 'type' => '', 'response' => [ 'authenticatorData' => '', - 'clientDataJSON' => '', - 'signature' => '', - 'userHandle' => null, + 'clientDataJSON' => '', + 'signature' => '', + 'userHandle' => null, ], ]; @@ -96,7 +95,6 @@ class WebAuthnLoginControllerTest extends FeatureTestCase ]); } - /** * @test */ @@ -105,18 +103,18 @@ class WebAuthnLoginControllerTest extends FeatureTestCase $this->user = User::factory()->create(); DB::table('webauthn_credentials')->insert([ - 'id' => self::CREDENTIAL_ID, + 'id' => self::CREDENTIAL_ID, 'authenticatable_type' => \App\Models\User::class, - 'authenticatable_id' => $this->user->id, - 'user_id' => self::USER_ID, - 'counter' => 0, - 'rp_id' => 'http://localhost', - 'origin' => 'http://localhost', - 'aaguid' => '00000000-0000-0000-0000-000000000000', - 'attestation_format' => 'none', - 'public_key' => self::PUBLIC_KEY, - 'updated_at' => now(), - 'created_at' => now(), + 'authenticatable_id' => $this->user->id, + 'user_id' => self::USER_ID, + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => '00000000-0000-0000-0000-000000000000', + 'attestation_format' => 'none', + 'public_key' => self::PUBLIC_KEY, + 'updated_at' => now(), + 'created_at' => now(), ]); $response = $this->json('POST', '/webauthn/login/options') @@ -128,13 +126,12 @@ class WebAuthnLoginControllerTest extends FeatureTestCase ]) ->assertJsonFragment([ 'allowCredentials' => [[ - 'id' => self::CREDENTIAL_ID, - 'type' => 'public-key' + 'id' => self::CREDENTIAL_ID, + 'type' => 'public-key', ]], ]); } - /** * @test */ @@ -146,5 +143,4 @@ class WebAuthnLoginControllerTest extends FeatureTestCase 'message', ]); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/WebAuthnManageControllerTest.php b/tests/Feature/Http/Auth/WebAuthnManageControllerTest.php index 2c8e5fb5..4fc735f2 100644 --- a/tests/Feature/Http/Auth/WebAuthnManageControllerTest.php +++ b/tests/Feature/Http/Auth/WebAuthnManageControllerTest.php @@ -3,11 +3,9 @@ namespace Tests\Feature\Http\Auth; use App\Models\User; -use Tests\FeatureTestCase; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Str; -use Webauthn\TrustPath\EmptyTrustPath; use Illuminate\Foundation\Testing\WithoutMiddleware; +use Illuminate\Support\Facades\DB; +use Tests\FeatureTestCase; class WebAuthnManageControllerTest extends FeatureTestCase { @@ -15,43 +13,41 @@ class WebAuthnManageControllerTest extends FeatureTestCase /** * @var \App\Models\User - */ + */ protected $user; - public const CREDENTIAL_ID = '-VOLFKPY-_FuMI_sJ7gMllK76L3VoRUINj6lL_Z3qDg'; - public const CREDENTIAL_ID_RAW = '+VOLFKPY+/FuMI/sJ7gMllK76L3VoRUINj6lL/Z3qDg='; + public const CREDENTIAL_ID_RAW = '+VOLFKPY+/FuMI/sJ7gMllK76L3VoRUINj6lL/Z3qDg='; /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); $this->user = User::factory()->create(); } - /** * @test */ public function test_index_returns_success_with_credentials() { DB::table('webauthn_credentials')->insert([ - 'id' => self::CREDENTIAL_ID, + 'id' => self::CREDENTIAL_ID, 'authenticatable_type' => \App\Models\User::class, - 'authenticatable_id' => $this->user->id, - 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', - 'counter' => 0, - 'rp_id' => 'http://localhost', - 'origin' => 'http://localhost', - 'aaguid' => '00000000-0000-0000-0000-000000000000', - 'attestation_format' => 'none', - 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', - 'updated_at' => now(), - 'created_at' => now(), + 'authenticatable_id' => $this->user->id, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => '00000000-0000-0000-0000-000000000000', + 'attestation_format' => 'none', + 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', + 'updated_at' => now(), + 'created_at' => now(), ]); $response = $this->actingAs($this->user, 'web-guard') @@ -61,34 +57,33 @@ class WebAuthnManageControllerTest extends FeatureTestCase '*' => [ 'id', 'alias', - ] + ], ]); } - /** * @test */ public function test_rename_returns_success_with_new_name() { DB::table('webauthn_credentials')->insert([ - 'id' => self::CREDENTIAL_ID, + 'id' => self::CREDENTIAL_ID, 'authenticatable_type' => \App\Models\User::class, - 'authenticatable_id' => $this->user->id, - 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', - 'alias' => 'MyNewCredential', - 'counter' => 0, - 'rp_id' => 'http://localhost', - 'origin' => 'http://localhost', - 'aaguid' => '00000000-0000-0000-0000-000000000000', - 'attestation_format' => 'none', - 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', - 'updated_at' => now(), - 'created_at' => now(), + 'authenticatable_id' => $this->user->id, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'alias' => 'MyNewCredential', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => '00000000-0000-0000-0000-000000000000', + 'attestation_format' => 'none', + 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', + 'updated_at' => now(), + 'created_at' => now(), ]); $response = $this->actingAs($this->user, 'web-guard') - ->json('PATCH', '/webauthn/credentials/'.self::CREDENTIAL_ID.'/name',[ + ->json('PATCH', '/webauthn/credentials/' . self::CREDENTIAL_ID . '/name', [ 'name' => 'MyNewCredential', ]) ->assertStatus(200) @@ -97,20 +92,18 @@ class WebAuthnManageControllerTest extends FeatureTestCase ]); } - /** * @test */ public function test_rename_invalid_data_returns_validation_error() { $response = $this->actingAs($this->user, 'web-guard') - ->json('PATCH', '/webauthn/credentials/'.self::CREDENTIAL_ID.'/name', [ + ->json('PATCH', '/webauthn/credentials/' . self::CREDENTIAL_ID . '/name', [ 'name' => null, ]) ->assertStatus(422); } - /** * @test */ @@ -122,11 +115,10 @@ class WebAuthnManageControllerTest extends FeatureTestCase ]) ->assertNotFound() ->assertJsonStructure([ - 'message' + 'message', ]); } - /** * @test */ @@ -137,7 +129,6 @@ class WebAuthnManageControllerTest extends FeatureTestCase ->assertStatus(400); } - /** * @test */ @@ -148,7 +139,6 @@ class WebAuthnManageControllerTest extends FeatureTestCase ->assertStatus(400); } - /** * @test */ @@ -159,7 +149,6 @@ class WebAuthnManageControllerTest extends FeatureTestCase ->assertStatus(400); } - /** * @test */ @@ -169,5 +158,4 @@ class WebAuthnManageControllerTest extends FeatureTestCase ->json('DELETE', '/webauthn/credentials/sdCKktnsdK') ->assertNoContent(); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Auth/WebAuthnRecoveryControllerTest.php b/tests/Feature/Http/Auth/WebAuthnRecoveryControllerTest.php index 5f32a803..e8ab62b6 100644 --- a/tests/Feature/Http/Auth/WebAuthnRecoveryControllerTest.php +++ b/tests/Feature/Http/Auth/WebAuthnRecoveryControllerTest.php @@ -3,32 +3,33 @@ namespace Tests\Feature\Http\Auth; use App\Models\User; -use Tests\FeatureTestCase; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Date; use Database\Factories\UserFactory; +use Illuminate\Support\Facades\Date; +use Illuminate\Support\Facades\DB; +use Tests\FeatureTestCase; class WebAuthnRecoveryControllerTest extends FeatureTestCase { /** * @var \App\Models\User - */ + */ protected $user; /** * @var - */ + */ protected $now; const STORED_TOKEN_VALUE = '$2y$10$P6q8rl8te5QaO1EdpyJcNO0s9VFlVgf62KaItQhrPTskxfyu97mlW'; + const ACTUAL_TOKEN_VALUE = '9e583e3fb6c32034164ac62415c9657dcbd1fb861b434340b08a94c2075cac66'; + const CREDENTIAL_ID = '-VOLFKPY-_FuMI_sJ7gMllK76L3VoRUINj6lL_Z3qDg'; - /** * @test */ - public function setUp(): void + public function setUp() : void { parent::setUp(); @@ -43,15 +44,14 @@ class WebAuthnRecoveryControllerTest extends FeatureTestCase ]); } - /** * @test */ public function test_recover_with_invalid_token_returns_validation_error() { $response = $this->json('POST', '/webauthn/recover', [ - 'token' => 'bad_token', - 'email' => $this->user->email, + 'token' => 'bad_token', + 'email' => $this->user->email, 'password' => UserFactory::USER_PASSWORD, ]) ->assertStatus(422) @@ -59,29 +59,27 @@ class WebAuthnRecoveryControllerTest extends FeatureTestCase ->assertJsonValidationErrors('token'); } - /** * @test */ public function test_recover_with_invalid_password_returns_authentication_error() { $response = $this->json('POST', '/webauthn/recover', [ - 'token' => self::ACTUAL_TOKEN_VALUE, - 'email' => $this->user->email, + 'token' => self::ACTUAL_TOKEN_VALUE, + 'email' => $this->user->email, 'password' => 'bad_password', ]) ->assertStatus(401); } - /** * @test */ public function test_recover_returns_success() { $response = $this->json('POST', '/webauthn/recover', [ - 'token' => self::ACTUAL_TOKEN_VALUE, - 'email' => $this->user->email, + 'token' => self::ACTUAL_TOKEN_VALUE, + 'email' => $this->user->email, 'password' => UserFactory::USER_PASSWORD, ]) ->assertStatus(200); @@ -95,32 +93,31 @@ class WebAuthnRecoveryControllerTest extends FeatureTestCase ]); } - /** * @test */ public function test_revoke_all_credentials_clear_registered_credentials() { DB::table('webauthn_credentials')->insert([ - 'id' => self::CREDENTIAL_ID, + 'id' => self::CREDENTIAL_ID, 'authenticatable_type' => \App\Models\User::class, - 'authenticatable_id' => $this->user->id, - 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', - 'counter' => 0, - 'rp_id' => 'http://localhost', - 'origin' => 'http://localhost', - 'aaguid' => '00000000-0000-0000-0000-000000000000', - 'attestation_format' => 'none', - 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', - 'updated_at' => now(), - 'created_at' => now(), + 'authenticatable_id' => $this->user->id, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => '00000000-0000-0000-0000-000000000000', + 'attestation_format' => 'none', + 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', + 'updated_at' => now(), + 'created_at' => now(), ]); $response = $this->json('POST', '/webauthn/recover', [ - 'token' => self::ACTUAL_TOKEN_VALUE, - 'email' => $this->user->email, - 'password' => UserFactory::USER_PASSWORD, - 'revokeAll' => true + 'token' => self::ACTUAL_TOKEN_VALUE, + 'email' => $this->user->email, + 'password' => UserFactory::USER_PASSWORD, + 'revokeAll' => true, ]) ->assertStatus(200); @@ -128,4 +125,4 @@ class WebAuthnRecoveryControllerTest extends FeatureTestCase 'authenticatable_id' => $this->user->id, ]); } -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Middlewares/AuthenticateMiddlewareTest.php b/tests/Feature/Http/Middlewares/AuthenticateMiddlewareTest.php index 193114e3..def57ec3 100644 --- a/tests/Feature/Http/Middlewares/AuthenticateMiddlewareTest.php +++ b/tests/Feature/Http/Middlewares/AuthenticateMiddlewareTest.php @@ -2,15 +2,13 @@ namespace Tests\Feature\Http\Middlewares; -use App\Models\User; -use Tests\FeatureTestCase; use Illuminate\Support\Facades\Config; - +use Tests\FeatureTestCase; class AuthenticateMiddlewareTest extends FeatureTestCase { - private const USER_NAME = 'John'; + private const USER_EMAIL = 'john@example.com'; /** @@ -19,14 +17,13 @@ class AuthenticateMiddlewareTest extends FeatureTestCase public function test_it_always_authenticates_with_reverse_proxy_guard() { Config::set('auth.auth_proxy_headers.user', 'HTTP_REMOTE_USER'); - + $this->app['auth']->shouldUse('reverse-proxy-guard'); $this->json('GET', '/api/v1/groups', [], ['HTTP_REMOTE_USER' => self::USER_NAME]); $this->assertAuthenticated('reverse-proxy-guard'); } - /** * @test */ @@ -38,8 +35,8 @@ class AuthenticateMiddlewareTest extends FeatureTestCase $this->app['auth']->shouldUse('reverse-proxy-guard'); $this->json('GET', '/api/v1/groups', [], [ - 'HTTP_REMOTE_USER' => self::USER_NAME, - 'HTTP_REMOTE_EMAIL' => self::USER_EMAIL + 'HTTP_REMOTE_USER' => self::USER_NAME, + 'HTTP_REMOTE_EMAIL' => self::USER_EMAIL, ]); $this->assertAuthenticated('reverse-proxy-guard'); @@ -48,7 +45,6 @@ class AuthenticateMiddlewareTest extends FeatureTestCase $this->assertEquals(self::USER_EMAIL, $user->email); } - /** * @test */ @@ -59,7 +55,7 @@ class AuthenticateMiddlewareTest extends FeatureTestCase $this->app['auth']->shouldUse('reverse-proxy-guard'); $this->json('GET', '/api/v1/groups', [], [ - 'HTTP_REMOTE_USER' => self::USER_NAME + 'HTTP_REMOTE_USER' => self::USER_NAME, ]); $this->assertAuthenticated('reverse-proxy-guard'); @@ -67,7 +63,6 @@ class AuthenticateMiddlewareTest extends FeatureTestCase $this->assertEquals('fake.email@do.not.use', $user->email); } - /** * @test */ @@ -79,12 +74,11 @@ class AuthenticateMiddlewareTest extends FeatureTestCase $this->app['auth']->shouldUse('reverse-proxy-guard'); $this->json('GET', '/api/v1/groups', [], [ - 'HTTP_REMOTE_USER' => '', - 'HTTP_REMOTE_EMAIL' => '' + 'HTTP_REMOTE_USER' => '', + 'HTTP_REMOTE_EMAIL' => '', ])->assertStatus(407); } - /** * @test */ @@ -95,5 +89,4 @@ class AuthenticateMiddlewareTest extends FeatureTestCase $this->json('GET', '/api/v1/groups', [], []) ->assertStatus(407); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Requests/LoginRequestTest.php b/tests/Feature/Http/Requests/LoginRequestTest.php index 3e07dd74..4738dbf1 100644 --- a/tests/Feature/Http/Requests/LoginRequestTest.php +++ b/tests/Feature/Http/Requests/LoginRequestTest.php @@ -2,20 +2,17 @@ namespace Tests\Feature\Http\Requests; -use App\Models\User; use App\Http\Requests\LoginRequest; +use App\Models\User; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; use Tests\FeatureTestCase; - /** * @covers \App\Http\Requests\LoginRequest */ class LoginRequestTest extends FeatureTestCase { - use WithoutMiddleware; /** @@ -24,27 +21,25 @@ class LoginRequestTest extends FeatureTestCase public function test_user_is_authorized() { $request = new LoginRequest(); - + $this->assertTrue($request->authorize()); } - /** * @dataProvider provideValidData */ public function test_valid_data(array $data) : void { User::factory()->create([ - 'email' => 'JOHN.DOE@example.com' + 'email' => 'JOHN.DOE@example.com', ]); - $request = new LoginRequest(); + $request = new LoginRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); } - /** * Provide Valid data for validation test */ @@ -52,33 +47,31 @@ class LoginRequestTest extends FeatureTestCase { return [ [[ - 'email' => 'john.doe@example.com', - 'password' => 'MyPassword' + 'email' => 'john.doe@example.com', + 'password' => 'MyPassword', ]], [[ - 'email' => 'JOHN.doe@example.com', - 'password' => 'MyPassword' + 'email' => 'JOHN.doe@example.com', + 'password' => 'MyPassword', ]], ]; } - /** * @dataProvider provideInvalidData */ public function test_invalid_data(array $data) : void - { + { User::factory()->create([ - 'email' => 'JOHN.DOE@example.com' + 'email' => 'JOHN.DOE@example.com', ]); - $request = new LoginRequest(); + $request = new LoginRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); } - /** * Provide invalid data for validation test */ @@ -86,25 +79,25 @@ class LoginRequestTest extends FeatureTestCase { return [ [[ - 'email' => '', // required - 'password' => 'MyPassword', + 'email' => '', // required + 'password' => 'MyPassword', ]], [[ - 'email' => 'john', // email - 'password' => 'MyPassword', + 'email' => 'john', // email + 'password' => 'MyPassword', ]], [[ - 'email' => 'john@example.com', // exists - 'password' => 'MyPassword', + 'email' => 'john@example.com', // exists + 'password' => 'MyPassword', ]], [[ - 'email' => 'john.doe@example.com', - 'password' => '', // required + 'email' => 'john.doe@example.com', + 'password' => '', // required ]], [[ - 'email' => 'john.doe@example.com', - 'password' => true, // string + 'email' => 'john.doe@example.com', + 'password' => true, // string ]], ]; } -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Requests/UserDeleteRequestTest.php b/tests/Feature/Http/Requests/UserDeleteRequestTest.php index c83ae904..e0ac501a 100644 --- a/tests/Feature/Http/Requests/UserDeleteRequestTest.php +++ b/tests/Feature/Http/Requests/UserDeleteRequestTest.php @@ -13,7 +13,6 @@ use Tests\FeatureTestCase; */ class UserDeleteRequestTest extends FeatureTestCase { - use WithoutMiddleware; /** @@ -26,7 +25,7 @@ class UserDeleteRequestTest extends FeatureTestCase ->andReturn(true); $request = new UserDeleteRequest(); - + $this->assertTrue($request->authorize()); } @@ -35,7 +34,7 @@ class UserDeleteRequestTest extends FeatureTestCase */ public function test_valid_data(array $data) : void { - $request = new UserDeleteRequest(); + $request = new UserDeleteRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -48,7 +47,7 @@ class UserDeleteRequestTest extends FeatureTestCase { return [ [[ - 'password' => 'Yubikey', + 'password' => 'Yubikey', ]], ]; } @@ -57,8 +56,8 @@ class UserDeleteRequestTest extends FeatureTestCase * @dataProvider provideInvalidData */ public function test_invalid_data(array $data) : void - { - $request = new UserDeleteRequest(); + { + $request = new UserDeleteRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -71,15 +70,14 @@ class UserDeleteRequestTest extends FeatureTestCase { return [ [[ - 'password' => '', // required + 'password' => '', // required ]], [[ - 'password' => true, // string + 'password' => true, // string ]], [[ - 'password' => 0, // string + 'password' => 0, // string ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Requests/UserPatchPwdRequestTest.php b/tests/Feature/Http/Requests/UserPatchPwdRequestTest.php index e849c291..87b079ca 100644 --- a/tests/Feature/Http/Requests/UserPatchPwdRequestTest.php +++ b/tests/Feature/Http/Requests/UserPatchPwdRequestTest.php @@ -4,8 +4,8 @@ namespace Tests\Feature\Http\Requests; use App\Http\Requests\UserPatchPwdRequest; use Illuminate\Foundation\Testing\WithoutMiddleware; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Validator; use Tests\TestCase; /** @@ -13,20 +13,19 @@ use Tests\TestCase; */ class UserPatchPwdRequestTest extends TestCase { - use WithoutMiddleware; /** * @test */ public function test_user_is_authorized() - { + { Auth::shouldReceive('check') ->once() ->andReturn(true); $request = new UserPatchPwdRequest(); - + $this->assertTrue($request->authorize()); } @@ -35,7 +34,7 @@ class UserPatchPwdRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new UserPatchPwdRequest(); + $request = new UserPatchPwdRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -48,8 +47,8 @@ class UserPatchPwdRequestTest extends TestCase { return [ [[ - 'currentPassword' => 'newPassword', - 'password' => 'newPassword', + 'currentPassword' => 'newPassword', + 'password' => 'newPassword', 'password_confirmation' => 'newPassword', ]], ]; @@ -60,7 +59,7 @@ class UserPatchPwdRequestTest extends TestCase */ public function test_invalid_data(array $data) : void { - $request = new UserPatchPwdRequest(); + $request = new UserPatchPwdRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -73,36 +72,35 @@ class UserPatchPwdRequestTest extends TestCase { return [ [[ - 'currentPassword' => '', // required - 'password' => 'newPassword', + 'currentPassword' => '', // required + 'password' => 'newPassword', 'password_confirmation' => 'newPassword', ]], [[ - 'currentPassword' => 'currentPassword', - 'password' => '', // required + 'currentPassword' => 'currentPassword', + 'password' => '', // required 'password_confirmation' => 'newPassword', ]], [[ - 'currentPassword' => 'newPassword', - 'password' => 'anotherPassword', // confirmed + 'currentPassword' => 'newPassword', + 'password' => 'anotherPassword', // confirmed 'password_confirmation' => 'newPassword', ]], [[ - 'currentPassword' => 'pwd', - 'password' => 'pwd', // min:8 + 'currentPassword' => 'pwd', + 'password' => 'pwd', // min:8 'password_confirmation' => 'newPassword', ]], [[ - 'currentPassword' => 'pwd', - 'password' => true, // string + 'currentPassword' => 'pwd', + 'password' => true, // string 'password_confirmation' => 'newPassword', ]], [[ - 'currentPassword' => 'pwd', - 'password' => 10, // string + 'currentPassword' => 'pwd', + 'password' => 10, // string 'password_confirmation' => 'newPassword', ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Requests/UserStoreRequestTest.php b/tests/Feature/Http/Requests/UserStoreRequestTest.php index c66edbff..0866db23 100644 --- a/tests/Feature/Http/Requests/UserStoreRequestTest.php +++ b/tests/Feature/Http/Requests/UserStoreRequestTest.php @@ -12,7 +12,6 @@ use Tests\FeatureTestCase; */ class UserStoreRequestTest extends FeatureTestCase { - use WithoutMiddleware; /** @@ -21,7 +20,7 @@ class UserStoreRequestTest extends FeatureTestCase public function test_user_is_authorized() { $request = new UserStoreRequest(); - + $this->assertTrue($request->authorize()); } @@ -30,7 +29,7 @@ class UserStoreRequestTest extends FeatureTestCase */ public function test_valid_data(array $data) : void { - $request = new UserStoreRequest(); + $request = new UserStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -43,10 +42,10 @@ class UserStoreRequestTest extends FeatureTestCase { return [ [[ - 'name' => 'John', - 'email' => 'john@example.com', - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => 'John', + 'email' => 'john@example.com', + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ]], ]; } @@ -58,15 +57,15 @@ class UserStoreRequestTest extends FeatureTestCase { $user = new \App\Models\User( [ - 'name' => 'John', - 'email' => 'john@example.com', - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => 'John', + 'email' => 'john@example.com', + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ] ); $user->save(); - - $request = new UserStoreRequest(); + + $request = new UserStoreRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -79,60 +78,59 @@ class UserStoreRequestTest extends FeatureTestCase { return [ [[ - 'name' => 'John', // unique - 'email' => 'john@example.com', - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => 'John', // unique + 'email' => 'john@example.com', + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ]], [[ - 'name' => '', // required - 'email' => 'john@example.com', - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => '', // required + 'email' => 'john@example.com', + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => '', // required - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => 'John', + 'email' => '', // required + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ]], [[ - 'name' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', // max:255 - 'email' => 'john@example.com', - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', // max:255 + 'email' => 'john@example.com', + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz@example.com', // max:255 - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => 'John', + 'email' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz@example.com', // max:255 + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => 'johnexample.com', // email - 'password' => 'MyPassword', - 'password_confirmation' => 'MyPassword', + 'name' => 'John', + 'email' => 'johnexample.com', // email + 'password' => 'MyPassword', + 'password_confirmation' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => 'john@example.com', - 'password' => '', // required - 'password_confirmation' => '', // required + 'name' => 'John', + 'email' => 'john@example.com', + 'password' => '', // required + 'password_confirmation' => '', // required ]], [[ - 'name' => 'John', - 'email' => 'john@example.com', - 'password' => 'MyPassword', - 'password_confirmation' => 'anotherPassword', // confirmed + 'name' => 'John', + 'email' => 'john@example.com', + 'password' => 'MyPassword', + 'password_confirmation' => 'anotherPassword', // confirmed ]], [[ - 'name' => 'John', - 'email' => 'john@example.com', - 'password' => 'pwd', // min:8 - 'password_confirmation' => 'pwd', + 'name' => 'John', + 'email' => 'john@example.com', + 'password' => 'pwd', // min:8 + 'password_confirmation' => 'pwd', ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Requests/UserUpdateRequestTest.php b/tests/Feature/Http/Requests/UserUpdateRequestTest.php index f6878040..eaf1374f 100644 --- a/tests/Feature/Http/Requests/UserUpdateRequestTest.php +++ b/tests/Feature/Http/Requests/UserUpdateRequestTest.php @@ -13,7 +13,6 @@ use Tests\TestCase; */ class UserUpdateRequestTest extends TestCase { - use WithoutMiddleware; /** @@ -26,7 +25,7 @@ class UserUpdateRequestTest extends TestCase ->andReturn(true); $request = new UserUpdateRequest(); - + $this->assertTrue($request->authorize()); } @@ -35,7 +34,7 @@ class UserUpdateRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new UserUpdateRequest(); + $request = new UserUpdateRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -48,9 +47,9 @@ class UserUpdateRequestTest extends TestCase { return [ [[ - 'name' => 'John', - 'email' => 'john@example.com', - 'password' => 'MyPassword' + 'name' => 'John', + 'email' => 'john@example.com', + 'password' => 'MyPassword', ]], ]; } @@ -59,8 +58,8 @@ class UserUpdateRequestTest extends TestCase * @dataProvider provideInvalidData */ public function test_invalid_data(array $data) : void - { - $request = new UserUpdateRequest(); + { + $request = new UserUpdateRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -73,46 +72,45 @@ class UserUpdateRequestTest extends TestCase { return [ [[ - 'name' => '', // required - 'email' => 'john@example.com', - 'password' => 'MyPassword', + 'name' => '', // required + 'email' => 'john@example.com', + 'password' => 'MyPassword', ]], [[ - 'name' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', // max:255 - 'email' => 'john@example.com', - 'password' => 'MyPassword', + 'name' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', // max:255 + 'email' => 'john@example.com', + 'password' => 'MyPassword', ]], [[ - 'name' => true, // string - 'email' => 'john@example.com', - 'password' => 'MyPassword', + 'name' => true, // string + 'email' => 'john@example.com', + 'password' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => '', // required - 'password' => 'MyPassword', + 'name' => 'John', + 'email' => '', // required + 'password' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => 0, // string - 'password' => 'MyPassword', + 'name' => 'John', + 'email' => 0, // string + 'password' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => 'johnexample.com', // email - 'password' => 'MyPassword', + 'name' => 'John', + 'email' => 'johnexample.com', // email + 'password' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz@example.com', // max:255 - 'password' => 'MyPassword', + 'name' => 'John', + 'email' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz@example.com', // max:255 + 'password' => 'MyPassword', ]], [[ - 'name' => 'John', - 'email' => 'john@example.com', - 'password' => '', // required + 'name' => 'John', + 'email' => 'john@example.com', + 'password' => '', // required ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Feature/Http/Requests/WebauthnRenameRequestTest.php b/tests/Feature/Http/Requests/WebauthnRenameRequestTest.php index c6645d67..939db80f 100644 --- a/tests/Feature/Http/Requests/WebauthnRenameRequestTest.php +++ b/tests/Feature/Http/Requests/WebauthnRenameRequestTest.php @@ -13,7 +13,6 @@ use Tests\TestCase; */ class WebauthnRenameRequestTest extends TestCase { - use WithoutMiddleware; /** @@ -26,7 +25,7 @@ class WebauthnRenameRequestTest extends TestCase ->andReturn(true); $request = new WebauthnRenameRequest(); - + $this->assertTrue($request->authorize()); } @@ -35,7 +34,7 @@ class WebauthnRenameRequestTest extends TestCase */ public function test_valid_data(array $data) : void { - $request = new WebauthnRenameRequest(); + $request = new WebauthnRenameRequest(); $validator = Validator::make($data, $request->rules()); $this->assertFalse($validator->fails()); @@ -48,7 +47,7 @@ class WebauthnRenameRequestTest extends TestCase { return [ [[ - 'name' => 'Yubikey', + 'name' => 'Yubikey', ]], ]; } @@ -57,8 +56,8 @@ class WebauthnRenameRequestTest extends TestCase * @dataProvider provideInvalidData */ public function test_invalid_data(array $data) : void - { - $request = new WebauthnRenameRequest(); + { + $request = new WebauthnRenameRequest(); $validator = Validator::make($data, $request->rules()); $this->assertTrue($validator->fails()); @@ -71,15 +70,14 @@ class WebauthnRenameRequestTest extends TestCase { return [ [[ - 'name' => '', // required + 'name' => '', // required ]], [[ - 'name' => true, // string + 'name' => true, // string ]], [[ - 'name' => 0, // string + 'name' => 0, // string ]], ]; } - -} \ No newline at end of file +} diff --git a/tests/Feature/Models/TwoFAccountModelTest.php b/tests/Feature/Models/TwoFAccountModelTest.php index 242e5469..b111c8b8 100644 --- a/tests/Feature/Models/TwoFAccountModelTest.php +++ b/tests/Feature/Models/TwoFAccountModelTest.php @@ -3,8 +3,8 @@ namespace Tests\Feature\Models; use App\Models\TwoFAccount; -use Tests\FeatureTestCase; use Tests\Classes\OtpTestData; +use Tests\FeatureTestCase; /** * @covers \App\Models\TwoFAccount @@ -16,13 +16,11 @@ class TwoFAccountModelTest extends FeatureTestCase */ protected $customTotpTwofaccount; - /** * App\Models\TwoFAccount $customTotpTwofaccount */ protected $customHotpTwofaccount; - /** * @test */ @@ -30,49 +28,48 @@ class TwoFAccountModelTest extends FeatureTestCase { parent::setUp(); - $this->customTotpTwofaccount = new TwoFAccount; + $this->customTotpTwofaccount = new TwoFAccount; $this->customTotpTwofaccount->legacy_uri = OtpTestData::TOTP_FULL_CUSTOM_URI; - $this->customTotpTwofaccount->service = OtpTestData::SERVICE; - $this->customTotpTwofaccount->account = OtpTestData::ACCOUNT; - $this->customTotpTwofaccount->icon = OtpTestData::ICON; - $this->customTotpTwofaccount->otp_type = 'totp'; - $this->customTotpTwofaccount->secret = OtpTestData::SECRET; - $this->customTotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; - $this->customTotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; - $this->customTotpTwofaccount->period = OtpTestData::PERIOD_CUSTOM; - $this->customTotpTwofaccount->counter = null; + $this->customTotpTwofaccount->service = OtpTestData::SERVICE; + $this->customTotpTwofaccount->account = OtpTestData::ACCOUNT; + $this->customTotpTwofaccount->icon = OtpTestData::ICON; + $this->customTotpTwofaccount->otp_type = 'totp'; + $this->customTotpTwofaccount->secret = OtpTestData::SECRET; + $this->customTotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; + $this->customTotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; + $this->customTotpTwofaccount->period = OtpTestData::PERIOD_CUSTOM; + $this->customTotpTwofaccount->counter = null; $this->customTotpTwofaccount->save(); - $this->customHotpTwofaccount = new TwoFAccount; + $this->customHotpTwofaccount = new TwoFAccount; $this->customHotpTwofaccount->legacy_uri = OtpTestData::HOTP_FULL_CUSTOM_URI; - $this->customHotpTwofaccount->service = OtpTestData::SERVICE; - $this->customHotpTwofaccount->account = OtpTestData::ACCOUNT; - $this->customHotpTwofaccount->icon = OtpTestData::ICON; - $this->customHotpTwofaccount->otp_type = 'hotp'; - $this->customHotpTwofaccount->secret = OtpTestData::SECRET; - $this->customHotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; - $this->customHotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; - $this->customHotpTwofaccount->period = null; - $this->customHotpTwofaccount->counter = OtpTestData::COUNTER_CUSTOM; + $this->customHotpTwofaccount->service = OtpTestData::SERVICE; + $this->customHotpTwofaccount->account = OtpTestData::ACCOUNT; + $this->customHotpTwofaccount->icon = OtpTestData::ICON; + $this->customHotpTwofaccount->otp_type = 'hotp'; + $this->customHotpTwofaccount->secret = OtpTestData::SECRET; + $this->customHotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; + $this->customHotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; + $this->customHotpTwofaccount->period = null; + $this->customHotpTwofaccount->counter = OtpTestData::COUNTER_CUSTOM; $this->customHotpTwofaccount->save(); - $this->customSteamTotpTwofaccount = new TwoFAccount; + $this->customSteamTotpTwofaccount = new TwoFAccount; $this->customSteamTotpTwofaccount->legacy_uri = OtpTestData::STEAM_TOTP_URI; - $this->customSteamTotpTwofaccount->service = OtpTestData::STEAM; - $this->customSteamTotpTwofaccount->account = OtpTestData::ACCOUNT; - $this->customSteamTotpTwofaccount->otp_type = 'steamtotp'; - $this->customSteamTotpTwofaccount->secret = OtpTestData::STEAM_SECRET; - $this->customSteamTotpTwofaccount->digits = OtpTestData::DIGITS_STEAM; - $this->customSteamTotpTwofaccount->algorithm = OtpTestData::ALGORITHM_DEFAULT; - $this->customSteamTotpTwofaccount->period = OtpTestData::PERIOD_DEFAULT; - $this->customSteamTotpTwofaccount->counter = null; + $this->customSteamTotpTwofaccount->service = OtpTestData::STEAM; + $this->customSteamTotpTwofaccount->account = OtpTestData::ACCOUNT; + $this->customSteamTotpTwofaccount->otp_type = 'steamtotp'; + $this->customSteamTotpTwofaccount->secret = OtpTestData::STEAM_SECRET; + $this->customSteamTotpTwofaccount->digits = OtpTestData::DIGITS_STEAM; + $this->customSteamTotpTwofaccount->algorithm = OtpTestData::ALGORITHM_DEFAULT; + $this->customSteamTotpTwofaccount->period = OtpTestData::PERIOD_DEFAULT; + $this->customSteamTotpTwofaccount->counter = null; $this->customSteamTotpTwofaccount->save(); } - /** - * @test - */ + * @test + */ public function test_fill_with_custom_totp_uri_returns_correct_value() { $twofaccount = new TwoFAccount; @@ -87,10 +84,9 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(OtpTestData::PERIOD_CUSTOM, $twofaccount->period); $this->assertEquals(null, $twofaccount->counter); $this->assertEquals(OtpTestData::ALGORITHM_CUSTOM, $twofaccount->algorithm); - $this->assertStringEndsWith('.png',$twofaccount->icon); + $this->assertStringEndsWith('.png', $twofaccount->icon); } - /** * @test */ @@ -111,7 +107,6 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->icon); } - /** * @test */ @@ -129,10 +124,9 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->period); $this->assertEquals(OtpTestData::COUNTER_CUSTOM, $twofaccount->counter); $this->assertEquals(OtpTestData::ALGORITHM_CUSTOM, $twofaccount->algorithm); - $this->assertStringEndsWith('.png',$twofaccount->icon); + $this->assertStringEndsWith('.png', $twofaccount->icon); } - /** * @test */ @@ -153,7 +147,6 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->icon); } - /** * @test */ @@ -164,20 +157,19 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount->save(); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'legacy_uri' => OtpTestData::TOTP_SHORT_URI, - 'service' => null, - 'account' => OtpTestData::ACCOUNT, - 'secret' => OtpTestData::SECRET, - 'digits' => OtpTestData::DIGITS_DEFAULT, - 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null, - 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, - 'icon' => null, + 'otp_type' => 'totp', + 'legacy_uri' => OtpTestData::TOTP_SHORT_URI, + 'service' => null, + 'account' => OtpTestData::ACCOUNT, + 'secret' => OtpTestData::SECRET, + 'digits' => OtpTestData::DIGITS_DEFAULT, + 'period' => OtpTestData::PERIOD_DEFAULT, + 'counter' => null, + 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, + 'icon' => null, ]); } - /** * @test */ @@ -188,7 +180,6 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount->fillWithURI(OtpTestData::INVALID_OTPAUTH_URI); } - /** * @test */ @@ -196,10 +187,9 @@ class TwoFAccountModelTest extends FeatureTestCase { $this->expectException(\Illuminate\Validation\ValidationException::class); $twofaccount = new TwoFAccount; - $twofaccount->fillWithURI('otpauth://totp/?secret='.OtpTestData::SECRET); + $twofaccount->fillWithURI('otpauth://totp/?secret=' . OtpTestData::SECRET); } - /** * @test */ @@ -216,10 +206,9 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(OtpTestData::PERIOD_CUSTOM, $twofaccount->period); $this->assertEquals(null, $twofaccount->counter); $this->assertEquals(OtpTestData::ALGORITHM_CUSTOM, $twofaccount->algorithm); - $this->assertStringEndsWith('.png',$twofaccount->icon); + $this->assertStringEndsWith('.png', $twofaccount->icon); } - /** * @test */ @@ -239,7 +228,6 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->icon); } - /** * @test */ @@ -256,10 +244,9 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->period); $this->assertEquals(OtpTestData::COUNTER_CUSTOM, $twofaccount->counter); $this->assertEquals(OtpTestData::ALGORITHM_CUSTOM, $twofaccount->algorithm); - $this->assertStringEndsWith('.png',$twofaccount->icon); + $this->assertStringEndsWith('.png', $twofaccount->icon); } - /** * @test */ @@ -279,7 +266,6 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->icon); } - /** * @test */ @@ -290,20 +276,19 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount->save(); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'legacy_uri' => OtpTestData::TOTP_SHORT_URI, - 'service' => null, - 'account' => OtpTestData::ACCOUNT, - 'secret' => OtpTestData::SECRET, - 'digits' => OtpTestData::DIGITS_DEFAULT, - 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null, - 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, - 'icon' => null, + 'otp_type' => 'totp', + 'legacy_uri' => OtpTestData::TOTP_SHORT_URI, + 'service' => null, + 'account' => OtpTestData::ACCOUNT, + 'secret' => OtpTestData::SECRET, + 'digits' => OtpTestData::DIGITS_DEFAULT, + 'period' => OtpTestData::PERIOD_DEFAULT, + 'counter' => null, + 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, + 'icon' => null, ]); } - /** * @test */ @@ -314,7 +299,6 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount->fillWithOtpParameters(OtpTestData::ARRAY_OF_PARAMETERS_FOR_UNSUPPORTED_OTP_TYPE); } - /** * @test */ @@ -323,13 +307,12 @@ class TwoFAccountModelTest extends FeatureTestCase $this->expectException(\App\Exceptions\InvalidOtpParameterException::class); $twofaccount = new TwoFAccount; $twofaccount->fillWithOtpParameters([ - 'account' => OtpTestData::ACCOUNT, - 'otp_type' => 'totp', - 'digits' => 'notsupported', + 'account' => OtpTestData::ACCOUNT, + 'otp_type' => 'totp', + 'digits' => 'notsupported', ]); } - /** * @test */ @@ -344,7 +327,6 @@ class TwoFAccountModelTest extends FeatureTestCase ]); } - /** * @test */ @@ -365,7 +347,6 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->icon); } - /** * @test */ @@ -386,7 +367,6 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals(null, $twofaccount->icon); } - /** * @test */ @@ -397,19 +377,18 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount->save(); $this->assertDatabaseHas('twofaccounts', [ - 'otp_type' => 'totp', - 'service' => null, - 'account' => OtpTestData::ACCOUNT, - 'secret' => OtpTestData::SECRET, - 'digits' => OtpTestData::DIGITS_DEFAULT, - 'period' => OtpTestData::PERIOD_DEFAULT, - 'counter' => null, - 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, - 'icon' => null, + 'otp_type' => 'totp', + 'service' => null, + 'account' => OtpTestData::ACCOUNT, + 'secret' => OtpTestData::SECRET, + 'digits' => OtpTestData::DIGITS_DEFAULT, + 'period' => OtpTestData::PERIOD_DEFAULT, + 'counter' => null, + 'algorithm' => OtpTestData::ALGORITHM_DEFAULT, + 'icon' => null, ]); } - /** * @test */ @@ -418,13 +397,13 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount = new TwoFAccount; $otp_from_model = $this->customTotpTwofaccount->getOTP(); - $otp_from_uri = $twofaccount->fillWithURI(OtpTestData::TOTP_FULL_CUSTOM_URI)->getOTP(); + $otp_from_uri = $twofaccount->fillWithURI(OtpTestData::TOTP_FULL_CUSTOM_URI)->getOTP(); if ($otp_from_model->generated_at === $otp_from_uri->generated_at) { $this->assertEquals($otp_from_model, $otp_from_uri); } - $otp_from_model = $this->customTotpTwofaccount->getOTP(); + $otp_from_model = $this->customTotpTwofaccount->getOTP(); $otp_from_parameters = $twofaccount->fillWithOtpParameters(OtpTestData::ARRAY_OF_FULL_VALID_PARAMETERS_FOR_CUSTOM_TOTP)->getOTP(); if ($otp_from_model->generated_at === $otp_from_parameters->generated_at) { @@ -432,7 +411,6 @@ class TwoFAccountModelTest extends FeatureTestCase } } - /** * @test */ @@ -441,7 +419,7 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount = new TwoFAccount; $otp_from_model = $this->customHotpTwofaccount->getOTP(); - $otp_from_uri = $twofaccount->fillWithURI(OtpTestData::HOTP_FULL_CUSTOM_URI)->getOTP(); + $otp_from_uri = $twofaccount->fillWithURI(OtpTestData::HOTP_FULL_CUSTOM_URI)->getOTP(); $this->assertEquals($otp_from_model, $otp_from_uri); @@ -450,7 +428,6 @@ class TwoFAccountModelTest extends FeatureTestCase $this->assertEquals($otp_from_model, $otp_from_parameters); } - /** * @test */ @@ -459,13 +436,13 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount = new TwoFAccount; $otp_from_model = $this->customSteamTotpTwofaccount->getOTP(); - $otp_from_uri = $twofaccount->fillWithURI(OtpTestData::STEAM_TOTP_URI)->getOTP(); + $otp_from_uri = $twofaccount->fillWithURI(OtpTestData::STEAM_TOTP_URI)->getOTP(); if ($otp_from_model->generated_at === $otp_from_uri->generated_at) { $this->assertEquals($otp_from_model, $otp_from_uri); } - $otp_from_model = $this->customSteamTotpTwofaccount->getOTP(); + $otp_from_model = $this->customSteamTotpTwofaccount->getOTP(); $otp_from_parameters = $twofaccount->fillWithOtpParameters(OtpTestData::ARRAY_OF_FULL_VALID_PARAMETERS_FOR_STEAM_TOTP)->getOTP(); if ($otp_from_model->generated_at === $otp_from_parameters->generated_at) { @@ -473,7 +450,6 @@ class TwoFAccountModelTest extends FeatureTestCase } } - /** * @test */ @@ -482,10 +458,9 @@ class TwoFAccountModelTest extends FeatureTestCase $twofaccount = new TwoFAccount; $this->expectException(\App\Exceptions\InvalidSecretException::class); - $otp_from_uri = $twofaccount->fillWithURI('otpauth://totp/'.OtpTestData::ACCOUNT.'?secret=0')->getOTP(); + $otp_from_uri = $twofaccount->fillWithURI('otpauth://totp/' . OtpTestData::ACCOUNT . '?secret=0')->getOTP(); } - /** * @test */ @@ -495,44 +470,41 @@ class TwoFAccountModelTest extends FeatureTestCase $this->expectException(\App\Exceptions\UndecipherableException::class); $otp_from_uri = $twofaccount->fillWithOtpParameters([ - 'account' => OtpTestData::ACCOUNT, - 'otp_type' => 'totp', - 'secret' => __('errors.indecipherable'), + 'account' => OtpTestData::ACCOUNT, + 'otp_type' => 'totp', + 'secret' => __('errors.indecipherable'), ])->getOTP(); } - /** * @test */ public function test_getURI_for_custom_totp_model_returns_uri() { $uri = $this->customTotpTwofaccount->getURI(); - + $this->assertStringContainsString('otpauth://totp/', $uri); $this->assertStringContainsString(OtpTestData::SERVICE, $uri); $this->assertStringContainsString(OtpTestData::ACCOUNT, $uri); - $this->assertStringContainsString('secret='.OtpTestData::SECRET, $uri); - $this->assertStringContainsString('digits='.OtpTestData::DIGITS_CUSTOM, $uri); - $this->assertStringContainsString('period='.OtpTestData::PERIOD_CUSTOM, $uri); - $this->assertStringContainsString('algorithm='.OtpTestData::ALGORITHM_CUSTOM, $uri); + $this->assertStringContainsString('secret=' . OtpTestData::SECRET, $uri); + $this->assertStringContainsString('digits=' . OtpTestData::DIGITS_CUSTOM, $uri); + $this->assertStringContainsString('period=' . OtpTestData::PERIOD_CUSTOM, $uri); + $this->assertStringContainsString('algorithm=' . OtpTestData::ALGORITHM_CUSTOM, $uri); } - /** * @test */ public function test_getURI_for_custom_hotp_model_returns_uri() { $uri = $this->customHotpTwofaccount->getURI(); - + $this->assertStringContainsString('otpauth://hotp/', $uri); $this->assertStringContainsString(OtpTestData::SERVICE, $uri); $this->assertStringContainsString(OtpTestData::ACCOUNT, $uri); - $this->assertStringContainsString('secret='.OtpTestData::SECRET, $uri); - $this->assertStringContainsString('digits='.OtpTestData::DIGITS_CUSTOM, $uri); - $this->assertStringContainsString('counter='.OtpTestData::COUNTER_CUSTOM, $uri); - $this->assertStringContainsString('algorithm='.OtpTestData::ALGORITHM_CUSTOM, $uri); + $this->assertStringContainsString('secret=' . OtpTestData::SECRET, $uri); + $this->assertStringContainsString('digits=' . OtpTestData::DIGITS_CUSTOM, $uri); + $this->assertStringContainsString('counter=' . OtpTestData::COUNTER_CUSTOM, $uri); + $this->assertStringContainsString('algorithm=' . OtpTestData::ALGORITHM_CUSTOM, $uri); } - -} \ No newline at end of file +} diff --git a/tests/Feature/RouteTest.php b/tests/Feature/RouteTest.php index 29779d45..0cb98b31 100644 --- a/tests/Feature/RouteTest.php +++ b/tests/Feature/RouteTest.php @@ -6,7 +6,6 @@ use Tests\FeatureTestCase; class RouteTest extends FeatureTestCase { - /** * test return main web view * @@ -31,5 +30,4 @@ class RouteTest extends FeatureTestCase $response->assertStatus(405); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Services/GroupServiceTest.php b/tests/Feature/Services/GroupServiceTest.php index b5502565..a264b223 100644 --- a/tests/Feature/Services/GroupServiceTest.php +++ b/tests/Feature/Services/GroupServiceTest.php @@ -2,12 +2,11 @@ namespace Tests\Feature\Services; +use App\Facades\Groups; +use App\Facades\Settings; use App\Models\Group; use App\Models\TwoFAccount; use Tests\FeatureTestCase; -use App\Facades\Groups; -use App\Facades\Settings; - /** * @covers \App\Services\GroupService @@ -17,27 +16,38 @@ class GroupServiceTest extends FeatureTestCase /** * App\Models\Group $groupOne, $groupTwo */ - protected $groupOne, $groupTwo; + protected $groupOne; + protected $groupTwo; /** * App\Models\Group $twofaccountOne, $twofaccountTwo */ - protected $twofaccountOne, $twofaccountTwo; + protected $twofaccountOne; + + protected $twofaccountTwo; private const NEW_GROUP_NAME = 'MyNewGroup'; + private const TWOFACCOUNT_COUNT = 2; + private const ACCOUNT = 'account'; + private const SERVICE = 'service'; + private const SECRET = 'A4GRFHVVRBGY7UIW'; + private const ALGORITHM_CUSTOM = 'sha256'; + private const DIGITS_CUSTOM = 7; + private const PERIOD_CUSTOM = 40; + private const IMAGE = 'https%3A%2F%2Fen.opensuse.org%2Fimages%2F4%2F44%2FButton-filled-colour.png'; + private const ICON = 'test.png'; - private const TOTP_FULL_CUSTOM_URI = 'otpauth://totp/'.self::SERVICE.':'.self::ACCOUNT.'?secret='.self::SECRET.'&issuer='.self::SERVICE.'&digits='.self::DIGITS_CUSTOM.'&period='.self::PERIOD_CUSTOM.'&algorithm='.self::ALGORITHM_CUSTOM.'&image='.self::IMAGE; - + private const TOTP_FULL_CUSTOM_URI = 'otpauth://totp/' . self::SERVICE . ':' . self::ACCOUNT . '?secret=' . self::SECRET . '&issuer=' . self::SERVICE . '&digits=' . self::DIGITS_CUSTOM . '&period=' . self::PERIOD_CUSTOM . '&algorithm=' . self::ALGORITHM_CUSTOM . '&image=' . self::IMAGE; /** * @test @@ -46,42 +56,41 @@ class GroupServiceTest extends FeatureTestCase { parent::setUp(); - $this->groupOne = new Group; + $this->groupOne = new Group; $this->groupOne->name = 'MyGroupOne'; $this->groupOne->save(); - $this->groupTwo = new Group; + $this->groupTwo = new Group; $this->groupTwo->name = 'MyGroupTwo'; $this->groupTwo->save(); - $this->twofaccountOne = new TwoFAccount; + $this->twofaccountOne = new TwoFAccount; $this->twofaccountOne->legacy_uri = self::TOTP_FULL_CUSTOM_URI; - $this->twofaccountOne->service = self::SERVICE; - $this->twofaccountOne->account = self::ACCOUNT; - $this->twofaccountOne->icon = self::ICON; - $this->twofaccountOne->otp_type = 'totp'; - $this->twofaccountOne->secret = self::SECRET; - $this->twofaccountOne->digits = self::DIGITS_CUSTOM; - $this->twofaccountOne->algorithm = self::ALGORITHM_CUSTOM; - $this->twofaccountOne->period = self::PERIOD_CUSTOM; - $this->twofaccountOne->counter = null; + $this->twofaccountOne->service = self::SERVICE; + $this->twofaccountOne->account = self::ACCOUNT; + $this->twofaccountOne->icon = self::ICON; + $this->twofaccountOne->otp_type = 'totp'; + $this->twofaccountOne->secret = self::SECRET; + $this->twofaccountOne->digits = self::DIGITS_CUSTOM; + $this->twofaccountOne->algorithm = self::ALGORITHM_CUSTOM; + $this->twofaccountOne->period = self::PERIOD_CUSTOM; + $this->twofaccountOne->counter = null; $this->twofaccountOne->save(); - $this->twofaccountTwo = new TwoFAccount; + $this->twofaccountTwo = new TwoFAccount; $this->twofaccountTwo->legacy_uri = self::TOTP_FULL_CUSTOM_URI; - $this->twofaccountTwo->service = self::SERVICE; - $this->twofaccountTwo->account = self::ACCOUNT; - $this->twofaccountTwo->icon = self::ICON; - $this->twofaccountTwo->otp_type = 'totp'; - $this->twofaccountTwo->secret = self::SECRET; - $this->twofaccountTwo->digits = self::DIGITS_CUSTOM; - $this->twofaccountTwo->algorithm = self::ALGORITHM_CUSTOM; - $this->twofaccountTwo->period = self::PERIOD_CUSTOM; - $this->twofaccountTwo->counter = null; + $this->twofaccountTwo->service = self::SERVICE; + $this->twofaccountTwo->account = self::ACCOUNT; + $this->twofaccountTwo->icon = self::ICON; + $this->twofaccountTwo->otp_type = 'totp'; + $this->twofaccountTwo->secret = self::SECRET; + $this->twofaccountTwo->digits = self::DIGITS_CUSTOM; + $this->twofaccountTwo->algorithm = self::ALGORITHM_CUSTOM; + $this->twofaccountTwo->period = self::PERIOD_CUSTOM; + $this->twofaccountTwo->counter = null; $this->twofaccountTwo->save(); } - /** * @test */ @@ -90,81 +99,74 @@ class GroupServiceTest extends FeatureTestCase $this->assertInstanceOf(\Illuminate\Database\Eloquent\Collection::class, Groups::getAll()); } - /** * @test */ public function test_getAll_adds_pseudo_group_on_top_of_user_groups() { $groups = Groups::getAll(); - + $this->assertEquals(0, $groups->first()->id); $this->assertEquals(__('commons.all'), $groups->first()->name); } - /** * @test */ public function test_getAll_returns_pseudo_group_with_all_twofaccounts_count() { $groups = Groups::getAll(); - + $this->assertEquals(self::TWOFACCOUNT_COUNT, $groups->first()->twofaccounts_count); } - /** * @test */ public function test_create_persists_and_returns_created_group() { $newGroup = Groups::create(['name' => self::NEW_GROUP_NAME]); - + $this->assertDatabaseHas('groups', ['name' => self::NEW_GROUP_NAME]); $this->assertInstanceOf(\App\Models\Group::class, $newGroup); $this->assertEquals(self::NEW_GROUP_NAME, $newGroup->name); } - /** * @test */ public function test_update_persists_and_returns_updated_group() { $this->groupOne = Groups::update($this->groupOne, ['name' => self::NEW_GROUP_NAME]); - + $this->assertDatabaseHas('groups', ['name' => self::NEW_GROUP_NAME]); $this->assertInstanceOf(\App\Models\Group::class, $this->groupOne); $this->assertEquals(self::NEW_GROUP_NAME, $this->groupOne->name); } - /** * @test */ public function test_delete_a_groupId_clear_db_and_returns_deleted_count() { $deleted = Groups::delete($this->groupOne->id); - + $this->assertDatabaseMissing('groups', ['id' => $this->groupOne->id]); $this->assertEquals(1, $deleted); } - /** * @test */ public function test_delete_an_array_of_ids_clear_db_and_returns_deleted_count() { $deleted = Groups::delete([$this->groupOne->id, $this->groupTwo->id]); - + $this->assertDatabaseMissing('groups', ['id' => $this->groupOne->id]); $this->assertDatabaseMissing('groups', ['id' => $this->groupTwo->id]); $this->assertEquals(2, $deleted); } - /** * @test */ @@ -173,14 +175,13 @@ class GroupServiceTest extends FeatureTestCase Settings::set('defaultGroup', $this->groupOne->id); $deleted = Groups::delete($this->groupOne->id); - + $this->assertDatabaseHas('options', [ - 'key' => 'defaultGroup', - 'value' => 0 + 'key' => 'defaultGroup', + 'value' => 0, ]); } - /** * @test */ @@ -188,65 +189,60 @@ class GroupServiceTest extends FeatureTestCase { Settings::set('rememberActiveGroup', true); Settings::set('activeGroup', $this->groupOne->id); - + $deleted = Groups::delete($this->groupOne->id); - + $this->assertDatabaseHas('options', [ - 'key' => 'activeGroup', - 'value' => 0 + 'key' => 'activeGroup', + 'value' => 0, ]); } - /** * @test */ public function test_assign_a_twofaccountid_to_a_specified_group_persists_the_relation() { - Groups::assign($this->twofaccountOne->id, $this->groupOne); - + $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->twofaccountOne->id, + 'id' => $this->twofaccountOne->id, 'group_id' => $this->groupOne->id, ]); } - /** * @test */ public function test_assign_multiple_twofaccountid_to_a_specified_group_persists_the_relation() { Groups::assign([$this->twofaccountOne->id, $this->twofaccountTwo->id], $this->groupOne); - + $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->twofaccountOne->id, + 'id' => $this->twofaccountOne->id, 'group_id' => $this->groupOne->id, ]); $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->twofaccountTwo->id, + 'id' => $this->twofaccountTwo->id, 'group_id' => $this->groupOne->id, ]); } - /** * @test */ public function test_assign_a_twofaccountid_to_no_group_assigns_to_default_group() { Settings::set('defaultGroup', $this->groupTwo->id); - + Groups::assign($this->twofaccountOne->id); - + $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->twofaccountOne->id, + 'id' => $this->twofaccountOne->id, 'group_id' => $this->groupTwo->id, ]); } - /** * @test */ @@ -254,16 +250,15 @@ class GroupServiceTest extends FeatureTestCase { Settings::set('defaultGroup', -1); Settings::set('activeGroup', $this->groupTwo->id); - + Groups::assign($this->twofaccountOne->id); - + $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->twofaccountOne->id, + 'id' => $this->twofaccountOne->id, 'group_id' => $this->groupTwo->id, ]); } - /** * @test */ @@ -271,16 +266,15 @@ class GroupServiceTest extends FeatureTestCase { Settings::set('defaultGroup', -1); Settings::set('activeGroup', 100000); - + Groups::assign($this->twofaccountOne->id); - + $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->twofaccountOne->id, + 'id' => $this->twofaccountOne->id, 'group_id' => null, ]); } - /** * @test */ @@ -288,8 +282,7 @@ class GroupServiceTest extends FeatureTestCase { Groups::assign([$this->twofaccountOne->id, $this->twofaccountTwo->id], $this->groupOne); $accounts = Groups::getAccounts($this->groupOne); - + $this->assertEquals(2, $accounts->count()); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Services/LogoServiceTest.php b/tests/Feature/Services/LogoServiceTest.php index 73d6b8b7..4a846c78 100644 --- a/tests/Feature/Services/LogoServiceTest.php +++ b/tests/Feature/Services/LogoServiceTest.php @@ -3,10 +3,9 @@ namespace Tests\Feature\Services; use App\Services\LogoService; -use Tests\FeatureTestCase; -use Tests\TestCase; -use Mockery\MockInterface; use Illuminate\Foundation\Testing\WithoutMiddleware; +use Mockery\MockInterface; +use Tests\TestCase; /** * @covers \App\Services\LogoService @@ -23,7 +22,6 @@ class LogoServiceTest extends TestCase parent::setUp(); } - /** * @test */ @@ -37,11 +35,10 @@ class LogoServiceTest extends TestCase }); $icon = $logoServiceMock->getIcon('service'); - + $this->assertNotNull($icon); } - /** * @test */ @@ -55,8 +52,7 @@ class LogoServiceTest extends TestCase }); $icon = $logoServiceMock->getIcon('no_logo_should_exists_with_this_name'); - + $this->assertEquals(null, $icon); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Services/QrCodeServiceTest.php b/tests/Feature/Services/QrCodeServiceTest.php index 1f6cbf6b..c5e5ca59 100644 --- a/tests/Feature/Services/QrCodeServiceTest.php +++ b/tests/Feature/Services/QrCodeServiceTest.php @@ -2,9 +2,9 @@ namespace Tests\Feature\Services; -use Tests\FeatureTestCase; -use Tests\Classes\LocalFile; use App\Facades\QrCode; +use Tests\Classes\LocalFile; +use Tests\FeatureTestCase; /** * @covers \App\Services\QrCodeService @@ -12,10 +12,11 @@ use App\Facades\QrCode; class QrCodeServiceTest extends FeatureTestCase { private const STRING_TO_ENCODE = 'stringToEncode'; + private const STRING_ENCODED = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAIAAAAiOjnJAAAABnRSTlMA/wD/AP83WBt9AAAACXBIWXMAAA7EAAAOxAGVKw4bAAADOklEQVR4nO3dMW7kMBAAwdPh/v/ldeBLFRCYBkm7KveaEBoMBhT1fD6fPzDt7+4F8DMJi4SwSAiLhLBICIuEsEgIi4SwSAiLhLBICIuEsEgIi4SwSPxb/YPneYp1jHs7Z7a6/tXzam+/P7WeXVafgx2LhLBICIuEsEgIi4SwSAiLxPIc682u9xOn5lKnzZNueZ5v7FgkhEVCWCSERUJYJIRFQlgkxuZYb6bmIlNznanzUrfPmer127FICIuEsEgIi4SwSAiLhLBI5HOs290y3zqNHYuEsEgIi4SwSAiLhLBICIuEOdZ/p71XeDs7FglhkRAWCWGREBYJYZEQFol8jnXa+aTT1rPqlvXbsUgIi4SwSAiLhLBICIuEsEiMzbFuOc9U34819b7hLc/zjR2LhLBICIuEsEgIi4SwSAiLxHPL+Z7a1HcP+WbHIiEsEsIiISwSwiIhLBLCIrE8x6rPCU2tpz5f9eaWc1r1Ou1YJIRFQlgkhEVCWCSERUJYJPLzWKd912/Xuavb3xM0x+IIwiIhLBLCIiEsEsIiISwSy/dj7ZpL1fOn+nxS/X/rc2ar7FgkhEVCWCSERUJYJIRFQlgk8u8VrjrtPb4p9VxtVf37diwSwiIhLBLCIiEsEsIiISwS+f1Yu+6dmlKvf8ppczs7FglhkRAWCWGREBYJYZEQFolf973C0+5bX7XrPcRVdiwSwiIhLBLCIiEsEsIiISwSx32vcMqu+9lP+7+7zmnZsUgIi4SwSAiLhLBICIuEsEiM3Y91y/cH699Z/f2357Y6l6qfg+8VcgRhkRAWCWGREBYJYZEQFon8nvf6XvJd6vNP9fcHvVfIlYRFQlgkhEVCWCSERUJYJI77XmHttPvQp9az6x78N3YsEsIiISwSwiIhLBLCIiEsEr9ujjXltHvCTvt+oh2LhLBICIuEsEgIi4SwSAiLRD7HOu19wDf1veqn3V9V/74di4SwSAiLhLBICIuEsEgIi8TYHOu080mrpt7LO+3+qqn75VfZsUgIi4SwSAiLhLBICIuEsEg8t5yX4i52LBLCIiEsEsIiISwSwiIhLBLCIiEsEsIiISwSwiIhLBLCIiEsEl+BmgChoSs9XAAAAABJRU5ErkJggg=='; + private const DECODED_IMAGE = 'otpauth://totp/test@test.com?secret=A4GRFHVIRBGY7UIW'; - /** * @test */ @@ -24,7 +25,6 @@ class QrCodeServiceTest extends FeatureTestCase parent::setUp(); } - /** * @test */ @@ -33,7 +33,6 @@ class QrCodeServiceTest extends FeatureTestCase $this->assertEquals(self::STRING_ENCODED, QrCode::encode(self::STRING_TO_ENCODE)); } - /** * @test */ @@ -44,7 +43,6 @@ class QrCodeServiceTest extends FeatureTestCase $this->assertEquals(self::DECODED_IMAGE, QrCode::decode($file)); } - /** * @test */ @@ -54,5 +52,4 @@ class QrCodeServiceTest extends FeatureTestCase QrCode::decode(LocalFile::fake()->invalidQrcode()); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Services/SettingServiceTest.php b/tests/Feature/Services/SettingServiceTest.php index 72ab5e3a..6b3bab67 100644 --- a/tests/Feature/Services/SettingServiceTest.php +++ b/tests/Feature/Services/SettingServiceTest.php @@ -2,12 +2,11 @@ namespace Tests\Feature\Services; -use Tests\FeatureTestCase; +use App\Facades\Settings; +use App\Models\TwoFAccount; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\DB; -use App\Models\TwoFAccount; -use App\Facades\Settings; - +use Tests\FeatureTestCase; /** * @covers \App\Services\SettingService @@ -17,26 +16,43 @@ class SettingServiceTest extends FeatureTestCase /** * App\Models\Group $groupOne, $groupTwo */ - protected $twofaccountOne, $twofaccountTwo; + protected $twofaccountOne; + + protected $twofaccountTwo; private const KEY = 'key'; + private const VALUE = 'value'; + private const SETTING_NAME = 'MySetting'; + private const SETTING_NAME_ALT = 'MySettingAlt'; + private const SETTING_VALUE_STRING = 'MyValue'; + private const SETTING_VALUE_TRUE_TRANSFORMED = '{{1}}'; + private const SETTING_VALUE_FALSE_TRANSFORMED = '{{}}'; + private const SETTING_VALUE_INT = 10; private const ACCOUNT = 'account'; + private const SERVICE = 'service'; + private const SECRET = 'A4GRFHVVRBGY7UIW'; + private const ALGORITHM_CUSTOM = 'sha256'; + private const DIGITS_CUSTOM = 7; + private const PERIOD_CUSTOM = 40; + private const IMAGE = 'https%3A%2F%2Fen.opensuse.org%2Fimages%2F4%2F44%2FButton-filled-colour.png'; + private const ICON = 'test.png'; - private const TOTP_FULL_CUSTOM_URI = 'otpauth://totp/'.self::SERVICE.':'.self::ACCOUNT.'?secret='.self::SECRET.'&issuer='.self::SERVICE.'&digits='.self::DIGITS_CUSTOM.'&period='.self::PERIOD_CUSTOM.'&algorithm='.self::ALGORITHM_CUSTOM.'&image='.self::IMAGE; + + private const TOTP_FULL_CUSTOM_URI = 'otpauth://totp/' . self::SERVICE . ':' . self::ACCOUNT . '?secret=' . self::SECRET . '&issuer=' . self::SERVICE . '&digits=' . self::DIGITS_CUSTOM . '&period=' . self::PERIOD_CUSTOM . '&algorithm=' . self::ALGORITHM_CUSTOM . '&image=' . self::IMAGE; /** * @test @@ -45,34 +61,33 @@ class SettingServiceTest extends FeatureTestCase { parent::setUp(); - $this->twofaccountOne = new TwoFAccount; + $this->twofaccountOne = new TwoFAccount; $this->twofaccountOne->legacy_uri = self::TOTP_FULL_CUSTOM_URI; - $this->twofaccountOne->service = self::SERVICE; - $this->twofaccountOne->account = self::ACCOUNT; - $this->twofaccountOne->icon = self::ICON; - $this->twofaccountOne->otp_type = 'totp'; - $this->twofaccountOne->secret = self::SECRET; - $this->twofaccountOne->digits = self::DIGITS_CUSTOM; - $this->twofaccountOne->algorithm = self::ALGORITHM_CUSTOM; - $this->twofaccountOne->period = self::PERIOD_CUSTOM; - $this->twofaccountOne->counter = null; + $this->twofaccountOne->service = self::SERVICE; + $this->twofaccountOne->account = self::ACCOUNT; + $this->twofaccountOne->icon = self::ICON; + $this->twofaccountOne->otp_type = 'totp'; + $this->twofaccountOne->secret = self::SECRET; + $this->twofaccountOne->digits = self::DIGITS_CUSTOM; + $this->twofaccountOne->algorithm = self::ALGORITHM_CUSTOM; + $this->twofaccountOne->period = self::PERIOD_CUSTOM; + $this->twofaccountOne->counter = null; $this->twofaccountOne->save(); - $this->twofaccountTwo = new TwoFAccount; + $this->twofaccountTwo = new TwoFAccount; $this->twofaccountTwo->legacy_uri = self::TOTP_FULL_CUSTOM_URI; - $this->twofaccountTwo->service = self::SERVICE; - $this->twofaccountTwo->account = self::ACCOUNT; - $this->twofaccountTwo->icon = self::ICON; - $this->twofaccountTwo->otp_type = 'totp'; - $this->twofaccountTwo->secret = self::SECRET; - $this->twofaccountTwo->digits = self::DIGITS_CUSTOM; - $this->twofaccountTwo->algorithm = self::ALGORITHM_CUSTOM; - $this->twofaccountTwo->period = self::PERIOD_CUSTOM; - $this->twofaccountTwo->counter = null; + $this->twofaccountTwo->service = self::SERVICE; + $this->twofaccountTwo->account = self::ACCOUNT; + $this->twofaccountTwo->icon = self::ICON; + $this->twofaccountTwo->otp_type = 'totp'; + $this->twofaccountTwo->secret = self::SECRET; + $this->twofaccountTwo->digits = self::DIGITS_CUSTOM; + $this->twofaccountTwo->algorithm = self::ALGORITHM_CUSTOM; + $this->twofaccountTwo->period = self::PERIOD_CUSTOM; + $this->twofaccountTwo->counter = null; $this->twofaccountTwo->save(); } - /** * @test */ @@ -83,7 +98,6 @@ class SettingServiceTest extends FeatureTestCase $this->assertEquals(self::SETTING_VALUE_STRING, Settings::get(self::SETTING_NAME)); } - /** * @test */ @@ -94,7 +108,6 @@ class SettingServiceTest extends FeatureTestCase $this->assertEquals(true, Settings::get(self::SETTING_NAME)); } - /** * @test */ @@ -105,7 +118,6 @@ class SettingServiceTest extends FeatureTestCase $this->assertEquals(false, Settings::get(self::SETTING_NAME)); } - /** * @test */ @@ -119,7 +131,6 @@ class SettingServiceTest extends FeatureTestCase $this->assertIsInt($value); } - /** * @test */ @@ -138,12 +149,10 @@ class SettingServiceTest extends FeatureTestCase $this->assertArrayHasKey($key, $all); $this->assertEquals($all[$key], $val); } - + $this->assertArrayHasKey('lang', $all); - } - /** * @test */ @@ -152,11 +161,10 @@ class SettingServiceTest extends FeatureTestCase $value = Settings::set(self::SETTING_NAME, self::SETTING_VALUE_STRING); $this->assertDatabaseHas('options', [ - self::KEY => self::SETTING_NAME, - self::VALUE => self::SETTING_VALUE_STRING + self::KEY => self::SETTING_NAME, + self::VALUE => self::SETTING_VALUE_STRING, ]); } - /** * @test @@ -174,7 +182,6 @@ class SettingServiceTest extends FeatureTestCase }); } - /** * @test */ @@ -192,7 +199,6 @@ class SettingServiceTest extends FeatureTestCase }); } - /** * @test */ @@ -210,7 +216,6 @@ class SettingServiceTest extends FeatureTestCase }); } - /** * @test * @dataProvider provideUndecipherableData @@ -225,12 +230,11 @@ class SettingServiceTest extends FeatureTestCase ->where('id', $this->twofaccountOne->id) ->update($data); - Settings::set('useEncryption', false); + Settings::set('useEncryption', false); $twofaccount = TwoFAccount::find($this->twofaccountOne->id); } - /** * Provide invalid data for validation test */ @@ -238,40 +242,38 @@ class SettingServiceTest extends FeatureTestCase { return [ [[ - 'account' => 'undecipherableString' + 'account' => 'undecipherableString', ]], [[ - 'secret' => 'undecipherableString' + 'secret' => 'undecipherableString', ]], [[ - 'legacy_uri' => 'undecipherableString' + 'legacy_uri' => 'undecipherableString', ]], ]; } - /** * @test */ public function test_set_array_of_settings_persist_correct_values() { $value = Settings::set([ - self::SETTING_NAME => self::SETTING_VALUE_STRING, + self::SETTING_NAME => self::SETTING_VALUE_STRING, self::SETTING_NAME_ALT => self::SETTING_VALUE_INT, ]); $this->assertDatabaseHas('options', [ - self::KEY => self::SETTING_NAME, - self::VALUE => self::SETTING_VALUE_STRING + self::KEY => self::SETTING_NAME, + self::VALUE => self::SETTING_VALUE_STRING, ]); $this->assertDatabaseHas('options', [ - self::KEY => self::SETTING_NAME_ALT, - self::VALUE => self::SETTING_VALUE_INT + self::KEY => self::SETTING_NAME_ALT, + self::VALUE => self::SETTING_VALUE_INT, ]); } - /** * @test */ @@ -280,12 +282,11 @@ class SettingServiceTest extends FeatureTestCase $value = Settings::set(self::SETTING_NAME, true); $this->assertDatabaseHas('options', [ - self::KEY => self::SETTING_NAME, - self::VALUE => self::SETTING_VALUE_TRUE_TRANSFORMED + self::KEY => self::SETTING_NAME, + self::VALUE => self::SETTING_VALUE_TRUE_TRANSFORMED, ]); } - /** * @test */ @@ -294,12 +295,11 @@ class SettingServiceTest extends FeatureTestCase $value = Settings::set(self::SETTING_NAME, false); $this->assertDatabaseHas('options', [ - self::KEY => self::SETTING_NAME, - self::VALUE => self::SETTING_VALUE_FALSE_TRANSFORMED + self::KEY => self::SETTING_NAME, + self::VALUE => self::SETTING_VALUE_FALSE_TRANSFORMED, ]); } - /** * @test */ @@ -312,8 +312,8 @@ class SettingServiceTest extends FeatureTestCase $value = Settings::delete(self::SETTING_NAME); $this->assertDatabaseMissing('options', [ - self::KEY => self::SETTING_NAME, - self::VALUE => self::SETTING_VALUE_STRING + self::KEY => self::SETTING_NAME, + self::VALUE => self::SETTING_VALUE_STRING, ]); } -} \ No newline at end of file +} diff --git a/tests/Feature/Services/TwoFAccountServiceTest.php b/tests/Feature/Services/TwoFAccountServiceTest.php index 42b9713c..9499e4d7 100644 --- a/tests/Feature/Services/TwoFAccountServiceTest.php +++ b/tests/Feature/Services/TwoFAccountServiceTest.php @@ -2,12 +2,11 @@ namespace Tests\Feature\Services; +use App\Facades\TwoFAccounts; use App\Models\Group; use App\Models\TwoFAccount; -use Tests\FeatureTestCase; use Tests\Classes\OtpTestData; -use App\Facades\TwoFAccounts; - +use Tests\FeatureTestCase; /** * @covers \App\Services\TwoFAccountService @@ -19,19 +18,16 @@ class TwoFAccountServiceTest extends FeatureTestCase */ protected $customTotpTwofaccount; - /** * App\Models\Group $group */ protected $group; - /** * App\Models\TwoFAccount $customTotpTwofaccount */ protected $customHotpTwofaccount; - /** * @test */ @@ -39,39 +35,37 @@ class TwoFAccountServiceTest extends FeatureTestCase { parent::setUp(); - $this->customTotpTwofaccount = new TwoFAccount; + $this->customTotpTwofaccount = new TwoFAccount; $this->customTotpTwofaccount->legacy_uri = OtpTestData::TOTP_FULL_CUSTOM_URI; - $this->customTotpTwofaccount->service = OtpTestData::SERVICE; - $this->customTotpTwofaccount->account = OtpTestData::ACCOUNT; - $this->customTotpTwofaccount->icon = OtpTestData::ICON; - $this->customTotpTwofaccount->otp_type = 'totp'; - $this->customTotpTwofaccount->secret = OtpTestData::SECRET; - $this->customTotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; - $this->customTotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; - $this->customTotpTwofaccount->period = OtpTestData::PERIOD_CUSTOM; - $this->customTotpTwofaccount->counter = null; + $this->customTotpTwofaccount->service = OtpTestData::SERVICE; + $this->customTotpTwofaccount->account = OtpTestData::ACCOUNT; + $this->customTotpTwofaccount->icon = OtpTestData::ICON; + $this->customTotpTwofaccount->otp_type = 'totp'; + $this->customTotpTwofaccount->secret = OtpTestData::SECRET; + $this->customTotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; + $this->customTotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; + $this->customTotpTwofaccount->period = OtpTestData::PERIOD_CUSTOM; + $this->customTotpTwofaccount->counter = null; $this->customTotpTwofaccount->save(); - $this->customHotpTwofaccount = new TwoFAccount; + $this->customHotpTwofaccount = new TwoFAccount; $this->customHotpTwofaccount->legacy_uri = OtpTestData::HOTP_FULL_CUSTOM_URI; - $this->customHotpTwofaccount->service = OtpTestData::SERVICE; - $this->customHotpTwofaccount->account = OtpTestData::ACCOUNT; - $this->customHotpTwofaccount->icon = OtpTestData::ICON; - $this->customHotpTwofaccount->otp_type = 'hotp'; - $this->customHotpTwofaccount->secret = OtpTestData::SECRET; - $this->customHotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; - $this->customHotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; - $this->customHotpTwofaccount->period = null; - $this->customHotpTwofaccount->counter = OtpTestData::COUNTER_CUSTOM; + $this->customHotpTwofaccount->service = OtpTestData::SERVICE; + $this->customHotpTwofaccount->account = OtpTestData::ACCOUNT; + $this->customHotpTwofaccount->icon = OtpTestData::ICON; + $this->customHotpTwofaccount->otp_type = 'hotp'; + $this->customHotpTwofaccount->secret = OtpTestData::SECRET; + $this->customHotpTwofaccount->digits = OtpTestData::DIGITS_CUSTOM; + $this->customHotpTwofaccount->algorithm = OtpTestData::ALGORITHM_CUSTOM; + $this->customHotpTwofaccount->period = null; + $this->customHotpTwofaccount->counter = OtpTestData::COUNTER_CUSTOM; $this->customHotpTwofaccount->save(); - - $this->group = new Group; + $this->group = new Group; $this->group->name = 'MyGroup'; $this->group->save(); } - /** * @test */ @@ -79,21 +73,20 @@ class TwoFAccountServiceTest extends FeatureTestCase { $twofaccounts = collect([$this->customHotpTwofaccount, $this->customTotpTwofaccount]); $this->group->twofaccounts()->saveMany($twofaccounts); - - TwoFAccounts::withdraw($this->customHotpTwofaccount->id.','.$this->customTotpTwofaccount->id); + + TwoFAccounts::withdraw($this->customHotpTwofaccount->id . ',' . $this->customTotpTwofaccount->id); $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->customTotpTwofaccount->id, - 'group_id' => null, + 'id' => $this->customTotpTwofaccount->id, + 'group_id' => null, ]); $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->customHotpTwofaccount->id, - 'group_id' => null, + 'id' => $this->customHotpTwofaccount->id, + 'group_id' => null, ]); } - /** * @test */ @@ -101,21 +94,20 @@ class TwoFAccountServiceTest extends FeatureTestCase { $twofaccounts = collect([$this->customHotpTwofaccount, $this->customTotpTwofaccount]); $this->group->twofaccounts()->saveMany($twofaccounts); - + TwoFAccounts::withdraw([$this->customHotpTwofaccount->id, $this->customTotpTwofaccount->id]); $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->customTotpTwofaccount->id, - 'group_id' => null, + 'id' => $this->customTotpTwofaccount->id, + 'group_id' => null, ]); $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->customHotpTwofaccount->id, - 'group_id' => null, + 'id' => $this->customHotpTwofaccount->id, + 'group_id' => null, ]); } - /** * @test */ @@ -123,16 +115,15 @@ class TwoFAccountServiceTest extends FeatureTestCase { $twofaccounts = collect([$this->customHotpTwofaccount, $this->customTotpTwofaccount]); $this->group->twofaccounts()->saveMany($twofaccounts); - + TwoFAccounts::withdraw($this->customTotpTwofaccount->id); $this->assertDatabaseHas('twofaccounts', [ - 'id' => $this->customTotpTwofaccount->id, - 'group_id' => null, + 'id' => $this->customTotpTwofaccount->id, + 'group_id' => null, ]); } - /** * @test */ @@ -141,57 +132,53 @@ class TwoFAccountServiceTest extends FeatureTestCase $this->assertNull(TwoFAccounts::withdraw(null)); } - /** * @test */ public function test_delete_comma_separated_ids() - { - TwoFAccounts::delete($this->customHotpTwofaccount->id.','.$this->customTotpTwofaccount->id); + { + TwoFAccounts::delete($this->customHotpTwofaccount->id . ',' . $this->customTotpTwofaccount->id); $this->assertDatabaseMissing('twofaccounts', [ - 'id' => $this->customTotpTwofaccount->id, + 'id' => $this->customTotpTwofaccount->id, ]); $this->assertDatabaseMissing('twofaccounts', [ - 'id' => $this->customHotpTwofaccount->id, + 'id' => $this->customHotpTwofaccount->id, ]); } - /** * @test */ public function test_delete_array_of_ids() - { + { TwoFAccounts::delete([$this->customTotpTwofaccount->id, $this->customHotpTwofaccount->id]); $this->assertDatabaseMissing('twofaccounts', [ - 'id' => $this->customTotpTwofaccount->id, + 'id' => $this->customTotpTwofaccount->id, ]); $this->assertDatabaseMissing('twofaccounts', [ - 'id' => $this->customHotpTwofaccount->id, + 'id' => $this->customHotpTwofaccount->id, ]); } - /** * @test */ public function test_delete_single_id() - { + { TwoFAccounts::delete($this->customTotpTwofaccount->id); $this->assertDatabaseMissing('twofaccounts', [ - 'id' => $this->customTotpTwofaccount->id, + 'id' => $this->customTotpTwofaccount->id, ]); } - /** * @test */ public function test_convert_migration_from_gauth_returns_correct_accounts() - { + { $twofaccounts = TwoFAccounts::migrate(OtpTestData::GOOGLE_AUTH_MIGRATION_URI); $this->assertCount(2, $twofaccounts); @@ -206,8 +193,8 @@ class TwoFAccountServiceTest extends FeatureTestCase $this->assertEquals(OtpTestData::ALGORITHM_DEFAULT, $twofaccounts->first()->algorithm); $this->assertEquals('totp', $twofaccounts->last()->otp_type); - $this->assertEquals(OtpTestData::SERVICE.'_bis', $twofaccounts->last()->service); - $this->assertEquals(OtpTestData::ACCOUNT.'_bis', $twofaccounts->last()->account); + $this->assertEquals(OtpTestData::SERVICE . '_bis', $twofaccounts->last()->service); + $this->assertEquals(OtpTestData::ACCOUNT . '_bis', $twofaccounts->last()->account); $this->assertEquals(OtpTestData::SECRET, $twofaccounts->last()->secret); $this->assertEquals(OtpTestData::DIGITS_DEFAULT, $twofaccounts->last()->digits); $this->assertEquals(OtpTestData::PERIOD_DEFAULT, $twofaccounts->last()->period); @@ -215,7 +202,6 @@ class TwoFAccountServiceTest extends FeatureTestCase $this->assertEquals(OtpTestData::ALGORITHM_DEFAULT, $twofaccounts->last()->algorithm); } - /** * @test */ @@ -234,8 +220,8 @@ class TwoFAccountServiceTest extends FeatureTestCase $twofaccount = new TwoFAccount; $twofaccount->fillWithOtpParameters($parameters)->save(); - $parameters['service'] = OtpTestData::SERVICE.'_bis'; - $parameters['account'] = OtpTestData::ACCOUNT.'_bis'; + $parameters['service'] = OtpTestData::SERVICE . '_bis'; + $parameters['account'] = OtpTestData::ACCOUNT . '_bis'; $twofaccount = new TwoFAccount; $twofaccount->fillWithOtpParameters($parameters)->save(); @@ -246,7 +232,6 @@ class TwoFAccountServiceTest extends FeatureTestCase $this->assertEquals(-1, $twofaccounts->last()->id); } - /** * @test */ @@ -255,5 +240,4 @@ class TwoFAccountServiceTest extends FeatureTestCase $this->expectException(\App\Exceptions\InvalidMigrationDataException::class); $twofaccounts = TwoFAccounts::migrate(OtpTestData::GOOGLE_AUTH_MIGRATION_URI_WITH_INVALID_DATA); } - -} \ No newline at end of file +} diff --git a/tests/FeatureTestCase.php b/tests/FeatureTestCase.php index 25aa1330..4f05583b 100644 --- a/tests/FeatureTestCase.php +++ b/tests/FeatureTestCase.php @@ -2,9 +2,9 @@ namespace Tests; -use Illuminate\Support\Facades\Artisan; use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; +use Illuminate\Support\Facades\Artisan; abstract class FeatureTestCase extends BaseTestCase { @@ -15,7 +15,6 @@ abstract class FeatureTestCase extends BaseTestCase */ use LazilyRefreshDatabase; - /** * Perform any work that should take place once the database has finished refreshing. * @@ -23,6 +22,6 @@ abstract class FeatureTestCase extends BaseTestCase */ protected function afterRefreshingDatabase() { - Artisan::call('passport:install',['--verbose' => 2]); + Artisan::call('passport:install', ['--verbose' => 2]); } } diff --git a/tests/ModelTestCase.php b/tests/ModelTestCase.php index 66d228df..d7fc039f 100644 --- a/tests/ModelTestCase.php +++ b/tests/ModelTestCase.php @@ -2,8 +2,8 @@ namespace Tests; -use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; @@ -11,17 +11,17 @@ use Illuminate\Database\Eloquent\Relations\HasMany; abstract class ModelTestCase extends TestCase { /** - * @param Model $model - * @param array $fillable - * @param array $guarded - * @param array $hidden - * @param array $visible - * @param array $casts - * @param array $dates - * @param string $collectionClass - * @param null $table - * @param string $primaryKey - * @param boolean $incrementing + * @param Model $model + * @param array $fillable + * @param array $guarded + * @param array $hidden + * @param array $visible + * @param array $casts + * @param array $dates + * @param string $collectionClass + * @param null $table + * @param string $primaryKey + * @param bool $incrementing * * - `$fillable` -> `getFillable()` * - `$guarded` -> `getGuarded()` @@ -70,14 +70,13 @@ abstract class ModelTestCase extends TestCase } } - /** - * @param HasMany $relation - * @param Model $model - * @param Model $related - * @param string $key - * @param string $parent - * @param \Closure $queryCheck + * @param HasMany $relation + * @param Model $model + * @param Model $related + * @param string $key + * @param string $parent + * @param \Closure $queryCheck * * - `getQuery()`: assert query has not been modified or modified properly. * - `getForeignKey()`: any `HasOneOrMany` or `BelongsTo` relation, but key type differs (see documentaiton). @@ -87,7 +86,7 @@ abstract class ModelTestCase extends TestCase { $this->assertInstanceOf(HasMany::class, $relation); - if (!is_null($queryCheck)) { + if (! is_null($queryCheck)) { $queryCheck->bindTo($this); $queryCheck($relation->getQuery(), $model, $relation); } @@ -102,17 +101,16 @@ abstract class ModelTestCase extends TestCase $parent = $model->getKeyName(); } - $this->assertEquals($model->getTable().'.'.$parent, $relation->getQualifiedParentKeyName()); + $this->assertEquals($model->getTable() . '.' . $parent, $relation->getQualifiedParentKeyName()); } - /** - * @param BelongsTo $relation - * @param Model $model - * @param Model $related - * @param string $key - * @param string $owner - * @param \Closure $queryCheck + * @param BelongsTo $relation + * @param Model $model + * @param Model $related + * @param string $key + * @param string $owner + * @param \Closure $queryCheck * * - `getQuery()`: assert query has not been modified or modified properly. * - `getForeignKey()`: any `HasOneOrMany` or `BelongsTo` relation, but key type differs (see documentaiton). @@ -122,7 +120,7 @@ abstract class ModelTestCase extends TestCase { $this->assertInstanceOf(BelongsTo::class, $relation); - if (!is_null($queryCheck)) { + if (! is_null($queryCheck)) { $queryCheck->bindTo($this); $queryCheck($relation->getQuery(), $model, $relation); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 6dfe07bb..5070528c 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,17 +2,14 @@ namespace Tests; -use Illuminate\Support\Facades\Artisan; -use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; - protected function setUp(): void + protected function setUp() : void { parent::setUp(); } - } diff --git a/tests/Unit/Api/v1/Controllers/GroupControllerTest.php b/tests/Unit/Api/v1/Controllers/GroupControllerTest.php index 8a74a229..7f71db63 100644 --- a/tests/Unit/Api/v1/Controllers/GroupControllerTest.php +++ b/tests/Unit/Api/v1/Controllers/GroupControllerTest.php @@ -2,15 +2,15 @@ namespace Tests\Unit\Api\v1\Controllers; -use App\Models\Group; -use Tests\TestCase; -use App\Models\TwoFAccount; +use App\Api\v1\Controllers\GroupController; use App\Facades\Groups; +use App\Models\Group; +use App\Models\TwoFAccount; use App\Services\SettingService; use Illuminate\Foundation\Testing\WithoutMiddleware; -use App\Api\v1\Controllers\GroupController; use Mockery; use Mockery\MockInterface; +use Tests\TestCase; /** * @covers \App\Api\v1\Controllers\GroupController @@ -24,13 +24,11 @@ class GroupControllerTest extends TestCase */ protected $controller; - /** * @var \App\Api\v1\Requests\GroupStoreRequest mocked request */ protected $groupStoreRequest; - public function setUp() : void { parent::setUp(); @@ -40,7 +38,6 @@ class GroupControllerTest extends TestCase $this->controller = new GroupController(); } - /** * @test */ @@ -57,7 +54,6 @@ class GroupControllerTest extends TestCase $this->assertContainsOnlyInstancesOf('App\Api\v1\Resources\GroupResource', $response->collection); } - /** * @test */ @@ -78,7 +74,6 @@ class GroupControllerTest extends TestCase $this->assertInstanceOf('App\Models\Group', $response->original); } - /** * @test */ @@ -91,7 +86,6 @@ class GroupControllerTest extends TestCase $this->assertInstanceOf('App\Api\v1\Resources\GroupResource', $response); } - /** * @test */ @@ -112,13 +106,12 @@ class GroupControllerTest extends TestCase $this->assertInstanceOf('App\Api\v1\Resources\GroupResource', $response); } - /** * @test */ public function test_assignAccounts_returns_api_resource_assigned_using_groupService() { - $group = Group::factory()->make(); + $group = Group::factory()->make(); $groupAssignRequest = Mockery::mock('App\Api\v1\Requests\GroupAssignRequest'); $groupAssignRequest->shouldReceive('validated') @@ -134,14 +127,13 @@ class GroupControllerTest extends TestCase $this->assertInstanceOf('App\Api\v1\Resources\GroupResource', $response); } - /** * @test */ public function test_accounts_returns_api_resources_fetched_using_groupService() { $group = Group::factory()->make(); - + $settingService = $this->mock(SettingService::class, function (MockInterface $settingService) { $settingService->shouldReceive('get') ->andReturn(false); @@ -159,7 +151,6 @@ class GroupControllerTest extends TestCase $this->assertContainsOnlyInstancesOf('App\Api\v1\Resources\TwoFAccountReadResource', $response->collection); } - /** * @test */ @@ -175,4 +166,4 @@ class GroupControllerTest extends TestCase $this->assertInstanceOf('Illuminate\Http\JsonResponse', $response); } -} \ No newline at end of file +} diff --git a/tests/Unit/Events/GroupDeletingTest.php b/tests/Unit/Events/GroupDeletingTest.php index 120528b4..09f32f4e 100644 --- a/tests/Unit/Events/GroupDeletingTest.php +++ b/tests/Unit/Events/GroupDeletingTest.php @@ -2,11 +2,10 @@ namespace Tests\Unit\Events; -use App\Models\Group; use App\Events\GroupDeleting; +use App\Models\Group; use Tests\TestCase; - /** * @covers \App\Events\GroupDeleting */ @@ -22,4 +21,4 @@ class GroupDeletingTest extends TestCase $this->assertSame($group, $event->group); } -} \ No newline at end of file +} diff --git a/tests/Unit/Events/TwoFAccountDeletedTest.php b/tests/Unit/Events/TwoFAccountDeletedTest.php index f2166b26..b51d10aa 100644 --- a/tests/Unit/Events/TwoFAccountDeletedTest.php +++ b/tests/Unit/Events/TwoFAccountDeletedTest.php @@ -2,11 +2,11 @@ namespace Tests\Unit\Events; -use App\Models\TwoFAccount; use App\Events\TwoFAccountDeleted; -use Tests\TestCase; -use Mockery\MockInterface; +use App\Models\TwoFAccount; use App\Services\SettingService; +use Mockery\MockInterface; +use Tests\TestCase; /** * @covers \App\Events\TwoFAccountDeleted @@ -24,8 +24,8 @@ class TwoFAccountDeletedTest extends TestCase }); $twofaccount = TwoFAccount::factory()->make(); - $event = new TwoFAccountDeleted($twofaccount); + $event = new TwoFAccountDeleted($twofaccount); $this->assertSame($twofaccount, $event->twofaccount); } -} \ No newline at end of file +} diff --git a/tests/Unit/Exceptions/HandlerTest.php b/tests/Unit/Exceptions/HandlerTest.php index 6f628bd9..65cbc6e3 100644 --- a/tests/Unit/Exceptions/HandlerTest.php +++ b/tests/Unit/Exceptions/HandlerTest.php @@ -3,28 +3,26 @@ namespace Tests\Unit\Exceptions; use App\Exceptions\Handler; -use Illuminate\Http\Request; -use Illuminate\Http\JsonResponse; use Illuminate\Contracts\Container\Container; +use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; use Tests\TestCase; - /** * @covers \App\Exceptions\Handler */ class HandlerTest extends TestCase { - /** - * @test - * - * @dataProvider provideExceptionsforBadRequest - */ + * @test + * + * @dataProvider provideExceptionsforBadRequest + */ public function test_exceptions_returns_badRequest_json_response($exception) { - $request = $this->createMock(Request::class); + $request = $this->createMock(Request::class); $instance = new Handler($this->createMock(Container::class)); - $class = new \ReflectionClass(Handler::class); + $class = new \ReflectionClass(Handler::class); $method = $class->getMethod('render'); $method->setAccessible(true); @@ -36,7 +34,7 @@ class HandlerTest extends TestCase $response = \Illuminate\Testing\TestResponse::fromBaseResponse($response); $response->assertStatus(400) ->assertJsonStructure([ - 'message' + 'message', ]); } @@ -47,42 +45,42 @@ class HandlerTest extends TestCase { return [ [ - '\App\Exceptions\InvalidOtpParameterException' + '\App\Exceptions\InvalidOtpParameterException', ], [ - '\App\Exceptions\InvalidQrCodeException' + '\App\Exceptions\InvalidQrCodeException', ], [ - '\App\Exceptions\InvalidSecretException' + '\App\Exceptions\InvalidSecretException', ], [ - '\App\Exceptions\DbEncryptionException' + '\App\Exceptions\DbEncryptionException', ], [ - '\App\Exceptions\InvalidMigrationDataException' + '\App\Exceptions\InvalidMigrationDataException', ], [ - '\App\Exceptions\UndecipherableException' + '\App\Exceptions\UndecipherableException', ], [ - '\App\Exceptions\UnsupportedMigrationException' + '\App\Exceptions\UnsupportedMigrationException', ], [ - '\App\Exceptions\UnsupportedOtpTypeException' + '\App\Exceptions\UnsupportedOtpTypeException', ], ]; } /** - * @test - * - * @dataProvider provideExceptionsforNotFound - */ + * @test + * + * @dataProvider provideExceptionsforNotFound + */ public function test_exceptions_returns_notFound_json_response($exception) { - $request = $this->createMock(Request::class); + $request = $this->createMock(Request::class); $instance = new Handler($this->createMock(Container::class)); - $class = new \ReflectionClass(Handler::class); + $class = new \ReflectionClass(Handler::class); $method = $class->getMethod('render'); $method->setAccessible(true); @@ -94,7 +92,7 @@ class HandlerTest extends TestCase $response = \Illuminate\Testing\TestResponse::fromBaseResponse($response); $response->assertStatus(404) ->assertJsonStructure([ - 'message' + 'message', ]); } @@ -105,28 +103,28 @@ class HandlerTest extends TestCase { return [ [ - '\Illuminate\Database\Eloquent\ModelNotFoundException' + '\Illuminate\Database\Eloquent\ModelNotFoundException', ], [ - '\Symfony\Component\HttpKernel\Exception\NotFoundHttpException' + '\Symfony\Component\HttpKernel\Exception\NotFoundHttpException', ], ]; } /** - * @test - */ + * @test + */ public function test_authenticationException_returns_proxyAuthRequired_json_response_with_proxy_guard() { - $request = $this->createMock(Request::class); + $request = $this->createMock(Request::class); $instance = new Handler($this->createMock(Container::class)); - $class = new \ReflectionClass(Handler::class); + $class = new \ReflectionClass(Handler::class); $method = $class->getMethod('render'); $method->setAccessible(true); $mockException = $this->createMock(\Illuminate\Auth\AuthenticationException::class); - $mockException->method("guards")->willReturn(['reverse-proxy-guard']); + $mockException->method('guards')->willReturn(['reverse-proxy-guard']); $response = $method->invokeArgs($instance, [$request, $mockException]); @@ -135,7 +133,7 @@ class HandlerTest extends TestCase $response = \Illuminate\Testing\TestResponse::fromBaseResponse($response); $response->assertStatus(407) ->assertJsonStructure([ - 'message' + 'message', ]); } -} \ No newline at end of file +} diff --git a/tests/Unit/Extensions/RemoteUserProviderTest.php b/tests/Unit/Extensions/RemoteUserProviderTest.php index 5da8bed8..b15da89e 100644 --- a/tests/Unit/Extensions/RemoteUserProviderTest.php +++ b/tests/Unit/Extensions/RemoteUserProviderTest.php @@ -2,9 +2,8 @@ namespace Tests\Unit\Extensions; -use Tests\TestCase; use App\Extensions\RemoteUserProvider; - +use Tests\TestCase; /** * @covers \App\Extensions\RemoteUserProvider @@ -16,11 +15,11 @@ class RemoteUserProviderTest extends TestCase $provider = new RemoteUserProvider; $user = $provider->retrieveById([ - 'user' => 'testUser', - 'email' => 'test@example.org' + 'user' => 'testUser', + 'email' => 'test@example.org', ]); $this->assertInstanceOf('\App\Models\User', $user); $this->assertEquals(false, $user->exists); } -} \ No newline at end of file +} diff --git a/tests/Unit/GroupModelTest.php b/tests/Unit/GroupModelTest.php index d3546650..665c148e 100644 --- a/tests/Unit/GroupModelTest.php +++ b/tests/Unit/GroupModelTest.php @@ -2,10 +2,9 @@ namespace Tests\Unit; +use App\Events\GroupDeleting; use App\Models\Group; use App\Models\TwoFAccount; -use App\Events\GroupDeleting; -use Illuminate\Database\Eloquent\Relations\HasMany; use Tests\ModelTestCase; /** @@ -13,7 +12,6 @@ use Tests\ModelTestCase; */ class GroupModelTest extends ModelTestCase { - /** * @test */ @@ -25,19 +23,18 @@ class GroupModelTest extends ModelTestCase ['created_at', 'updated_at'], ['*'], [], - ['id' => 'int', 'twofaccounts_count' => 'integer',], + ['id' => 'int', 'twofaccounts_count' => 'integer'], ['deleting' => GroupDeleting::class] ); } - /** * @test */ public function test_groups_relation() { - $group = new Group(); + $group = new Group(); $accounts = $group->twofaccounts(); $this->assertHasManyRelation($accounts, $group, new TwoFAccount()); } -} \ No newline at end of file +} diff --git a/tests/Unit/Listeners/CleanIconStorageTest.php b/tests/Unit/Listeners/CleanIconStorageTest.php index 40eaa7ed..9f9fc8d0 100644 --- a/tests/Unit/Listeners/CleanIconStorageTest.php +++ b/tests/Unit/Listeners/CleanIconStorageTest.php @@ -2,15 +2,14 @@ namespace Tests\Unit\Listeners; -use App\Models\TwoFAccount; use App\Events\TwoFAccountDeleted; -use Tests\TestCase; use App\Listeners\CleanIconStorage; -use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Facades\Event; -use Mockery\MockInterface; +use App\Models\TwoFAccount; use App\Services\SettingService; - +use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Storage; +use Mockery\MockInterface; +use Tests\TestCase; /** * @covers \App\Listeners\CleanIconStorage @@ -25,8 +24,8 @@ class CleanIconStorageTest extends TestCase }); $twofaccount = TwoFAccount::factory()->make(); - $event = new TwoFAccountDeleted($twofaccount); - $listener = new CleanIconStorage(); + $event = new TwoFAccountDeleted($twofaccount); + $listener = new CleanIconStorage(); Storage::shouldReceive('disk->delete') ->with($event->twofaccount->icon) @@ -35,7 +34,6 @@ class CleanIconStorageTest extends TestCase $this->assertNull($listener->handle($event)); } - public function test_CleanIconStorage_listen_to_TwoFAccountDeleted_event() { Event::fake(); @@ -45,4 +43,4 @@ class CleanIconStorageTest extends TestCase CleanIconStorage::class ); } -} \ No newline at end of file +} diff --git a/tests/Unit/Listeners/DissociateTwofaccountFromGroupTest.php b/tests/Unit/Listeners/DissociateTwofaccountFromGroupTest.php index 75cd4bbf..84c08dbb 100644 --- a/tests/Unit/Listeners/DissociateTwofaccountFromGroupTest.php +++ b/tests/Unit/Listeners/DissociateTwofaccountFromGroupTest.php @@ -2,12 +2,11 @@ namespace Tests\Unit\Listeners; -use App\Models\Group; use App\Events\GroupDeleting; -use Tests\TestCase; use App\Listeners\DissociateTwofaccountFromGroup; +use App\Models\Group; use Illuminate\Support\Facades\Event; - +use Tests\TestCase; /** * @covers \App\Listeners\DissociateTwofaccountFromGroup @@ -23,7 +22,6 @@ class DissociateTwofaccountFromGroupTest extends TestCase // $this->assertNull($listener->handle($event)); // } - public function test_DissociateTwofaccountFromGroup_listen_to_groupDeleting_event() { Event::fake(); @@ -33,4 +31,4 @@ class DissociateTwofaccountFromGroupTest extends TestCase DissociateTwofaccountFromGroup::class ); } -} \ No newline at end of file +} diff --git a/tests/Unit/TwoFAccountModelTest.php b/tests/Unit/TwoFAccountModelTest.php index d8633ae6..412a284e 100644 --- a/tests/Unit/TwoFAccountModelTest.php +++ b/tests/Unit/TwoFAccountModelTest.php @@ -2,19 +2,18 @@ namespace Tests\Unit; -use App\Models\TwoFAccount; use App\Events\TwoFAccountDeleted; -use Tests\ModelTestCase; +use App\Models\TwoFAccount; +use App\Services\SettingService; use Illuminate\Support\Facades\Crypt; use Mockery\MockInterface; -use App\Services\SettingService; +use Tests\ModelTestCase; /** * @covers \App\Models\TwoFAccount */ class TwoFAccountModelTest extends ModelTestCase { - /** * @test */ @@ -26,7 +25,7 @@ class TwoFAccountModelTest extends ModelTestCase [], ['*'], [], - ['id' => 'int'], + ['id' => 'int'], ['deleted' => TwoFAccountDeleted::class], ['created_at', 'updated_at'], \Illuminate\Database\Eloquent\Collection::class, @@ -36,10 +35,9 @@ class TwoFAccountModelTest extends ModelTestCase ); } - /** * @test - * + * * @dataProvider provideSensitiveAttributes */ public function test_sensitive_attributes_are_stored_encrypted(string $attribute) @@ -64,20 +62,20 @@ class TwoFAccountModelTest extends ModelTestCase { return [ [ - 'legacy_uri' + 'legacy_uri', ], [ - 'secret' + 'secret', ], [ - 'account' + 'account', ], ]; } /** * @test - * + * * @dataProvider provideSensitiveAttributes */ public function test_sensitive_attributes_are_returned_clear(string $attribute) @@ -93,10 +91,9 @@ class TwoFAccountModelTest extends ModelTestCase $this->assertEquals($twofaccount->getAttributes()[$attribute], $twofaccount->$attribute); } - /** * @test - * + * * @dataProvider provideSensitiveAttributes */ public function test_indecipherable_attributes_returns_masked_value(string $attribute) @@ -114,4 +111,4 @@ class TwoFAccountModelTest extends ModelTestCase $this->assertEquals(__('errors.indecipherable'), $twofaccount->$attribute); } -} \ No newline at end of file +} diff --git a/tests/Unit/UserModelTest.php b/tests/Unit/UserModelTest.php index 1d3c3809..dd93f7c9 100644 --- a/tests/Unit/UserModelTest.php +++ b/tests/Unit/UserModelTest.php @@ -10,7 +10,6 @@ use Tests\ModelTestCase; */ class UserModelTest extends ModelTestCase { - /** * @test */ @@ -36,4 +35,4 @@ class UserModelTest extends ModelTestCase $this->assertEquals(strtolower('UPPERCASE@example.COM'), $user->email); } -} \ No newline at end of file +}