Guardian db not inserting record into database

341 views Asked by At

My mix file contains

{:guardian, "~> 1.0"},
{:guardian_db, "~> 1.1"},

and config contains

config :my_app, MyApp.Guardian,
   issuer: "my_app",
   ttl: {30, :days},
   allowed_drift: 2000,
   verify_issuer: true,

  #  mix guardian.gen.secret (to get a key for dev and prod envs)
   secret_key: "yKwVGXFyH6nbiE+ELRMLYjCDC3QughF02LN+xPlB7z2loDKeNuBJ6RIUdTMBul23"

config :guardian, Guardian.DB,
   repo: Qserv.BaseRepo,
   schema_name: "sessions", # default
   token_types: ["refresh_token"], # store all token types if not set
   sweep_interval: 60

and my application has this line

worker(Guardian.DB.Token.SweeperServer, []),

and My migration for sessions table

defmodule MyApp.Repo.Migrations.CreateTable.Auth.Sessions do
  use Ecto.Migration

  @table :sessions

  def change do
    create table(@table, primary_key: false) do
      add :jti, :string, primary_key: true
      add :aud, :string, primary_key: true
      add :typ, :string
      add :iss, :string
      add :sub, :string
      add :exp, :bigint
      add :jwt, :text
      add :claims, :map
      timestamps()
    end

    create index(@table, [:jwt])
    create index(@table, [:sub])
    create index(@table, [:jti])
  end
end

and I have this file

defmodule MyApp.Guardian do
  use Guardian, otp_app: :my_app

  def subject_for_token(resource, _claims) do
    sub = to_string(resource.id)
    {:ok, sub}
  end
  def subject_for_token(_, _) do
    {:error, :reason_for_error}
  end

  def resource_from_claims(claims) do
    resource = %{id: 1}
    {:ok,  resource}
  end

  def resource_from_claims(_claims) do
    {:error, :reason_for_error}
  end

  def after_encode_and_sign(resource, claims, token, _options) do
    with {:ok, _} <- Guardian.DB.after_encode_and_sign(resource, claims["typ"], claims, token) do
      {:ok, token}
    else whatever ->
      IO.inspect whatever

    end
  end

  def on_verify(claims, token, _options) do
    with {:ok, _} <- Guardian.DB.on_verify(claims, token) do
      {:ok, claims}
    end
  end

  def on_revoke(claims, token, _options) do
    with {:ok, _} <- Guardian.DB.on_revoke(claims, token) do
      {:ok, claims}
    end
  end
end

Everything works great and I am able to login and get token successfully except that guardian db is unable to insert record into database. I login like this

MyApp.Guardian.encode_and_sign(%{id: 1}, %{key: :value}, token_type: "cus")

I also got printed after_encode_and_sign, resource and claims correctly guardian db hooks, but token details not being inserted into database. What might be wrong here

1

There are 1 answers

0
Ooba Elda On BEST ANSWER

In the configuration you specified token_types: ["refresh_token"].

By calling Guardian.encode you create access token that's why nothing is persisted in database.

To persist all types of tokens remove this line.