Current section

Files

Jump to
spannex lib spannex interceptors auth.ex
Raw

lib/spannex/interceptors/auth.ex

defmodule Spannex.Interceptors.Auth do
@moduledoc """
A gRPC interceptor that adds authentication headers to outgoing requests. Requires `Goth` to fetch the latest auth token.
"""
@behaviour GRPC.Client.Interceptor
@doc """
Requires a `:goth` option that is the name of the `Goth` instance to fetch tokens from.
"""
@impl GRPC.Client.Interceptor
def init(opts), do: Keyword.fetch!(opts, :goth)
@impl GRPC.Client.Interceptor
def call(stream, req, next, goth) do
%{type: type, token: token} = Goth.fetch!(goth)
stream = GRPC.Client.Stream.put_headers(stream, %{"authorization" => "#{type} #{token}"})
next.(stream, req)
end
end