Wrap error messages into gettext helpers
[akkoma] / lib / pleroma / plugs / oauth_scopes_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Plugs.OAuthScopesPlug do
6 import Plug.Conn
7 import Pleroma.Web.Gettext
8
9 @behaviour Plug
10
11 def init(%{scopes: _} = options), do: options
12
13 def call(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
14 op = options[:op] || :|
15 token = assigns[:token]
16
17 cond do
18 is_nil(token) ->
19 conn
20
21 op == :| && scopes -- token.scopes != scopes ->
22 conn
23
24 op == :& && scopes -- token.scopes == [] ->
25 conn
26
27 options[:fallback] == :proceed_unauthenticated ->
28 conn
29 |> assign(:user, nil)
30 |> assign(:token, nil)
31
32 true ->
33 missing_scopes = scopes -- token.scopes
34 permissions = Enum.join(missing_scopes, " #{op} ")
35
36 error_message =
37 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
38
39 conn
40 |> put_resp_content_type("application/json")
41 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
42 |> halt()
43 end
44 end
45 end