extract get_or_exchange token

This commit is contained in:
FloatingGhost 2022-08-23 18:16:45 +01:00
parent dafdadfb72
commit 4c89219fb8
3 changed files with 12 additions and 26 deletions

View File

@ -22,21 +22,13 @@ defmodule Pleroma.Web.MastodonAPI.AuthController do
@local_mastodon_name "Mastodon-Local"
defp get_or_exchange_token(%Authorization{} = auth, %App{} = app, %User{} = user) do
if auth.used do
Token.get_preeexisting_by_app_and_user(app, user)
else
Token.exchange_token(app, auth)
end
end
@doc "GET /web/login"
# Local Mastodon FE login callback action
def login(conn, %{"code" => auth_token} = params) do
with {:ok, app} <- local_mastofe_app(),
{:ok, auth} <- Authorization.get_by_token(app, auth_token),
%User{} = user <- User.get_cached_by_id(auth.user_id),
{:ok, oauth_token} <- get_or_exchange_token(auth, app, user) do
{:ok, oauth_token} <- Token.get_or_exchange_token(auth, app, user) do
redirect_to =
conn
|> local_mastodon_post_login_path()

View File

@ -291,23 +291,9 @@ defmodule Pleroma.Web.OAuth.OAuthController do
with {:ok, app} <- Token.Utils.fetch_app(conn),
fixed_token = Token.Utils.fix_padding(params["code"]),
{:ok, auth} <- Authorization.get_by_token(app, fixed_token),
%User{} = user <- User.get_cached_by_id(auth.user_id) do
if auth.used do
# reuse token, we already have a valid one
with {:ok, token} <- Token.get_preeexisting_by_app_and_user(app, user) do
after_token_exchange(conn, %{user: user, token: token})
else
error ->
handle_token_exchange_error(conn, error)
end
else
with {:ok, token} <- Token.exchange_token(app, auth) do
after_token_exchange(conn, %{user: user, token: token})
else
error ->
handle_token_exchange_error(conn, error)
end
end
%User{} = user <- User.get_cached_by_id(auth.user_id),
{:ok, token} <- Token.get_or_exchange_token(auth, app, user) do
after_token_exchange(conn, %{user: user, token: token})
else
error ->
handle_token_exchange_error(conn, error)

View File

@ -96,6 +96,14 @@ defmodule Pleroma.Web.OAuth.Token do
|> unique_constraint(:refresh_token)
end
def get_or_exchange_token(%Authorization{} = auth, %App{} = app, %User{} = user) do
if auth.used do
get_preeexisting_by_app_and_user(app, user)
else
exchange_token(app, auth)
end
end
defp put_valid_until(changeset, attrs) do
valid_until =
Map.get(attrs, :valid_until, NaiveDateTime.add(NaiveDateTime.utc_now(), lifespan()))