TwoFAccountController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. namespace App\Api\v1\Controllers;
  3. use App\Api\v1\Requests\TwoFAccountBatchRequest;
  4. use App\Api\v1\Requests\TwoFAccountDynamicRequest;
  5. use App\Api\v1\Requests\TwoFAccountExportRequest;
  6. use App\Api\v1\Requests\TwoFAccountImportRequest;
  7. use App\Api\v1\Requests\TwoFAccountIndexRequest;
  8. use App\Api\v1\Requests\TwoFAccountReorderRequest;
  9. use App\Api\v1\Requests\TwoFAccountStoreRequest;
  10. use App\Api\v1\Requests\TwoFAccountUpdateRequest;
  11. use App\Api\v1\Requests\TwoFAccountUriRequest;
  12. use App\Api\v1\Resources\TwoFAccountCollection;
  13. use App\Api\v1\Resources\TwoFAccountExportCollection;
  14. use App\Api\v1\Resources\TwoFAccountReadResource;
  15. use App\Api\v1\Resources\TwoFAccountStoreResource;
  16. use App\Facades\Groups;
  17. use App\Facades\TwoFAccounts;
  18. use App\Helpers\Helpers;
  19. use App\Http\Controllers\Controller;
  20. use App\Models\TwoFAccount;
  21. use App\Models\User;
  22. use Illuminate\Http\Request;
  23. use Illuminate\Support\Arr;
  24. class TwoFAccountController extends Controller
  25. {
  26. /**
  27. * List all resources
  28. *
  29. * @return \App\Api\v1\Resources\TwoFAccountCollection
  30. */
  31. public function index(TwoFAccountIndexRequest $request)
  32. {
  33. // Quick fix for #176
  34. if (config('auth.defaults.guard') === 'reverse-proxy-guard' && User::count() === 1) {
  35. if (TwoFAccount::orphans()->exists()) {
  36. $twofaccounts = TwoFAccount::orphans()->get();
  37. TwoFAccounts::setUser($twofaccounts, $request->user());
  38. }
  39. }
  40. $validated = $request->validated();
  41. return Arr::has($validated, 'ids')
  42. ? new TwoFAccountCollection($request->user()->twofaccounts()->whereIn('id', Helpers::commaSeparatedToArray($validated['ids']))->get()->sortBy('order_column'))
  43. : new TwoFAccountCollection($request->user()->twofaccounts->sortBy('order_column'));
  44. }
  45. /**
  46. * Display a 2FA account
  47. *
  48. * @return \App\Api\v1\Resources\TwoFAccountReadResource
  49. */
  50. public function show(TwoFAccount $twofaccount)
  51. {
  52. $this->authorize('view', $twofaccount);
  53. // $icon = $twofaccount->icon;
  54. // $iconRes = $twofaccount->icon()->get();
  55. return new TwoFAccountReadResource($twofaccount);
  56. }
  57. /**
  58. * Store a new 2FA account
  59. *
  60. * @return \Illuminate\Http\JsonResponse
  61. */
  62. public function store(TwoFAccountDynamicRequest $request)
  63. {
  64. $this->authorize('create', TwoFAccount::class);
  65. // Two possible cases :
  66. // - The most common case, an URI is provided by the QuickForm, thanks to a QR code live scan or file upload
  67. // -> We use that URI to define the account
  68. // - The advanced form has been used and all individual parameters
  69. // -> We use the parameters array to define the account
  70. $validated = $request->validated();
  71. $twofaccount = new TwoFAccount;
  72. if (Arr::has($validated, 'uri')) {
  73. $twofaccount->fillWithURI($validated['uri'], Arr::get($validated, 'custom_otp') === TwoFAccount::STEAM_TOTP);
  74. } else {
  75. $twofaccount->fillWithOtpParameters($validated);
  76. }
  77. $request->user()->twofaccounts()->save($twofaccount);
  78. // Possible group association
  79. Groups::assign($twofaccount->id, $request->user(), Arr::get($validated, 'group_id', null));
  80. return (new TwoFAccountReadResource($twofaccount->refresh()))
  81. ->response()
  82. ->setStatusCode(201);
  83. }
  84. /**
  85. * Update a 2FA account
  86. *
  87. * @return \Illuminate\Http\JsonResponse
  88. */
  89. public function update(TwoFAccountUpdateRequest $request, TwoFAccount $twofaccount)
  90. {
  91. $this->authorize('update', $twofaccount);
  92. $validated = $request->validated();
  93. $twofaccount->fillWithOtpParameters($validated);
  94. $request->user()->twofaccounts()->save($twofaccount);
  95. // Possible group change
  96. $groupId = Arr::get($validated, 'group_id', null);
  97. if ($twofaccount->group_id != $groupId) {
  98. if ((int) $groupId === 0) {
  99. TwoFAccounts::withdraw($twofaccount->id);
  100. } else {
  101. Groups::assign($twofaccount->id, $request->user(), $groupId);
  102. }
  103. $twofaccount->refresh();
  104. }
  105. return (new TwoFAccountReadResource($twofaccount))
  106. ->response()
  107. ->setStatusCode(200);
  108. }
  109. /**
  110. * Convert a migration resource to a valid TwoFAccounts collection
  111. *
  112. * @return \Illuminate\Http\JsonResponse|\App\Api\v1\Resources\TwoFAccountCollection
  113. */
  114. public function migrate(TwoFAccountImportRequest $request)
  115. {
  116. $validated = $request->validated();
  117. if (Arr::has($validated, 'file')) {
  118. $migrationResource = $request->file('file');
  119. return $migrationResource instanceof \Illuminate\Http\UploadedFile
  120. ? new TwoFAccountCollection(TwoFAccounts::migrate($migrationResource->get()))
  121. : response()->json(['message' => __('errors.file_upload_failed')], 500);
  122. } else {
  123. return new TwoFAccountCollection(TwoFAccounts::migrate($request->payload));
  124. }
  125. }
  126. /**
  127. * Save 2FA accounts order
  128. *
  129. * @return \Illuminate\Http\JsonResponse
  130. */
  131. public function reorder(TwoFAccountReorderRequest $request)
  132. {
  133. $validated = $request->validated();
  134. $twofaccounts = TwoFAccount::whereIn('id', $validated['orderedIds'])->get();
  135. $this->authorize('updateEach', [new TwoFAccount, $twofaccounts]);
  136. TwoFAccount::setNewOrder($validated['orderedIds']);
  137. $orderedIds = $request->user()->twofaccounts->sortBy('order_column')->pluck('id');
  138. return response()->json([
  139. 'message' => 'order saved',
  140. 'orderedIds' => $orderedIds,
  141. ], 200);
  142. }
  143. /**
  144. * Preview account using an uri, without any db moves
  145. *
  146. * @return \App\Api\v1\Resources\TwoFAccountStoreResource
  147. */
  148. public function preview(TwoFAccountUriRequest $request)
  149. {
  150. $twofaccount = new TwoFAccount;
  151. $twofaccount->fillWithURI($request->uri, $request->custom_otp === TwoFAccount::STEAM_TOTP);
  152. return new TwoFAccountStoreResource($twofaccount);
  153. }
  154. /**
  155. * Export accounts
  156. *
  157. * @return TwoFAccountExportCollection|\Illuminate\Http\JsonResponse
  158. */
  159. public function export(TwoFAccountExportRequest $request)
  160. {
  161. $validated = $request->validated();
  162. if ($this->tooManyIds($validated['ids'])) {
  163. return response()->json([
  164. 'message' => 'bad request',
  165. 'reason' => [__('errors.too_many_ids')],
  166. ], 400);
  167. }
  168. $twofaccounts = TwoFAccounts::export($validated['ids']);
  169. $this->authorize('viewEach', [new TwoFAccount, $twofaccounts]);
  170. return new TwoFAccountExportCollection($twofaccounts);
  171. }
  172. /**
  173. * Get a One-Time Password
  174. *
  175. * @param string|null $id
  176. * @return \Illuminate\Http\JsonResponse
  177. */
  178. public function otp(Request $request, $id = null)
  179. {
  180. $inputs = $request->all();
  181. // The request input is the ID of an existing account
  182. if ($id) {
  183. $twofaccount = TwoFAccount::findOrFail((int) $id);
  184. $this->authorize('view', $twofaccount);
  185. }
  186. // The request input is an uri
  187. elseif ($request->has('uri')) {
  188. // return 404 if uri is provided with any parameter other than otp_type
  189. if ((count($inputs) == 2 && $request->missing('custom_otp')) || count($inputs) > 2) {
  190. return response()->json([
  191. 'message' => 'bad request',
  192. 'reason' => ['uri' => __('validation.onlyCustomOtpWithUri')],
  193. ], 400);
  194. } else {
  195. $validatedData = $request->validate((new TwoFAccountUriRequest)->rules());
  196. $twofaccount = new TwoFAccount;
  197. $twofaccount->fillWithURI($validatedData['uri'], Arr::get($validatedData, 'custom_otp') === TwoFAccount::STEAM_TOTP, true);
  198. }
  199. }
  200. // The request inputs should define an account
  201. else {
  202. $validatedData = $request->validate((new TwoFAccountStoreRequest)->rules());
  203. $twofaccount = new TwoFAccount;
  204. $twofaccount->fillWithOtpParameters($validatedData, true);
  205. }
  206. return response()->json($twofaccount->getOTP(), 200);
  207. }
  208. /**
  209. * A simple and light method to get the account count.
  210. *
  211. * @return \Illuminate\Http\JsonResponse
  212. */
  213. public function count(Request $request)
  214. {
  215. return response()->json(['count' => $request->user()->twofaccounts->count()], 200);
  216. }
  217. /**
  218. * Withdraw one or more accounts from their group
  219. *
  220. * @return \Illuminate\Http\JsonResponse
  221. */
  222. public function withdraw(TwoFAccountBatchRequest $request)
  223. {
  224. $validated = $request->validated();
  225. if ($this->tooManyIds($validated['ids'])) {
  226. return response()->json([
  227. 'message' => 'bad request',
  228. 'reason' => [__('errors.too_many_ids')],
  229. ], 400);
  230. }
  231. $ids = Helpers::commaSeparatedToArray($validated['ids']);
  232. $twofaccounts = TwoFAccount::whereIn('id', $ids)->get();
  233. $this->authorize('updateEach', [new TwoFAccount, $twofaccounts]);
  234. TwoFAccounts::withdraw($ids);
  235. return response()->json(['message' => 'accounts withdrawn'], 200);
  236. }
  237. /**
  238. * Remove the specified resource from storage.
  239. *
  240. * @return \Illuminate\Http\JsonResponse
  241. */
  242. public function destroy(TwoFAccount $twofaccount)
  243. {
  244. $this->authorize('delete', $twofaccount);
  245. $twofaccount->delete();
  246. return response()->json(null, 204);
  247. }
  248. /**
  249. * Remove the specified resources from storage.
  250. *
  251. * @return \Illuminate\Http\JsonResponse
  252. */
  253. public function batchDestroy(TwoFAccountBatchRequest $request)
  254. {
  255. $validated = $request->validated();
  256. if ($this->tooManyIds($validated['ids'])) {
  257. return response()->json([
  258. 'message' => 'bad request',
  259. 'reason' => [__('errors.too_many_ids')],
  260. ], 400);
  261. }
  262. $ids = Helpers::commaSeparatedToArray($validated['ids']);
  263. $twofaccounts = TwoFAccount::whereIn('id', $ids)->get();
  264. $this->authorize('deleteEach', [new TwoFAccount, $twofaccounts]);
  265. TwoFAccounts::delete($validated['ids']);
  266. return response()->json(null, 204);
  267. }
  268. /**
  269. * Checks ids length
  270. *
  271. * @param string $ids comma-separated ids
  272. * @return bool whether or not the number of ids is acceptable
  273. */
  274. private function tooManyIds(string $ids) : bool
  275. {
  276. $arIds = explode(',', $ids, 100);
  277. $nb = count($arIds);
  278. return $nb > 99 ? true : false;
  279. }
  280. }