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