Automatic checks of authentication / instance publicity. Definition of missing OAuth...
[akkoma] / lib / pleroma / web / twitter_api / 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.Plugs.OAuthScopesPlug
10 alias Pleroma.User
11 alias Pleroma.Web.OAuth.Token
12 alias Pleroma.Web.TwitterAPI.TokenView
13
14 require Logger
15
16 plug(
17 OAuthScopesPlug,
18 %{scopes: ["write:notifications"]} when action == :mark_notifications_as_read
19 )
20
21 plug(:skip_plug, OAuthScopesPlug when action in [:oauth_tokens, :revoke_token])
22
23 action_fallback(:errors)
24
25 def confirm_email(conn, %{"user_id" => uid, "token" => token}) do
26 with %User{} = user <- User.get_cached_by_id(uid),
27 true <- user.local and user.confirmation_pending and user.confirmation_token == token,
28 {:ok, _} <-
29 user
30 |> User.confirmation_changeset(need_confirmation: false)
31 |> User.update_and_set_cache() do
32 redirect(conn, to: "/")
33 end
34 end
35
36 def oauth_tokens(%{assigns: %{user: user}} = conn, _params) do
37 with oauth_tokens <- Token.get_user_tokens(user) do
38 conn
39 |> put_view(TokenView)
40 |> render("index.json", %{tokens: oauth_tokens})
41 end
42 end
43
44 def revoke_token(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
45 Token.delete_user_token(user, id)
46
47 json_reply(conn, 201, "")
48 end
49
50 def errors(conn, {:param_cast, _}) do
51 conn
52 |> put_status(400)
53 |> json("Invalid parameters")
54 end
55
56 def errors(conn, _) do
57 conn
58 |> put_status(500)
59 |> json("Something went wrong")
60 end
61
62 defp json_reply(conn, status, json) do
63 conn
64 |> put_resp_content_type("application/json")
65 |> send_resp(status, json)
66 end
67
68 def mark_notifications_as_read(
69 %{assigns: %{user: user}} = conn,
70 %{"latest_id" => latest_id} = params
71 ) do
72 Notification.set_read_up_to(user, latest_id)
73
74 notifications = Notification.for_user(user, params)
75
76 conn
77 # XXX: This is a hack because pleroma-fe still uses that API.
78 |> put_view(Pleroma.Web.MastodonAPI.NotificationView)
79 |> render("index.json", %{notifications: notifications, for: user})
80 end
81
82 def mark_notifications_as_read(%{assigns: %{user: _user}} = conn, _) do
83 bad_request_reply(conn, "You need to specify latest_id")
84 end
85
86 defp bad_request_reply(conn, error_message) do
87 json = error_json(conn, error_message)
88 json_reply(conn, 400, json)
89 end
90
91 defp error_json(conn, error_message) do
92 %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
93 end
94 end