Skip to content

Instantly share code, notes, and snippets.

@g33kidd
Last active December 1, 2015 19:55
Show Gist options
  • Save g33kidd/207fcfae4b7d755c2dc9 to your computer and use it in GitHub Desktop.
Save g33kidd/207fcfae4b7d755c2dc9 to your computer and use it in GitHub Desktop.
custom storage module for OAuth2Ex in Elixir
defmodule StorageUpload.RepoStorage do
@moduledoc """
This is a storage module built based on OAuth2Ex's file storage.
The only difference here is that the token is fetched from the Repo
in the app and stored in the Repo's data store.
"""
alias StorageUpload.Repo
alias StorageUpload.Setting
defstruct module: __MODULE__, key: nil
def save(token, storage) do
map = Map.from_struct(token) |> Map.delete(:storage)
if has_existing_token?(storage) do
token = Repo.get_by!(Setting, key: storage.key)
update_token(token, map, storage)
else
add_token(map, storage)
end
end
def load(storage) do
token = Repo.get_by!(Setting, key: storage.key).val
|> OAuth2Ex.Token.merge_into_struct(%OAuth2Ex.Token{storage: storage})
end
def has_existing_token?(storage) do
if token = Repo.get_by!(Setting, key: storage.key) do
:true
else
:false
end
end
def update_token(token, token_map, storage) do
IO.inspect token_map
IO.inspect token
new_token = %{token | val: token_map}
case Repo.update(new_token) do
{:ok, token} ->
token
{_, error} ->
raise %OAuth2Ex.Error{message: "Could not update token in Repo! Error: #{error}."}
end
end
def add_token(token_map, storage) do
changeset = %Setting{key: storage.key, val: token_map}
case Repo.insert(changeset) do
{:ok, token} ->
token
{_, error} ->
raise %OAuth2Ex.Error{message: "Could not add token to Repo! Error: #{error}."}
end
end
end
config = OAuth2Ex.config(
id: System.get_env("GOOGLE_CLIENT_ID"),
secret: System.get_env("GOOGLE_CLIENT_SECRET"),
authorize_url: "https://accounts.google.com/o/oauth2/auth",
token_url: "https://accounts.google.com/o/oauth2/token",
scope: "https://www.googleapis.com/auth/youtube",
callback_url: System.get_env("GOOGLE_CALLBACK"),
token_store: %StorageUpload.RepoStorage{key: "google_api_token"}
)
# See: https://github.com/parroty/oauth2ex
# on how to use OAuth2Ex. It will work as it did with the default storage module, if you have your Repo, Model, setup.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment