Merge branch 'develop' into stable
[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.User
9 alias Pleroma.Web.OAuth.Token
10 alias Pleroma.Web.Plugs.OAuthScopesPlug
11 alias Pleroma.Web.TwitterAPI.TokenView
12
13 require Logger
14
15 plug(:skip_auth when action == :confirm_email)
16 plug(:skip_plug, OAuthScopesPlug when action in [:oauth_tokens, :revoke_token])
17
18 action_fallback(:errors)
19
20 def confirm_email(conn, %{"user_id" => uid, "token" => token}) do
21 case User.get_cached_by_id(uid) do
22 %User{local: true, is_confirmed: false, confirmation_token: ^token} = user ->
23 case User.confirm(user) do
24 {:ok, _} ->
25 redirect(conn, to: "/")
26
27 {:error, _} ->
28 json_reply(conn, 400, "Unable to confirm")
29 end
30
31 %User{is_confirmed: true} ->
32 json_reply(conn, 400, "Already verified email")
33
34 _ ->
35 json_reply(conn, 400, "Couldn't verify email")
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 end