-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth.ex
97 lines (79 loc) · 2.35 KB
/
oauth.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
defmodule Gamora.OAuth do
@moduledoc """
OAuth2 for Amco.
Add `:client_id` and `:client_secret` to your configuration:
config :ueberauth, Gamora.OAuth,
client_id: System.get_env("AMCO_APP_ID"),
client_secret: System.get_env("AMCO_APP_SECRET")
"""
use OAuth2.Strategy
alias Gamora.Exceptions
@defaults [
strategy: __MODULE__,
token_url: "/oauth2/token",
authorize_url: "/oauth2/authorize"
]
@userinfo_path "/oauth2/userinfo"
@introspect_path "/oauth2/introspect"
@doc """
Construct a client for requests to Amco.
This will be setup automatically for you in `Gamora`.
These options are only useful for usage outside the normal callback phase
of Ueberauth.
"""
def client(opts \\ []) do
config = Application.get_env(:ueberauth, __MODULE__, [])
opts =
@defaults
|> Keyword.merge(config)
|> Keyword.merge(opts)
json_library = Ueberauth.json_library()
unless Keyword.has_key?(opts, :site) do
raise Exceptions.MissingSiteConfiguration
end
opts
|> OAuth2.Client.new()
|> OAuth2.Client.put_serializer("application/json", json_library)
end
def userinfo(access_token, opts \\ []) do
client = client(opts)
data = %{access_token: access_token}
OAuth2.Client.post(client, @userinfo_path, data, [
{"Content-Type", "application/json"}
])
end
def introspect(access_token, opts \\ []) do
client = client(opts)
data =
client
|> Map.take([:client_id, :client_secret])
|> Map.put(:token, access_token)
OAuth2.Client.post(client, @introspect_path, data, [
{"Content-Type", "application/json"}
])
end
@doc """
Provides the authorize url for the request phase of Ueberauth.
No need to call this usually.
"""
def authorize_url!(params \\ [], opts \\ []) do
opts
|> client()
|> OAuth2.Client.authorize_url!(params)
end
def get_access_token(params \\ [], opts \\ []) do
opts
|> client()
|> OAuth2.Client.get_token(params)
end
# Strategy Callbacks
def authorize_url(client, params) do
OAuth2.Strategy.AuthCode.authorize_url(client, params)
end
def get_token(client, params, headers) do
client
|> put_param("client_secret", client.client_secret)
|> put_header("Accept", "application/json")
|> OAuth2.Strategy.AuthCode.get_token(params, headers)
end
end