TwoFAccountController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. // if ($request->has('withOtp')) {
  41. // $request->merge(['at' => time()]);
  42. // }
  43. return Arr::has($validated, 'ids')
  44. ? new TwoFAccountCollection($request->user()->twofaccounts()->whereIn('id', Helpers::commaSeparatedToArray($validated['ids']))->get()->sortBy('order_column'))
  45. : new TwoFAccountCollection($request->user()->twofaccounts->sortBy('order_column'));
  46. }
  47. /**
  48. * Display a 2FA account
  49. *
  50. * @return \App\Api\v1\Resources\TwoFAccountReadResource
  51. */
  52. public function show(TwoFAccount $twofaccount)
  53. {
  54. $this->authorize('view', $twofaccount);
  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());
  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. return (new TwoFAccountReadResource($twofaccount))
  96. ->response()
  97. ->setStatusCode(200);
  98. }
  99. /**
  100. * Convert a migration resource to a valid TwoFAccounts collection
  101. *
  102. * @return \Illuminate\Http\JsonResponse|\App\Api\v1\Resources\TwoFAccountCollection
  103. */
  104. public function migrate(TwoFAccountImportRequest $request)
  105. {
  106. $validated = $request->validated();
  107. if (Arr::has($validated, 'file')) {
  108. $migrationResource = $request->file('file');
  109. return $migrationResource instanceof \Illuminate\Http\UploadedFile
  110. ? new TwoFAccountCollection(TwoFAccounts::migrate($migrationResource->get()))
  111. : response()->json(['message' => __('errors.file_upload_failed')], 500);
  112. } else {
  113. return new TwoFAccountCollection(TwoFAccounts::migrate($request->payload));
  114. }
  115. }
  116. /**
  117. * Save 2FA accounts order
  118. *
  119. * @return \Illuminate\Http\JsonResponse
  120. */
  121. public function reorder(TwoFAccountReorderRequest $request)
  122. {
  123. $validated = $request->validated();
  124. $twofaccounts = TwoFAccount::whereIn('id', $validated['orderedIds'])->get();
  125. $this->authorize('updateEach', [new TwoFAccount(), $twofaccounts]);
  126. TwoFAccount::setNewOrder($validated['orderedIds']);
  127. $orderedIds = $request->user()->twofaccounts->sortBy('order_column')->pluck('id');
  128. return response()->json([
  129. 'message' => 'order saved',
  130. 'orderedIds' => $orderedIds,
  131. ], 200);
  132. }
  133. /**
  134. * Preview account using an uri, without any db moves
  135. *
  136. * @return \App\Api\v1\Resources\TwoFAccountStoreResource
  137. */
  138. public function preview(TwoFAccountUriRequest $request)
  139. {
  140. $twofaccount = new TwoFAccount;
  141. $twofaccount->fillWithURI($request->uri, $request->custom_otp === TwoFAccount::STEAM_TOTP);
  142. return new TwoFAccountStoreResource($twofaccount);
  143. }
  144. /**
  145. * Export accounts
  146. *
  147. * @return TwoFAccountExportCollection|\Illuminate\Http\JsonResponse
  148. */
  149. public function export(TwoFAccountBatchRequest $request)
  150. {
  151. $validated = $request->validated();
  152. if ($this->tooManyIds($validated['ids'])) {
  153. return response()->json([
  154. 'message' => 'bad request',
  155. 'reason' => [__('errors.too_many_ids')],
  156. ], 400);
  157. }
  158. $twofaccounts = TwoFAccounts::export($validated['ids']);
  159. $this->authorize('viewEach', [new TwoFAccount(), $twofaccounts]);
  160. return new TwoFAccountExportCollection($twofaccounts);
  161. }
  162. /**
  163. * Get a One-Time Password
  164. *
  165. * @param string|null $id
  166. * @return \Illuminate\Http\JsonResponse
  167. */
  168. public function otp(Request $request, $id = null)
  169. {
  170. $inputs = $request->all();
  171. // The request input is the ID of an existing account
  172. if ($id) {
  173. $twofaccount = TwoFAccount::findOrFail((int) $id);
  174. $this->authorize('view', $twofaccount);
  175. }
  176. // The request input is an uri
  177. elseif ($request->has('uri')) {
  178. // return 404 if uri is provided with any parameter other than otp_type
  179. if ((count($inputs) == 2 && $request->missing('custom_otp')) || count($inputs) > 2) {
  180. return response()->json([
  181. 'message' => 'bad request',
  182. 'reason' => ['uri' => __('validation.onlyCustomOtpWithUri')],
  183. ], 400);
  184. } else {
  185. $validatedData = $request->validate((new TwoFAccountUriRequest)->rules());
  186. $twofaccount = new TwoFAccount;
  187. $twofaccount->fillWithURI($validatedData['uri'], Arr::get($validatedData, 'custom_otp') === TwoFAccount::STEAM_TOTP, true);
  188. }
  189. }
  190. // The request inputs should define an account
  191. else {
  192. $validatedData = $request->validate((new TwoFAccountStoreRequest)->rules());
  193. $twofaccount = new TwoFAccount();
  194. $twofaccount->fillWithOtpParameters($validatedData, true);
  195. }
  196. return response()->json($twofaccount->getOTP(), 200);
  197. }
  198. /**
  199. * A simple and light method to get the account count.
  200. *
  201. * @return \Illuminate\Http\JsonResponse
  202. */
  203. public function count(Request $request)
  204. {
  205. return response()->json(['count' => $request->user()->twofaccounts->count()], 200);
  206. }
  207. /**
  208. * Withdraw one or more accounts from their group
  209. *
  210. * @return \Illuminate\Http\JsonResponse
  211. */
  212. public function withdraw(TwoFAccountBatchRequest $request)
  213. {
  214. $validated = $request->validated();
  215. if ($this->tooManyIds($validated['ids'])) {
  216. return response()->json([
  217. 'message' => 'bad request',
  218. 'reason' => [__('errors.too_many_ids')],
  219. ], 400);
  220. }
  221. $ids = Helpers::commaSeparatedToArray($validated['ids']);
  222. $twofaccounts = TwoFAccount::whereIn('id', $ids)->get();
  223. $this->authorize('updateEach', [new TwoFAccount(), $twofaccounts]);
  224. TwoFAccounts::withdraw($ids);
  225. return response()->json(['message' => 'accounts withdrawn'], 200);
  226. }
  227. /**
  228. * Remove the specified resource from storage.
  229. *
  230. * @return \Illuminate\Http\JsonResponse
  231. */
  232. public function destroy(TwoFAccount $twofaccount)
  233. {
  234. $this->authorize('delete', $twofaccount);
  235. $twofaccount->delete();
  236. return response()->json(null, 204);
  237. }
  238. /**
  239. * Remove the specified resources from storage.
  240. *
  241. * @return \Illuminate\Http\JsonResponse
  242. */
  243. public function batchDestroy(TwoFAccountBatchRequest $request)
  244. {
  245. $validated = $request->validated();
  246. if ($this->tooManyIds($validated['ids'])) {
  247. return response()->json([
  248. 'message' => 'bad request',
  249. 'reason' => [__('errors.too_many_ids')],
  250. ], 400);
  251. }
  252. $ids = Helpers::commaSeparatedToArray($validated['ids']);
  253. $twofaccounts = TwoFAccount::whereIn('id', $ids)->get();
  254. $this->authorize('deleteEach', [new TwoFAccount(), $twofaccounts]);
  255. TwoFAccounts::delete($validated['ids']);
  256. return response()->json(null, 204);
  257. }
  258. /**
  259. * Checks ids length
  260. *
  261. * @param string $ids comma-separated ids
  262. * @return bool whether or not the number of ids is acceptable
  263. */
  264. private function tooManyIds(string $ids) : bool
  265. {
  266. $arIds = explode(',', $ids, 100);
  267. $nb = count($arIds);
  268. return $nb > 99 ? true : false;
  269. }
  270. }