summaryrefslogtreecommitdiff
path: root/lib/pleroma/web/plugs/cookie_auth_plug.ex
blob: dd5153cd4e2f1688696bf1950db7a1fcf2d446e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.Plugs.CookieAuthPlug do
  alias Pleroma.User
  import Plug.Conn

  def init(opts) do
    opts
  end

  # If the user is already assigned (by a bearer token, probably), skip ahead.
  def call(%{assigns: %{user: _}} = conn, _), do: conn

  # Authenticate with a session cookie, if available.
  # For staticly-rendered pages (like the OAuth form)
  # this is the only way it can authenticate.
  def call(conn, _) do
    with user_id <- get_session(conn, :user_id),
         true <- is_binary(user_id),
         %User{} = user <- User.get_by_id(user_id) do
      assign(conn, :user, user)
    else
      _ -> conn
    end
  end
end