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.Plugs.OAuthPlug do
6 @moduledoc "Performs OAuth authentication by token from params / headers / cookies."
11 alias Pleroma.Helpers.AuthHelper
14 alias Pleroma.Web.OAuth.App
15 alias Pleroma.Web.OAuth.Token
17 @realm_reg Regex.compile!("Bearer\:?\s+(.*)$", "i")
19 def init(options), do: options
21 def call(%{assigns: %{user: %User{}}} = conn, _), do: conn
24 with {:ok, token_str} <- fetch_token_str(conn) do
25 with {:ok, user, user_token} <- fetch_user_and_token(token_str),
26 false <- Token.is_expired?(user_token) do
28 |> assign(:token, user_token)
29 |> assign(:user, user)
32 with {:ok, app, app_token} <- fetch_app_and_token(token_str),
33 false <- Token.is_expired?(app_token) do
35 |> assign(:token, app_token)
48 @spec fetch_user_and_token(String.t()) :: {:ok, User.t(), Token.t()} | nil
49 defp fetch_user_and_token(token) do
52 where: t.token == ^token
55 with %Token{user_id: user_id} = token_record <- Repo.one(token_query),
56 false <- is_nil(user_id),
57 %User{} = user <- User.get_cached_by_id(user_id) do
58 {:ok, user, token_record}
64 @spec fetch_app_and_token(String.t()) :: {:ok, App.t(), Token.t()} | nil
65 defp fetch_app_and_token(token) do
67 from(t in Token, where: t.token == ^token, join: app in assoc(t, :app), preload: [app: app])
69 with %Token{app: app} = token_record <- Repo.one(query) do
70 {:ok, app, token_record}
74 # Gets token string from conn (in params / headers / session)
76 @spec fetch_token_str(Plug.Conn.t() | list(String.t())) :: :no_token_found | {:ok, String.t()}
77 defp fetch_token_str(%Plug.Conn{params: %{"access_token" => access_token}} = _conn) do
81 defp fetch_token_str(%Plug.Conn{} = conn) do
82 headers = get_req_header(conn, "authorization")
84 with {:ok, token} <- fetch_token_str(headers) do
87 _ -> fetch_token_from_session(conn)
91 defp fetch_token_str([token | tail]) do
92 trimmed_token = String.trim(token)
94 case Regex.run(@realm_reg, trimmed_token) do
95 [_, match] -> {:ok, String.trim(match)}
96 _ -> fetch_token_str(tail)
100 defp fetch_token_str([]), do: :no_token_found
102 @spec fetch_token_from_session(Plug.Conn.t()) :: :no_token_found | {:ok, String.t()}
103 defp fetch_token_from_session(conn) do
104 case AuthHelper.get_session_token(conn) do
105 nil -> :no_token_found
106 token -> {:ok, token}