Merge branch 'fixes_2034_reports_should_send_a_notification_to_admins' into 'develop'
[akkoma] / lib / pleroma / web / twitter_api / controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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.confirmation_pending and user.confirmation_token == token,
34 {:ok, _} <-
35 user
36 |> User.confirmation_changeset(need_confirmation: false)
37 |> User.update_and_set_cache() do
38 redirect(conn, to: "/")
39 end
40 end
41
42 def oauth_tokens(%{assigns: %{user: user}} = conn, _params) do
43 with oauth_tokens <- Token.get_user_tokens(user) do
44 conn
45 |> put_view(TokenView)
46 |> render("index.json", %{tokens: oauth_tokens})
47 end
48 end
49
50 def revoke_token(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
51 Token.delete_user_token(user, id)
52
53 json_reply(conn, 201, "")
54 end
55
56 defp errors(conn, {:param_cast, _}) do
57 conn
58 |> put_status(400)
59 |> json("Invalid parameters")
60 end
61
62 defp errors(conn, _) do
63 conn
64 |> put_status(500)
65 |> json("Something went wrong")
66 end
67
68 defp json_reply(conn, status, json) do
69 conn
70 |> put_resp_content_type("application/json")
71 |> send_resp(status, json)
72 end
73
74 def mark_notifications_as_read(
75 %{assigns: %{user: user}} = conn,
76 %{"latest_id" => latest_id} = params
77 ) do
78 Notification.set_read_up_to(user, latest_id)
79
80 notifications = Notification.for_user(user, params)
81
82 conn
83 # XXX: This is a hack because pleroma-fe still uses that API.
84 |> put_view(Pleroma.Web.MastodonAPI.NotificationView)
85 |> render("index.json", %{notifications: notifications, for: user})
86 end
87
88 def mark_notifications_as_read(%{assigns: %{user: _user}} = conn, _) do
89 bad_request_reply(conn, "You need to specify latest_id")
90 end
91
92 defp bad_request_reply(conn, error_message) do
93 json = error_json(conn, error_message)
94 json_reply(conn, 400, json)
95 end
96
97 defp error_json(conn, error_message) do
98 %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
99 end
100 end