First
[anni] / lib / pleroma / web / plugs / ensure_public_or_authenticated_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug do
6   @moduledoc """
7   Ensures instance publicity or _user_ authentication
8   (app-bound user-unbound tokens are accepted only if the instance is public).
9   """
10
11   import Pleroma.Web.TranslationHelpers
12   import Plug.Conn
13
14   alias Pleroma.Config
15   alias Pleroma.User
16
17   use Pleroma.Web, :plug
18
19   def init(options) do
20     options
21   end
22
23   @impl true
24   def perform(conn, _) do
25     public? = Config.get!([:instance, :public])
26
27     case {public?, conn} do
28       {true, _} ->
29         conn
30
31       {false, %{assigns: %{user: %User{}}}} ->
32         conn
33
34       {false, _} ->
35         conn
36         |> render_error(:forbidden, "This resource requires authentication.")
37         |> halt
38     end
39   end
40 end