1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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
8 import Pleroma.Web.ControllerHelper, only: [json_response: 3]
10 alias Pleroma.Helpers.AuthHelper
11 alias Pleroma.Helpers.UriHelper
13 alias Pleroma.Web.OAuth.App
14 alias Pleroma.Web.OAuth.Authorization
15 alias Pleroma.Web.OAuth.Token
16 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
17 alias Pleroma.Web.TwitterAPI.TwitterAPI
19 action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
21 plug(Pleroma.Web.Plugs.RateLimiter, [name: :password_reset] when action == :password_reset)
23 @local_mastodon_name "Mastodon-Local"
26 # Local Mastodon FE login callback action
27 def login(conn, %{"code" => auth_token} = params) do
28 with {:ok, app} <- local_mastofe_app(),
29 {:ok, auth} <- Authorization.get_by_token(app, auth_token),
30 {:ok, oauth_token} <- Token.exchange_token(app, auth) do
33 |> local_mastodon_post_login_path()
34 |> UriHelper.modify_uri_params(%{"access_token" => oauth_token.token})
37 |> AuthHelper.put_session_token(oauth_token.token)
38 |> redirect(to: redirect_to)
40 _ -> redirect_to_oauth_form(conn, params)
44 def login(conn, params) do
45 with %{assigns: %{user: %User{}, token: %Token{app_id: app_id}}} <- conn,
46 {:ok, %{id: ^app_id}} <- local_mastofe_app() do
47 redirect(conn, to: local_mastodon_post_login_path(conn))
49 _ -> redirect_to_oauth_form(conn, params)
53 defp redirect_to_oauth_form(conn, _params) do
54 with {:ok, app} <- local_mastofe_app() do
56 Routes.o_auth_path(conn, :authorize,
57 response_type: "code",
58 client_id: app.client_id,
60 scope: Enum.join(app.scopes, " ")
63 redirect(conn, to: path)
67 @doc "DELETE /auth/sign_out"
68 def logout(conn, _) do
70 with %{assigns: %{token: %Token{} = oauth_token}} <- conn,
71 session_token = AuthHelper.get_session_token(conn),
72 {:ok, %Token{token: ^session_token}} <- RevokeToken.revoke(oauth_token) do
73 AuthHelper.delete_session_token(conn)
78 redirect(conn, to: "/")
81 @doc "POST /auth/password"
82 def password_reset(conn, params) do
83 nickname_or_email = params["email"] || params["nickname"]
85 TwitterAPI.password_reset(nickname_or_email)
87 json_response(conn, :no_content, "")
90 defp local_mastodon_post_login_path(conn) do
91 case get_session(conn, :return_to) do
93 Routes.masto_fe_path(conn, :index, ["getting-started"])
96 delete_session(conn, :return_to)
101 @spec local_mastofe_app() :: {:ok, App.t()} | {:error, Ecto.Changeset.t()}
102 def local_mastofe_app do
104 %{client_name: @local_mastodon_name, redirect_uris: "."},
105 ["read", "write", "follow", "push", "admin"]