ApiV1Dot1Controller.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Cache;
  4. use DB;
  5. use App\Http\Controllers\Controller;
  6. use Illuminate\Http\Request;
  7. use League\Fractal;
  8. use League\Fractal\Serializer\ArraySerializer;
  9. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  10. use App\AccountLog;
  11. use App\EmailVerification;
  12. use App\Status;
  13. use App\Report;
  14. use App\Profile;
  15. use App\Services\AccountService;
  16. use App\Services\StatusService;
  17. use App\Services\ProfileStatusService;
  18. use Jenssegers\Agent\Agent;
  19. use Mail;
  20. use App\Mail\PasswordChange;
  21. class ApiV1Dot1Controller extends Controller
  22. {
  23. protected $fractal;
  24. public function __construct()
  25. {
  26. $this->fractal = new Fractal\Manager();
  27. $this->fractal->setSerializer(new ArraySerializer());
  28. }
  29. public function json($res, $code = 200, $headers = [])
  30. {
  31. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  32. }
  33. public function error($msg, $code = 400, $extra = [], $headers = [])
  34. {
  35. $res = [
  36. "msg" => $msg,
  37. "code" => $code
  38. ];
  39. return response()->json(array_merge($res, $extra), $code, $headers, JSON_UNESCAPED_SLASHES);
  40. }
  41. public function report(Request $request)
  42. {
  43. $user = $request->user();
  44. abort_if(!$user, 403);
  45. abort_if($user->status != null, 403);
  46. $report_type = $request->input('report_type');
  47. $object_id = $request->input('object_id');
  48. $object_type = $request->input('object_type');
  49. $types = [
  50. 'spam',
  51. 'sensitive',
  52. 'abusive',
  53. 'underage',
  54. 'violence',
  55. 'copyright',
  56. 'impersonation',
  57. 'scam',
  58. 'terrorism'
  59. ];
  60. if (!$report_type || !$object_id || !$object_type) {
  61. return $this->error("Invalid or missing parameters", 400, ["error_code" => "ERROR_INVALID_PARAMS"]);
  62. }
  63. if (!in_array($report_type, $types)) {
  64. return $this->error("Invalid report type", 400, ["error_code" => "ERROR_TYPE_INVALID"]);
  65. }
  66. if ($object_type === "user" && $object_id == $user->profile_id) {
  67. return $this->error("Cannot self report", 400, ["error_code" => "ERROR_NO_SELF_REPORTS"]);
  68. }
  69. $rpid = null;
  70. switch ($object_type) {
  71. case 'post':
  72. $object = Status::find($object_id);
  73. if (!$object) {
  74. return $this->error("Invalid object id", 400, ["error_code" => "ERROR_INVALID_OBJECT_ID"]);
  75. }
  76. $object_type = 'App\Status';
  77. $exists = Report::whereUserId($user->id)
  78. ->whereObjectId($object->id)
  79. ->whereObjectType('App\Status')
  80. ->count();
  81. $rpid = $object->profile_id;
  82. break;
  83. case 'user':
  84. $object = Profile::find($object_id);
  85. if (!$object) {
  86. return $this->error("Invalid object id", 400, ["error_code" => "ERROR_INVALID_OBJECT_ID"]);
  87. }
  88. $object_type = 'App\Profile';
  89. $exists = Report::whereUserId($user->id)
  90. ->whereObjectId($object->id)
  91. ->whereObjectType('App\Profile')
  92. ->count();
  93. $rpid = $object->id;
  94. break;
  95. default:
  96. return $this->error("Invalid report type", 400, ["error_code" => "ERROR_REPORT_OBJECT_TYPE_INVALID"]);
  97. break;
  98. }
  99. if ($exists !== 0) {
  100. return $this->error("Duplicate report", 400, ["error_code" => "ERROR_REPORT_DUPLICATE"]);
  101. }
  102. if ($object->profile_id == $user->profile_id) {
  103. return $this->error("Cannot self report", 400, ["error_code" => "ERROR_NO_SELF_REPORTS"]);
  104. }
  105. $report = new Report;
  106. $report->profile_id = $user->profile_id;
  107. $report->user_id = $user->id;
  108. $report->object_id = $object->id;
  109. $report->object_type = $object_type;
  110. $report->reported_profile_id = $rpid;
  111. $report->type = $report_type;
  112. $report->save();
  113. $res = [
  114. "msg" => "Successfully sent report",
  115. "code" => 200
  116. ];
  117. return $this->json($res);
  118. }
  119. /**
  120. * DELETE /api/v1.1/accounts/avatar
  121. *
  122. * @return \App\Transformer\Api\AccountTransformer
  123. */
  124. public function deleteAvatar(Request $request)
  125. {
  126. $user = $request->user();
  127. abort_if(!$user, 403);
  128. abort_if($user->status != null, 403);
  129. $avatar = $user->profile->avatar;
  130. if( $avatar->media_path == 'public/avatars/default.png' ||
  131. $avatar->media_path == 'public/avatars/default.jpg'
  132. ) {
  133. return AccountService::get($user->profile_id);
  134. }
  135. if(is_file(storage_path('app/' . $avatar->media_path))) {
  136. @unlink(storage_path('app/' . $avatar->media_path));
  137. }
  138. $avatar->media_path = 'public/avatars/default.jpg';
  139. $avatar->change_count = $avatar->change_count + 1;
  140. $avatar->save();
  141. Cache::forget('avatar:' . $user->profile_id);
  142. Cache::forget("avatar:{$user->profile_id}");
  143. Cache::forget('user:account:id:'.$user->id);
  144. AccountService::del($user->profile_id);
  145. return AccountService::get($user->profile_id);
  146. }
  147. /**
  148. * GET /api/v1.1/accounts/{id}/posts
  149. *
  150. * @return \App\Transformer\Api\StatusTransformer
  151. */
  152. public function accountPosts(Request $request, $id)
  153. {
  154. $user = $request->user();
  155. abort_if(!$user, 403);
  156. abort_if($user->status != null, 403);
  157. $account = AccountService::get($id);
  158. if(!$account || $account['username'] !== $request->input('username')) {
  159. return $this->json([]);
  160. }
  161. $posts = ProfileStatusService::get($id);
  162. if(!$posts) {
  163. return $this->json([]);
  164. }
  165. $res = collect($posts)
  166. ->map(function($id) {
  167. return StatusService::get($id);
  168. })
  169. ->filter(function($post) {
  170. return $post && isset($post['account']);
  171. })
  172. ->toArray();
  173. return $this->json($res);
  174. }
  175. /**
  176. * POST /api/v1.1/accounts/change-password
  177. *
  178. * @return \App\Transformer\Api\AccountTransformer
  179. */
  180. public function accountChangePassword(Request $request)
  181. {
  182. $user = $request->user();
  183. abort_if(!$user, 403);
  184. abort_if($user->status != null, 403);
  185. $this->validate($request, [
  186. 'current_password' => 'bail|required|current_password',
  187. 'new_password' => 'required|min:' . config('pixelfed.min_password_length', 8),
  188. 'confirm_password' => 'required|same:new_password'
  189. ],[
  190. 'current_password' => 'The password you entered is incorrect'
  191. ]);
  192. $user->password = bcrypt($request->input('new_password'));
  193. $user->save();
  194. $log = new AccountLog;
  195. $log->user_id = $user->id;
  196. $log->item_id = $user->id;
  197. $log->item_type = 'App\User';
  198. $log->action = 'account.edit.password';
  199. $log->message = 'Password changed';
  200. $log->link = null;
  201. $log->ip_address = $request->ip();
  202. $log->user_agent = $request->userAgent();
  203. $log->save();
  204. Mail::to($request->user())->send(new PasswordChange($user));
  205. return $this->json(AccountService::get($user->profile_id));
  206. }
  207. /**
  208. * GET /api/v1.1/accounts/login-activity
  209. *
  210. * @return array
  211. */
  212. public function accountLoginActivity(Request $request)
  213. {
  214. $user = $request->user();
  215. abort_if(!$user, 403);
  216. abort_if($user->status != null, 403);
  217. $agent = new Agent();
  218. $currentIp = $request->ip();
  219. $activity = AccountLog::whereUserId($user->id)
  220. ->whereAction('auth.login')
  221. ->orderBy('created_at', 'desc')
  222. ->groupBy('ip_address')
  223. ->limit(10)
  224. ->get()
  225. ->map(function($item) use($agent, $currentIp) {
  226. $agent->setUserAgent($item->user_agent);
  227. return [
  228. 'id' => $item->id,
  229. 'action' => $item->action,
  230. 'ip' => $item->ip_address,
  231. 'ip_current' => $item->ip_address === $currentIp,
  232. 'is_mobile' => $agent->isMobile(),
  233. 'device' => $agent->device(),
  234. 'browser' => $agent->browser(),
  235. 'platform' => $agent->platform(),
  236. 'created_at' => $item->created_at->format('c')
  237. ];
  238. });
  239. return $this->json($activity);
  240. }
  241. /**
  242. * GET /api/v1.1/accounts/two-factor
  243. *
  244. * @return array
  245. */
  246. public function accountTwoFactor(Request $request)
  247. {
  248. $user = $request->user();
  249. abort_if(!$user, 403);
  250. abort_if($user->status != null, 403);
  251. $res = [
  252. 'active' => (bool) $user->{'2fa_enabled'},
  253. 'setup_at' => $user->{'2fa_setup_at'}
  254. ];
  255. return $this->json($res);
  256. }
  257. /**
  258. * GET /api/v1.1/accounts/emails-from-pixelfed
  259. *
  260. * @return array
  261. */
  262. public function accountEmailsFromPixelfed(Request $request)
  263. {
  264. $user = $request->user();
  265. abort_if(!$user, 403);
  266. abort_if($user->status != null, 403);
  267. $from = config('mail.from.address');
  268. $emailVerifications = EmailVerification::whereUserId($user->id)
  269. ->orderByDesc('id')
  270. ->where('created_at', '>', now()->subDays(14))
  271. ->limit(10)
  272. ->get()
  273. ->map(function($mail) use($user, $from) {
  274. return [
  275. 'type' => 'Email Verification',
  276. 'subject' => 'Confirm Email',
  277. 'to_address' => $user->email,
  278. 'from_address' => $from,
  279. 'created_at' => str_replace('@', 'at', $mail->created_at->format('M j, Y @ g:i:s A'))
  280. ];
  281. })
  282. ->toArray();
  283. $passwordResets = DB::table('password_resets')
  284. ->whereEmail($user->email)
  285. ->where('created_at', '>', now()->subDays(14))
  286. ->orderByDesc('created_at')
  287. ->limit(10)
  288. ->get()
  289. ->map(function($mail) use($user, $from) {
  290. return [
  291. 'type' => 'Password Reset',
  292. 'subject' => 'Reset Password Notification',
  293. 'to_address' => $user->email,
  294. 'from_address' => $from,
  295. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A'))
  296. ];
  297. })
  298. ->toArray();
  299. $passwordChanges = AccountLog::whereUserId($user->id)
  300. ->whereAction('account.edit.password')
  301. ->where('created_at', '>', now()->subDays(14))
  302. ->orderByDesc('created_at')
  303. ->limit(10)
  304. ->get()
  305. ->map(function($mail) use($user, $from) {
  306. return [
  307. 'type' => 'Password Change',
  308. 'subject' => 'Password Change',
  309. 'to_address' => $user->email,
  310. 'from_address' => $from,
  311. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A'))
  312. ];
  313. })
  314. ->toArray();
  315. $res = collect([])
  316. ->merge($emailVerifications)
  317. ->merge($passwordResets)
  318. ->merge($passwordChanges)
  319. ->sortByDesc('created_at')
  320. ->values();
  321. return $this->json($res);
  322. }
  323. /**
  324. * GET /api/v1.1/accounts/apps-and-applications
  325. *
  326. * @return array
  327. */
  328. public function accountApps(Request $request)
  329. {
  330. $user = $request->user();
  331. abort_if(!$user, 403);
  332. abort_if($user->status != null, 403);
  333. $res = $user->tokens->map(function($token, $key) {
  334. return [
  335. 'id' => $key + 1,
  336. 'did' => encrypt($token->id),
  337. 'name' => $token->name,
  338. 'scopes' => $token->scopes,
  339. 'revoked' => $token->revoked,
  340. 'created_at' => $token->created_at,
  341. 'expires_at' => $token->expires_at
  342. ];
  343. });
  344. return $this->json($res);
  345. }
  346. }