in dev, allow dev FE
[akkoma] / lib / pleroma / web / plugs / ensure_user_token_assigns_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Plugs.EnsureUserTokenAssignsPlug do
6 import Plug.Conn
7
8 alias Pleroma.Helpers.AuthHelper
9 alias Pleroma.User
10 alias Pleroma.Web.OAuth.Token
11
12 @moduledoc "Ensures presence and consistency of :user and :token assigns."
13
14 def init(opts) do
15 opts
16 end
17
18 def call(%{assigns: %{user: %User{id: user_id}} = assigns} = conn, _) do
19 with %Token{user_id: ^user_id} <- assigns[:token] do
20 conn
21 else
22 %Token{} ->
23 # A safety net for abnormal (unexpected) scenario: :token belongs to another user
24 AuthHelper.drop_auth_info(conn)
25
26 _ ->
27 assign(conn, :token, nil)
28 end
29 end
30
31 # App-bound token case (obtained with client_id and client_secret)
32 def call(%{assigns: %{token: %Token{user_id: nil}}} = conn, _) do
33 assign(conn, :user, nil)
34 end
35
36 def call(conn, _) do
37 conn
38 |> assign(:user, nil)
39 |> assign(:token, nil)
40 end
41 end