Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / mastodon_api / controllers / auth_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.MastodonAPI.AuthController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.User
9 alias Pleroma.Web.OAuth.App
10 alias Pleroma.Web.OAuth.Authorization
11 alias Pleroma.Web.OAuth.Token
12 alias Pleroma.Web.TwitterAPI.TwitterAPI
13
14 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
15
16 plug(Pleroma.Plugs.RateLimiter, [name: :password_reset] when action == :password_reset)
17
18 @local_mastodon_name "Mastodon-Local"
19
20 @doc "GET /web/login"
21 def login(%{assigns: %{user: %User{}}} = conn, _params) do
22 redirect(conn, to: local_mastodon_root_path(conn))
23 end
24
25 @doc "Local Mastodon FE login init action"
26 def login(conn, %{"code" => auth_token}) do
27 with {:ok, app} <- get_or_make_app(),
28 {:ok, auth} <- Authorization.get_by_token(app, auth_token),
29 {:ok, token} <- Token.exchange_token(app, auth) do
30 conn
31 |> put_session(:oauth_token, token.token)
32 |> redirect(to: local_mastodon_root_path(conn))
33 end
34 end
35
36 @doc "Local Mastodon FE callback action"
37 def login(conn, _) do
38 with {:ok, app} <- get_or_make_app() do
39 path =
40 o_auth_path(conn, :authorize,
41 response_type: "code",
42 client_id: app.client_id,
43 redirect_uri: ".",
44 scope: Enum.join(app.scopes, " ")
45 )
46
47 redirect(conn, to: path)
48 end
49 end
50
51 @doc "DELETE /auth/sign_out"
52 def logout(conn, _) do
53 conn
54 |> clear_session
55 |> redirect(to: "/")
56 end
57
58 @doc "POST /auth/password"
59 def password_reset(conn, params) do
60 nickname_or_email = params["email"] || params["nickname"]
61
62 with {:ok, _} <- TwitterAPI.password_reset(nickname_or_email) do
63 conn
64 |> put_status(:no_content)
65 |> json("")
66 else
67 {:error, "unknown user"} ->
68 send_resp(conn, :not_found, "")
69
70 {:error, _} ->
71 send_resp(conn, :bad_request, "")
72 end
73 end
74
75 defp local_mastodon_root_path(conn) do
76 case get_session(conn, :return_to) do
77 nil ->
78 masto_fe_path(conn, :index, ["getting-started"])
79
80 return_to ->
81 delete_session(conn, :return_to)
82 return_to
83 end
84 end
85
86 @spec get_or_make_app() :: {:ok, App.t()} | {:error, Ecto.Changeset.t()}
87 defp get_or_make_app do
88 %{client_name: @local_mastodon_name, redirect_uris: "."}
89 |> App.get_or_make(["read", "write", "follow", "push", "admin"])
90 end
91 end