1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.AuthController do
6 use Pleroma.Web, :controller
9 alias Pleroma.Web.OAuth.App
10 alias Pleroma.Web.OAuth.Authorization
11 alias Pleroma.Web.OAuth.Token
12 alias Pleroma.Web.TwitterAPI.TwitterAPI
14 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
16 @local_mastodon_name "Mastodon-Local"
18 plug(Pleroma.Plugs.RateLimiter, :password_reset when action == :password_reset)
21 def login(%{assigns: %{user: %User{}}} = conn, _params) do
22 redirect(conn, to: local_mastodon_root_path(conn))
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
31 |> put_session(:oauth_token, token.token)
32 |> redirect(to: local_mastodon_root_path(conn))
36 @doc "Local Mastodon FE callback action"
38 with {:ok, app} <- get_or_make_app() do
40 o_auth_path(conn, :authorize,
41 response_type: "code",
42 client_id: app.client_id,
44 scope: Enum.join(app.scopes, " ")
47 redirect(conn, to: path)
51 @doc "DELETE /auth/sign_out"
52 def logout(conn, _) do
58 @doc "POST /auth/password"
59 def password_reset(conn, params) do
60 nickname_or_email = params["email"] || params["nickname"]
62 with {:ok, _} <- TwitterAPI.password_reset(nickname_or_email) do
64 |> put_status(:no_content)
67 {:error, "unknown user"} ->
68 send_resp(conn, :not_found, "")
71 send_resp(conn, :bad_request, "")
75 defp local_mastodon_root_path(conn) do
76 case get_session(conn, :return_to) do
78 masto_fe_path(conn, :index, ["getting-started"])
81 delete_session(conn, :return_to)
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"])