reuse token where we have one

This commit is contained in:
FloatingGhost 2022-08-23 12:57:18 +01:00
parent 7963dcf3c5
commit 1b2a95429b
4 changed files with 16 additions and 4 deletions

View file

@ -94,4 +94,9 @@ def get_by_token(%App{id: app_id} = _app, token) do
from(t in __MODULE__, where: t.app_id == ^app_id and t.token == ^token)
|> Repo.find_resource()
end
def get_preeexisting_by_app_and_user(%App{id: app_id} = _app, %User{id: user_id} = _user) do
from(t in __MODULE__, where: t.app_id == ^app_id and t.user_id == ^user_id, limit: 1)
|> Repo.find_resource()
end
end

View file

@ -77,10 +77,12 @@ def authorize(%Plug.Conn{} = conn, params) do
false <- is_nil(user_id),
%User{} = user <- User.get_cached_by_id(user_id),
%App{} = app <- Repo.get_by(App, client_id: params["client_id"]),
{:ok, %Token{} = token} <- Token.get_preeexisting_by_app_and_user(app, user) do
{:ok, %Token{} = token} <- Token.get_preeexisting_by_app_and_user(app, user),
{:ok, %Authorization{} = auth} <- Authorization.get_preeexisting_by_app_and_user(app, user) do
IO.inspect(params)
conn
|> assign(:token, token)
|> handle_existing_authorization(params)
|> after_create_authorization(auth, %{"authorization" => params})
else
_ -> do_authorize(conn, params)
end
@ -281,11 +283,11 @@ def token_exchange(
end
def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "authorization_code"} = params) do
with {:ok, app} <- Token.Utils.fetch_app(conn),
with {:ok, app} <- IO.inspect(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),
{:ok, token} <- Token.exchange_token(app, auth) do
{:ok, token} <- IO.inspect(Token.exchange_token(app, auth)) do
after_token_exchange(conn, %{user: user, token: token})
else
error ->

View file

@ -75,6 +75,7 @@ def get_preeexisting_by_app_and_user(app, user) do
|> Query.get_by_user(user.id)
|> Query.get_unexpired()
|> Query.preload([:user])
|> Query.sort_by_inserted_at()
|> Query.limit(1)
|> Repo.find_resource()
end

View file

@ -47,6 +47,10 @@ def limit(query, limit) do
from(q in query, limit: ^limit)
end
def sort_by_inserted_at(query) do
from(q in query, order_by: [desc: :updated_at])
end
@spec preload(query, any) :: query
def preload(query \\ Token, assoc_preload \\ [])