077bfa70d5661db507bcfd106abd5e9460540a8f
[akkoma] / lib / pleroma / web / twitter_api / controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.TwitterAPI.Controller do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Notification
9 alias Pleroma.User
10 alias Pleroma.Web.OAuth.Token
11 alias Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug
12 alias Pleroma.Web.Plugs.OAuthScopesPlug
13 alias Pleroma.Web.TwitterAPI.TokenView
14
15 require Logger
16
17 plug(
18 OAuthScopesPlug,
19 %{scopes: ["write:notifications"]} when action == :mark_notifications_as_read
20 )
21
22 plug(
23 :skip_plug,
24 [OAuthScopesPlug, EnsurePublicOrAuthenticatedPlug] when action == :confirm_email
25 )
26
27 plug(:skip_plug, OAuthScopesPlug when action in [:oauth_tokens, :revoke_token])
28
29 action_fallback(:errors)
30
31 def confirm_email(conn, %{"user_id" => uid, "token" => token}) do
32 with %User{} = user <- User.get_cached_by_id(uid),
33 true <- user.local and !user.is_confirmed and user.confirmation_token == token,
34 {:ok, _} <- User.confirm(user) do
35 redirect(conn, to: "/")
36 end
37 end
38
39 def oauth_tokens(%{assigns: %{user: user}} = conn, _params) do
40 with oauth_tokens <- Token.get_user_tokens(user) do
41 conn
42 |> put_view(TokenView)
43 |> render("index.json", %{tokens: oauth_tokens})
44 end
45 end
46
47 def revoke_token(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
48 Token.delete_user_token(user, id)
49
50 json_reply(conn, 201, "")
51 end
52
53 defp errors(conn, {:param_cast, _}) do
54 conn
55 |> put_status(400)
56 |> json("Invalid parameters")
57 end
58
59 defp errors(conn, _) do
60 conn
61 |> put_status(500)
62 |> json("Something went wrong")
63 end
64
65 defp json_reply(conn, status, json) do
66 conn
67 |> put_resp_content_type("application/json")
68 |> send_resp(status, json)
69 end
70
71 def mark_notifications_as_read(
72 %{assigns: %{user: user}} = conn,
73 %{"latest_id" => latest_id} = params
74 ) do
75 Notification.set_read_up_to(user, latest_id)
76
77 notifications = Notification.for_user(user, params)
78
79 conn
80 # XXX: This is a hack because pleroma-fe still uses that API.
81 |> put_view(Pleroma.Web.MastodonAPI.NotificationView)
82 |> render("index.json", %{notifications: notifications, for: user})
83 end
84
85 def mark_notifications_as_read(%{assigns: %{user: _user}} = conn, _) do
86 bad_request_reply(conn, "You need to specify latest_id")
87 end
88
89 defp bad_request_reply(conn, error_message) do
90 json = error_json(conn, error_message)
91 json_reply(conn, 400, json)
92 end
93
94 defp error_json(conn, error_message) do
95 %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
96 end
97 end