Skip to content

Commit

Permalink
clean up package (#66)
Browse files Browse the repository at this point in the history
- separate the genserver from the behavior
- add unit testing for token sweeper
- ran mix format
- fix hex.pm files
- add extra configs for docs
  • Loading branch information
yordis authored and doomspork committed Nov 28, 2017
1 parent 99a5cbc commit e338bdb
Show file tree
Hide file tree
Showing 13 changed files with 216 additions and 151 deletions.
3 changes: 3 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[
inputs: ["mix.exs", "{config,lib,test,priv}/**/*.{ex,exs}"]
]
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ run `mix guardian_db.gen.migration` to generate a migration.
sweep_interval: 60 # default: 60 minutes
```

To sweep expired tokens from your db you should add `Guardian.DB.ExpiredSweeper` to your supervision tree.
To sweep expired tokens from your db you should add `Guardian.DB.Token.SweeperServer` to your supervision tree.

```elixir
worker(Guardian.DB.ExpiredSweeper, [])
worker(Guardian.DB.Token.SweeperServer, [])
```

`Guardian.DB` works by hooking into the lifecycle of your token module.
Expand Down
4 changes: 1 addition & 3 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ use Mix.Config

config :guardian, Guardian.DB,
issuer: "GuardianDB",
secret_key: "HcdlxxmyDRvfrwdpjUPh2M8mWP+KtpOQK1g6fT5SHrnflSY8KiWeORqN6IZSJYTA"

config :guardian, Guardian.DB,
secret_key: "HcdlxxmyDRvfrwdpjUPh2M8mWP+KtpOQK1g6fT5SHrnflSY8KiWeORqN6IZSJYTA",
repo: Guardian.DB.Test.Repo

config :guardian_db, ecto_repos: [Guardian.DB.Test.Repo]
Expand Down
19 changes: 9 additions & 10 deletions lib/guardian/db.ex
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,14 @@ defmodule Guardian.DB do
```elixir
create table(:guardian_tokens, primary_key: false) do
add :jti, :string, primary_key: true
add :typ, :string
add :aud, :string
add :iss, :string
add :sub, :string
add :exp, :bigint
add :jwt, :text
add :claims, :map
add(:jti, :string, primary_key: true)
add(:typ, :string)
add(:aud, :string)
add(:iss, :string)
add(:sub, :string)
add(:exp, :bigint)
add(:jwt, :text)
add(:claims, :map)
timestamps()
end
```
Expand Down Expand Up @@ -119,7 +118,7 @@ defmodule Guardian.DB do
After the JWT is generated, stores the various fields of it in the DB for tracking
"""
def after_encode_and_sign(resource, type, claims, jwt) do
case Token.create!(claims, jwt) do
case Token.create(claims, jwt) do
{:error, _} -> {:error, :token_storage_failure}
_ -> {:ok, {resource, type, claims, jwt}}
end
Expand Down
88 changes: 0 additions & 88 deletions lib/guardian/db/expired_sweeper.ex

This file was deleted.

6 changes: 4 additions & 2 deletions lib/guardian/db/token.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ defmodule Guardian.DB.Token do
@doc """
Create a new new token based on the JWT and decoded claims
"""
def create!(claims, jwt) do
def create(claims, jwt) do
prepared_claims =
claims
|> Map.put("jwt", jwt)
Expand All @@ -52,18 +52,20 @@ defmodule Guardian.DB.Token do
@doc """
Purge any tokens that are expired. This should be done periodically to keep your DB table clean of clutter
"""
def purge_expired_tokens! do
def purge_expired_tokens do
timestamp = Guardian.timestamp()

query_schema()
|> where([token], token.exp < ^timestamp)
|> Guardian.DB.repo().delete_all()
end

@doc false
def query_schema do
{schema_name(), Token}
end

@doc false
def schema_name do
:guardian
|> Application.fetch_env!(Guardian.DB)
Expand Down
44 changes: 44 additions & 0 deletions lib/guardian/db/token/sweeper.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
defmodule Guardian.DB.Token.Sweeper do
@moduledoc """
Purges and schedule work for cleaning up expired tokens.
"""

alias Guardian.DB.Token

@doc """
Purges the expired tokens and schedule the next purge.
"""
def sweep(pid, state) do
Token.purge_expired_tokens()
schedule_work(pid, state)
end

@doc """
Schedule the next purge.
"""
def schedule_work(pid, state) do
if state[:timer] do
Process.cancel_timer(state.timer)
end

timer = Process.send_after(pid, :sweep, state[:interval])
Map.merge(state, %{timer: timer})
end

@doc false
def get_interval do
:guardian
|> Application.get_env(Guardian.DB)
|> Keyword.get(:sweep_interval, 60)
|> minute_to_ms()
end

defp minute_to_ms(value) when is_binary(value) do
value
|> String.to_integer()
|> minute_to_ms()
end

defp minute_to_ms(value) when value < 1, do: 1000
defp minute_to_ms(value), do: round(value * 60 * 1000)
end
58 changes: 58 additions & 0 deletions lib/guardian/db/token/sweeper_server.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
defmodule Guardian.DB.Token.SweeperServer do
@moduledoc """
Periocially purges expired tokens from the DB.
## Example
config :guardian, Guardian.DB,
sweep_interval: 60 # 1 hour
# in your supervisor
worker(Guardian.DB.Token.SweeperServer, [])
"""

use GenServer
alias Guardian.DB.Token.Sweeper

def start_link(opts \\ []) do
defaults = %{
interval: Sweeper.get_interval()
}

state = Enum.into(opts, defaults)

GenServer.start_link(__MODULE__, state, name: __MODULE__)
end

@doc """
Reset the purge timer.
"""
def reset_timer do
GenServer.call(__MODULE__, :reset_timer)
end

@doc """
Manually trigger a database purge of expired tokens. Also resets the current
scheduled work.
"""
def purge do
GenServer.call(__MODULE__, :sweep)
end

def init(state) do
{:ok, Sweeper.schedule_work(self(), state)}
end

def handle_call(:reset_timer, _from, state) do
{:reply, :ok, Sweeper.schedule_work(self(), state)}
end

def handle_call(:sweep, _from, state) do
{:reply, :ok, Sweeper.sweep(self(), state)}
end

def handle_info(:sweep, state) do
{:noreply, Sweeper.sweep(self(), state)}
end

def handle_info(_, state), do: {:noreply, state}
end
64 changes: 44 additions & 20 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,70 @@ defmodule Guardian.DB.Mixfile do
use Mix.Project

@version "1.0.0"
@source_url "https://github.com/ueberauth/guardian_db"

def project do
[app: :guardian_db,
version: @version,
description: "DB tracking for token validity",
elixir: "~> 1.4 or ~> 1.5",
elixirc_paths: elixirc_paths(Mix.env),
package: package(),
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
preferred_cli_env: [guardian_db: :test],
aliases: aliases(),
deps: deps()]
[
name: "Guardian.DB",
app: :guardian_db,
version: @version,
description: "DB tracking for token validity",
elixir: "~> 1.4 or ~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
package: package(),
docs: docs(),
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
preferred_cli_env: [guardian_db: :test],
aliases: aliases(),
deps: deps()
]
end

def application do
[extra_applications: [:logger]]
end

defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp elixirc_paths(_), do: ["lib"]

defp deps do
[{:guardian, "~> 1.0"},
{:ecto, "~> 2.2"},
{:postgrex, "~> 0.13", optional: true},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:credo, ">= 0.0.0", only: [:dev, :test], runtime: false}]
[
{:guardian, "~> 1.0"},
{:ecto, "~> 2.2"},
{:postgrex, "~> 0.13", optional: true},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:credo, ">= 0.0.0", only: [:dev, :test], runtime: false}
]
end

defp package do
[
maintainers: ["Daniel Neighman", "Sean Callan", "Sonny Scroggin"],
licenses: ["MIT"],
links: %{github: "https://github.com/hassox/guardian_db"},
files: ~w(lib) ++ ~w(CHANGELOG.md LICENSE mix.exs README.md)
links: %{GitHub: @source_url},
files: [
"lib",
"CHANGELOG.md",
"LICENSE",
"mix.exs",
"README.md",
"priv/templates"
]
]
end

defp docs do
[
main: "readme",
homepage_url: @source_url,
source_ref: "v#{@version}",
source_url: @source_url,
extras: ["README.md"]
]
end

defp aliases do
["test": ["ecto.create --quiet", "ecto.migrate", "test"]]
[test: ["ecto.create --quiet", "ecto.migrate", "test"]]
end
end
Loading

0 comments on commit e338bdb

Please sign in to comment.