TwoFAccountController.php 11 KB

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