-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
base.ex
77 lines (62 loc) · 2.07 KB
/
base.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
defmodule Assent.Strategy.OAuth2.Base do
@moduledoc """
OAuth 2.0 strategy base.
## Usage
defmodule MyApp.MyOAuth2Strategy do
use Assent.Strategy.OAuth2.Base
def default_config(_config) do
[
site: "https://api.example.com",
user_url: "/authorization.json"
]
end
@impl true
def normalize(_config, user) do
{:ok, %{
"sub" => user["id"],
"name" => user["name"],
"email" => user["email"]
}}
end
end
"""
alias Assent.Strategy, as: Helpers
alias Assent.Strategy.OAuth2
@callback default_config(Keyword.t()) :: Keyword.t()
@callback normalize(Keyword.t(), map()) :: {:ok, map()} | {:ok, map(), map()} | {:error, term()}
@callback get_user(Keyword.t(), map()) :: {:ok, map()} | {:error, term()}
@doc false
defmacro __using__(_opts) do
quote do
@behaviour Assent.Strategy
@behaviour unquote(__MODULE__)
alias Assent.Strategy, as: Helpers
@impl Assent.Strategy
def authorize_url(config), do: unquote(__MODULE__).authorize_url(config, __MODULE__)
@impl Assent.Strategy
def callback(config, params), do: unquote(__MODULE__).callback(config, params, __MODULE__)
@impl unquote(__MODULE__)
def get_user(config, token), do: OAuth2.get_user(config, token)
defoverridable unquote(__MODULE__)
end
end
@spec authorize_url(Keyword.t(), module()) :: {:ok, %{session_params: %{state: binary()}, url: binary()}}
def authorize_url(config, strategy) do
config
|> set_config(strategy)
|> OAuth2.authorize_url()
end
@spec callback(Keyword.t(), map(), module()) :: {:ok, %{user: map()}} | {:error, term()}
def callback(config, params, strategy) do
config = set_config(config, strategy)
config
|> OAuth2.callback(params, strategy)
|> Helpers.__normalize__(config, strategy)
end
defp set_config(config, strategy) do
config
|> strategy.default_config()
|> Keyword.merge(config)
|> Keyword.put(:strategy, strategy)
end
end