-
Notifications
You must be signed in to change notification settings - Fork 86
/
ecto_adapter.ex
81 lines (62 loc) · 1.76 KB
/
ecto_adapter.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
defmodule Guardian.DB.EctoAdapter do
@moduledoc """
Implement the Guardian.DB.Adapter for Ecto.Repo
"""
import Ecto.Query
alias Guardian.DB.Token
@behaviour Guardian.DB.Adapter
@default_schema_name "guardian_tokens"
@impl true
def one(claims, opts) do
prefix = Keyword.get(opts, :prefix, nil)
repo = Keyword.get(opts, :repo)
jti = Map.get(claims, "jti")
aud = Map.get(claims, "aud")
opts
|> query_schema()
|> where([token], token.jti == ^jti and token.aud == ^aud)
|> repo.one(prefix: prefix)
end
@impl true
def insert(changeset, opts) do
prefix = Keyword.get(opts, :prefix, nil)
repo = Keyword.get(opts, :repo)
data =
changeset
|> Map.get(:data)
|> Ecto.put_meta(source: schema_name(opts))
|> Ecto.put_meta(prefix: prefix)
changeset = %{changeset | data: data}
repo.insert(changeset, prefix: prefix)
end
@impl true
def delete(record, opts) do
prefix = Keyword.get(opts, :prefix, nil)
repo = Keyword.get(opts, :repo)
repo.delete(record, prefix: prefix, stale_error_field: :stale_token)
end
@impl true
def delete_by_sub(sub, opts) do
prefix = Keyword.get(opts, :prefix, nil)
repo = Keyword.get(opts, :repo)
opts
|> query_schema()
|> where([token], token.sub == ^sub)
|> repo.delete_all(prefix: prefix)
end
@impl true
def purge_expired_tokens(timestamp, opts) do
prefix = Keyword.get(opts, :prefix, nil)
repo = Keyword.get(opts, :repo)
opts
|> query_schema()
|> where([token], token.exp < ^timestamp)
|> repo.delete_all(prefix: prefix)
end
defp query_schema(opts) do
{schema_name(opts), Token}
end
defp schema_name(opts) do
Keyword.get(opts, :schema_name, @default_schema_name)
end
end